babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881
  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 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 = Vector3.Normalize(axis1);
  870. var w = Vector3.Normalize(axis3);
  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;
  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;
  890. var v1;
  891. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  892. z = 1.0;
  893. }
  894. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  895. x = 1.0;
  896. }
  897. else {
  898. t = w.z / w.x;
  899. x = -t * Math.sqrt(1 / (1 + t * t));
  900. z = Math.sqrt(1 / (1 + t * t));
  901. }
  902. u1 = new Vector3(x, y, z);
  903. u1.normalize();
  904. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  905. v1.normalize();
  906. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  907. cross.normalize();
  908. if (Vector3.Dot(w, cross) < 0) {
  909. sign = 1.0;
  910. }
  911. dot = Vector3.Dot(u, u1);
  912. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  913. roll = Math.acos(dot) * sign;
  914. if (Vector3.Dot(u1, X) < 0) {
  915. roll = Math.PI + roll;
  916. u1 = u1.scaleInPlace(-1);
  917. v1 = v1.scaleInPlace(-1);
  918. nbRevert++;
  919. }
  920. // step 2 : rotate around u1
  921. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  922. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  923. var w2;
  924. var v2;
  925. x = 0.0;
  926. y = 0.0;
  927. z = 0.0;
  928. sign = -1;
  929. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  930. x = 1.0;
  931. }
  932. else {
  933. t = u1.z / u1.x;
  934. x = -t * Math.sqrt(1 / (1 + t * t));
  935. z = Math.sqrt(1 / (1 + t * t));
  936. }
  937. w2 = new Vector3(x, y, z);
  938. w2.normalize();
  939. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. cross = Vector3.Cross(w, w2); // 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. v2 = v2.scaleInPlace(-1);
  952. w2 = w2.scaleInPlace(-1);
  953. nbRevert++;
  954. }
  955. // step 3 : rotate around v2
  956. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  957. sign = -1;
  958. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  959. cross.normalize();
  960. if (Vector3.Dot(cross, Y) < 0) {
  961. sign = 1.0;
  962. }
  963. dot = Vector3.Dot(u1, X);
  964. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  965. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  966. if (dot < 0 && nbRevert < 2) {
  967. yaw = Math.PI + yaw;
  968. }
  969. ref.x = pitch;
  970. ref.y = yaw;
  971. ref.z = roll;
  972. };
  973. return Vector3;
  974. })();
  975. BABYLON.Vector3 = Vector3;
  976. //Vector4 class created for EulerAngle class conversion to Quaternion
  977. var Vector4 = (function () {
  978. function Vector4(x, y, z, w) {
  979. this.x = x;
  980. this.y = y;
  981. this.z = z;
  982. this.w = w;
  983. }
  984. Vector4.prototype.toString = function () {
  985. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  986. };
  987. // Operators
  988. Vector4.prototype.asArray = function () {
  989. var result = [];
  990. this.toArray(result, 0);
  991. return result;
  992. };
  993. Vector4.prototype.toArray = function (array, index) {
  994. if (index === undefined) {
  995. index = 0;
  996. }
  997. array[index] = this.x;
  998. array[index + 1] = this.y;
  999. array[index + 2] = this.z;
  1000. array[index + 3] = this.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.addInPlace = function (otherVector) {
  1004. this.x += otherVector.x;
  1005. this.y += otherVector.y;
  1006. this.z += otherVector.z;
  1007. this.w += otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.add = function (otherVector) {
  1011. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1012. };
  1013. Vector4.prototype.addToRef = function (otherVector, result) {
  1014. result.x = this.x + otherVector.x;
  1015. result.y = this.y + otherVector.y;
  1016. result.z = this.z + otherVector.z;
  1017. result.w = this.w + otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractInPlace = function (otherVector) {
  1021. this.x -= otherVector.x;
  1022. this.y -= otherVector.y;
  1023. this.z -= otherVector.z;
  1024. this.w -= otherVector.w;
  1025. return this;
  1026. };
  1027. Vector4.prototype.subtract = function (otherVector) {
  1028. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1029. };
  1030. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1031. result.x = this.x - otherVector.x;
  1032. result.y = this.y - otherVector.y;
  1033. result.z = this.z - otherVector.z;
  1034. result.w = this.w - otherVector.w;
  1035. return this;
  1036. };
  1037. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1038. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1039. };
  1040. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1041. result.x = this.x - x;
  1042. result.y = this.y - y;
  1043. result.z = this.z - z;
  1044. result.w = this.w - w;
  1045. return this;
  1046. };
  1047. Vector4.prototype.negate = function () {
  1048. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1049. };
  1050. Vector4.prototype.scaleInPlace = function (scale) {
  1051. this.x *= scale;
  1052. this.y *= scale;
  1053. this.z *= scale;
  1054. this.w *= scale;
  1055. return this;
  1056. };
  1057. Vector4.prototype.scale = function (scale) {
  1058. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1059. };
  1060. Vector4.prototype.scaleToRef = function (scale, result) {
  1061. result.x = this.x * scale;
  1062. result.y = this.y * scale;
  1063. result.z = this.z * scale;
  1064. result.w = this.w * scale;
  1065. };
  1066. Vector4.prototype.equals = function (otherVector) {
  1067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1068. };
  1069. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1070. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1071. return otherVector
  1072. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1074. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1075. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1076. };
  1077. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1078. return this.x === x && this.y === y && this.z === z && this.w === w;
  1079. };
  1080. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1081. this.x *= otherVector.x;
  1082. this.y *= otherVector.y;
  1083. this.z *= otherVector.z;
  1084. this.w *= otherVector.w;
  1085. return this;
  1086. };
  1087. Vector4.prototype.multiply = function (otherVector) {
  1088. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1089. };
  1090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1091. result.x = this.x * otherVector.x;
  1092. result.y = this.y * otherVector.y;
  1093. result.z = this.z * otherVector.z;
  1094. result.w = this.w * otherVector.w;
  1095. return this;
  1096. };
  1097. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1098. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1099. };
  1100. Vector4.prototype.divide = function (otherVector) {
  1101. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1102. };
  1103. Vector4.prototype.divideToRef = function (otherVector, result) {
  1104. result.x = this.x / otherVector.x;
  1105. result.y = this.y / otherVector.y;
  1106. result.z = this.z / otherVector.z;
  1107. result.w = this.w / otherVector.w;
  1108. return this;
  1109. };
  1110. Vector4.prototype.MinimizeInPlace = function (other) {
  1111. if (other.x < this.x)
  1112. this.x = other.x;
  1113. if (other.y < this.y)
  1114. this.y = other.y;
  1115. if (other.z < this.z)
  1116. this.z = other.z;
  1117. if (other.w < this.w)
  1118. this.w = other.w;
  1119. return this;
  1120. };
  1121. Vector4.prototype.MaximizeInPlace = function (other) {
  1122. if (other.x > this.x)
  1123. this.x = other.x;
  1124. if (other.y > this.y)
  1125. this.y = other.y;
  1126. if (other.z > this.z)
  1127. this.z = other.z;
  1128. if (other.w > this.w)
  1129. this.w = other.w;
  1130. return this;
  1131. };
  1132. // Properties
  1133. Vector4.prototype.length = function () {
  1134. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1135. };
  1136. Vector4.prototype.lengthSquared = function () {
  1137. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1138. };
  1139. // Methods
  1140. Vector4.prototype.normalize = function () {
  1141. var len = this.length();
  1142. if (len === 0)
  1143. return this;
  1144. var num = 1.0 / len;
  1145. this.x *= num;
  1146. this.y *= num;
  1147. this.z *= num;
  1148. this.w *= num;
  1149. return this;
  1150. };
  1151. Vector4.prototype.clone = function () {
  1152. return new Vector4(this.x, this.y, this.z, this.w);
  1153. };
  1154. Vector4.prototype.copyFrom = function (source) {
  1155. this.x = source.x;
  1156. this.y = source.y;
  1157. this.z = source.z;
  1158. this.w = source.w;
  1159. return this;
  1160. };
  1161. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1162. this.x = x;
  1163. this.y = y;
  1164. this.z = z;
  1165. this.w = w;
  1166. return this;
  1167. };
  1168. // Statics
  1169. Vector4.FromArray = function (array, offset) {
  1170. if (!offset) {
  1171. offset = 0;
  1172. }
  1173. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1174. };
  1175. Vector4.FromArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1182. result.x = array[offset];
  1183. result.y = array[offset + 1];
  1184. result.z = array[offset + 2];
  1185. result.w = array[offset + 3];
  1186. };
  1187. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1188. result.x = x;
  1189. result.y = y;
  1190. result.z = z;
  1191. result.w = w;
  1192. };
  1193. Vector4.Zero = function () {
  1194. return new Vector4(0, 0, 0, 0);
  1195. };
  1196. Vector4.Normalize = function (vector) {
  1197. var result = Vector4.Zero();
  1198. Vector4.NormalizeToRef(vector, result);
  1199. return result;
  1200. };
  1201. Vector4.NormalizeToRef = function (vector, result) {
  1202. result.copyFrom(vector);
  1203. result.normalize();
  1204. };
  1205. Vector4.Minimize = function (left, right) {
  1206. var min = left.clone();
  1207. min.MinimizeInPlace(right);
  1208. return min;
  1209. };
  1210. Vector4.Maximize = function (left, right) {
  1211. var max = left.clone();
  1212. max.MaximizeInPlace(right);
  1213. return max;
  1214. };
  1215. Vector4.Distance = function (value1, value2) {
  1216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1217. };
  1218. Vector4.DistanceSquared = function (value1, value2) {
  1219. var x = value1.x - value2.x;
  1220. var y = value1.y - value2.y;
  1221. var z = value1.z - value2.z;
  1222. var w = value1.w - value2.w;
  1223. return (x * x) + (y * y) + (z * z) + (w * w);
  1224. };
  1225. Vector4.Center = function (value1, value2) {
  1226. var center = value1.add(value2);
  1227. center.scaleInPlace(0.5);
  1228. return center;
  1229. };
  1230. return Vector4;
  1231. })();
  1232. BABYLON.Vector4 = Vector4;
  1233. var Quaternion = (function () {
  1234. function Quaternion(x, y, z, w) {
  1235. if (x === void 0) { x = 0; }
  1236. if (y === void 0) { y = 0; }
  1237. if (z === void 0) { z = 0; }
  1238. if (w === void 0) { w = 1; }
  1239. this.x = x;
  1240. this.y = y;
  1241. this.z = z;
  1242. this.w = w;
  1243. }
  1244. Quaternion.prototype.toString = function () {
  1245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1246. };
  1247. Quaternion.prototype.asArray = function () {
  1248. return [this.x, this.y, this.z, this.w];
  1249. };
  1250. Quaternion.prototype.equals = function (otherQuaternion) {
  1251. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1252. };
  1253. Quaternion.prototype.clone = function () {
  1254. return new Quaternion(this.x, this.y, this.z, this.w);
  1255. };
  1256. Quaternion.prototype.copyFrom = function (other) {
  1257. this.x = other.x;
  1258. this.y = other.y;
  1259. this.z = other.z;
  1260. this.w = other.w;
  1261. return this;
  1262. };
  1263. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1264. this.x = x;
  1265. this.y = y;
  1266. this.z = z;
  1267. this.w = w;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.add = function (other) {
  1271. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1272. };
  1273. Quaternion.prototype.subtract = function (other) {
  1274. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1275. };
  1276. Quaternion.prototype.scale = function (value) {
  1277. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1278. };
  1279. Quaternion.prototype.multiply = function (q1) {
  1280. var result = new Quaternion(0, 0, 0, 1.0);
  1281. this.multiplyToRef(q1, result);
  1282. return result;
  1283. };
  1284. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1285. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1286. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1287. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1288. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1289. result.copyFromFloats(x, y, z, w);
  1290. return this;
  1291. };
  1292. Quaternion.prototype.multiplyInPlace = function (q1) {
  1293. this.multiplyToRef(q1, this);
  1294. return this;
  1295. };
  1296. Quaternion.prototype.length = function () {
  1297. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1298. };
  1299. Quaternion.prototype.normalize = function () {
  1300. var length = 1.0 / this.length();
  1301. this.x *= length;
  1302. this.y *= length;
  1303. this.z *= length;
  1304. this.w *= length;
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toEulerAngles = function () {
  1308. var result = Vector3.Zero();
  1309. this.toEulerAnglesToRef(result);
  1310. return result;
  1311. };
  1312. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1313. //result is an EulerAngles in the in the z-x-z convention
  1314. var qx = this.x;
  1315. var qy = this.y;
  1316. var qz = this.z;
  1317. var qw = this.w;
  1318. var qxy = qx * qy;
  1319. var qxz = qx * qz;
  1320. var qwy = qw * qy;
  1321. var qwz = qw * qz;
  1322. var qwx = qw * qx;
  1323. var qyz = qy * qz;
  1324. var sqx = qx * qx;
  1325. var sqy = qy * qy;
  1326. var determinant = sqx + sqy;
  1327. if (determinant !== 0.000 && determinant !== 1.000) {
  1328. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1329. result.y = Math.acos(1 - 2 * determinant);
  1330. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1331. }
  1332. else {
  1333. if (determinant === 0.0) {
  1334. result.x = 0.0;
  1335. result.y = 0.0;
  1336. 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)
  1337. }
  1338. else {
  1339. 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)
  1340. result.y = Math.PI;
  1341. result.z = 0.0;
  1342. }
  1343. }
  1344. return this;
  1345. };
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. return Viewport;
  2244. })();
  2245. BABYLON.Viewport = Viewport;
  2246. var Frustum = (function () {
  2247. function Frustum() {
  2248. }
  2249. Frustum.GetPlanes = function (transform) {
  2250. var frustumPlanes = [];
  2251. for (var index = 0; index < 6; index++) {
  2252. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2253. }
  2254. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2255. return frustumPlanes;
  2256. };
  2257. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2258. // Near
  2259. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2260. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2261. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2262. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2263. frustumPlanes[0].normalize();
  2264. // Far
  2265. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2266. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2267. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2268. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2269. frustumPlanes[1].normalize();
  2270. // Left
  2271. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2272. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2273. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2274. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2275. frustumPlanes[2].normalize();
  2276. // Right
  2277. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2278. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2279. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2280. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2281. frustumPlanes[3].normalize();
  2282. // Top
  2283. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2284. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2285. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2286. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2287. frustumPlanes[4].normalize();
  2288. // Bottom
  2289. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2290. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2291. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2292. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2293. frustumPlanes[5].normalize();
  2294. };
  2295. return Frustum;
  2296. })();
  2297. BABYLON.Frustum = Frustum;
  2298. var Ray = (function () {
  2299. function Ray(origin, direction, length) {
  2300. if (length === void 0) { length = Number.MAX_VALUE; }
  2301. this.origin = origin;
  2302. this.direction = direction;
  2303. this.length = length;
  2304. }
  2305. // Methods
  2306. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2307. var d = 0.0;
  2308. var maxValue = Number.MAX_VALUE;
  2309. var inv;
  2310. var min;
  2311. var max;
  2312. var temp;
  2313. if (Math.abs(this.direction.x) < 0.0000001) {
  2314. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2315. return false;
  2316. }
  2317. }
  2318. else {
  2319. inv = 1.0 / this.direction.x;
  2320. min = (minimum.x - this.origin.x) * inv;
  2321. max = (maximum.x - this.origin.x) * inv;
  2322. if (max === -Infinity) {
  2323. max = Infinity;
  2324. }
  2325. if (min > max) {
  2326. temp = min;
  2327. min = max;
  2328. max = temp;
  2329. }
  2330. d = Math.max(min, d);
  2331. maxValue = Math.min(max, maxValue);
  2332. if (d > maxValue) {
  2333. return false;
  2334. }
  2335. }
  2336. if (Math.abs(this.direction.y) < 0.0000001) {
  2337. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2338. return false;
  2339. }
  2340. }
  2341. else {
  2342. inv = 1.0 / this.direction.y;
  2343. min = (minimum.y - this.origin.y) * inv;
  2344. max = (maximum.y - this.origin.y) * inv;
  2345. if (max === -Infinity) {
  2346. max = Infinity;
  2347. }
  2348. if (min > max) {
  2349. temp = min;
  2350. min = max;
  2351. max = temp;
  2352. }
  2353. d = Math.max(min, d);
  2354. maxValue = Math.min(max, maxValue);
  2355. if (d > maxValue) {
  2356. return false;
  2357. }
  2358. }
  2359. if (Math.abs(this.direction.z) < 0.0000001) {
  2360. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2361. return false;
  2362. }
  2363. }
  2364. else {
  2365. inv = 1.0 / this.direction.z;
  2366. min = (minimum.z - this.origin.z) * inv;
  2367. max = (maximum.z - this.origin.z) * inv;
  2368. if (max === -Infinity) {
  2369. max = Infinity;
  2370. }
  2371. if (min > max) {
  2372. temp = min;
  2373. min = max;
  2374. max = temp;
  2375. }
  2376. d = Math.max(min, d);
  2377. maxValue = Math.min(max, maxValue);
  2378. if (d > maxValue) {
  2379. return false;
  2380. }
  2381. }
  2382. return true;
  2383. };
  2384. Ray.prototype.intersectsBox = function (box) {
  2385. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2386. };
  2387. Ray.prototype.intersectsSphere = function (sphere) {
  2388. var x = sphere.center.x - this.origin.x;
  2389. var y = sphere.center.y - this.origin.y;
  2390. var z = sphere.center.z - this.origin.z;
  2391. var pyth = (x * x) + (y * y) + (z * z);
  2392. var rr = sphere.radius * sphere.radius;
  2393. if (pyth <= rr) {
  2394. return true;
  2395. }
  2396. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2397. if (dot < 0.0) {
  2398. return false;
  2399. }
  2400. var temp = pyth - (dot * dot);
  2401. return temp <= rr;
  2402. };
  2403. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2404. if (!this._edge1) {
  2405. this._edge1 = Vector3.Zero();
  2406. this._edge2 = Vector3.Zero();
  2407. this._pvec = Vector3.Zero();
  2408. this._tvec = Vector3.Zero();
  2409. this._qvec = Vector3.Zero();
  2410. }
  2411. vertex1.subtractToRef(vertex0, this._edge1);
  2412. vertex2.subtractToRef(vertex0, this._edge2);
  2413. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2414. var det = Vector3.Dot(this._edge1, this._pvec);
  2415. if (det === 0) {
  2416. return null;
  2417. }
  2418. var invdet = 1 / det;
  2419. this.origin.subtractToRef(vertex0, this._tvec);
  2420. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2421. if (bu < 0 || bu > 1.0) {
  2422. return null;
  2423. }
  2424. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2425. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2426. if (bv < 0 || bu + bv > 1.0) {
  2427. return null;
  2428. }
  2429. //check if the distance is longer than the predefined length.
  2430. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2431. if (distance > this.length) {
  2432. return null;
  2433. }
  2434. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2435. };
  2436. // Statics
  2437. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2438. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2439. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2440. var direction = end.subtract(start);
  2441. direction.normalize();
  2442. return new Ray(start, direction);
  2443. };
  2444. /**
  2445. * 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
  2446. * transformed to the given world matrix.
  2447. * @param origin The origin point
  2448. * @param end The end point
  2449. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2450. */
  2451. Ray.CreateNewFromTo = function (origin, end, world) {
  2452. if (world === void 0) { world = Matrix.Identity(); }
  2453. var direction = end.subtract(origin);
  2454. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2455. direction.normalize();
  2456. return Ray.Transform(new Ray(origin, direction, length), world);
  2457. };
  2458. Ray.Transform = function (ray, matrix) {
  2459. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2460. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2461. return new Ray(newOrigin, newDirection, ray.length);
  2462. };
  2463. return Ray;
  2464. })();
  2465. BABYLON.Ray = Ray;
  2466. (function (Space) {
  2467. Space[Space["LOCAL"] = 0] = "LOCAL";
  2468. Space[Space["WORLD"] = 1] = "WORLD";
  2469. })(BABYLON.Space || (BABYLON.Space = {}));
  2470. var Space = BABYLON.Space;
  2471. var Axis = (function () {
  2472. function Axis() {
  2473. }
  2474. Axis.X = new Vector3(1, 0, 0);
  2475. Axis.Y = new Vector3(0, 1, 0);
  2476. Axis.Z = new Vector3(0, 0, 1);
  2477. return Axis;
  2478. })();
  2479. BABYLON.Axis = Axis;
  2480. ;
  2481. var BezierCurve = (function () {
  2482. function BezierCurve() {
  2483. }
  2484. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2485. // Extract X (which is equal to time here)
  2486. var f0 = 1 - 3 * x2 + 3 * x1;
  2487. var f1 = 3 * x2 - 6 * x1;
  2488. var f2 = 3 * x1;
  2489. var refinedT = t;
  2490. for (var i = 0; i < 5; i++) {
  2491. var refinedT2 = refinedT * refinedT;
  2492. var refinedT3 = refinedT2 * refinedT;
  2493. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2494. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2495. refinedT -= (x - t) * slope;
  2496. refinedT = Math.min(1, Math.max(0, refinedT));
  2497. }
  2498. // Resolve cubic bezier for the given x
  2499. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2500. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2501. Math.pow(refinedT, 3);
  2502. };
  2503. return BezierCurve;
  2504. })();
  2505. BABYLON.BezierCurve = BezierCurve;
  2506. (function (Orientation) {
  2507. Orientation[Orientation["CW"] = 0] = "CW";
  2508. Orientation[Orientation["CCW"] = 1] = "CCW";
  2509. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2510. var Orientation = BABYLON.Orientation;
  2511. var Angle = (function () {
  2512. function Angle(radians) {
  2513. var _this = this;
  2514. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2515. this.radians = function () { return _this._radians; };
  2516. this._radians = radians;
  2517. if (this._radians < 0)
  2518. this._radians += (2 * Math.PI);
  2519. }
  2520. Angle.BetweenTwoPoints = function (a, b) {
  2521. var delta = b.subtract(a);
  2522. var theta = Math.atan2(delta.y, delta.x);
  2523. return new Angle(theta);
  2524. };
  2525. Angle.FromRadians = function (radians) {
  2526. return new Angle(radians);
  2527. };
  2528. Angle.FromDegrees = function (degrees) {
  2529. return new Angle(degrees * Math.PI / 180);
  2530. };
  2531. return Angle;
  2532. })();
  2533. BABYLON.Angle = Angle;
  2534. var Arc2 = (function () {
  2535. function Arc2(startPoint, midPoint, endPoint) {
  2536. this.startPoint = startPoint;
  2537. this.midPoint = midPoint;
  2538. this.endPoint = endPoint;
  2539. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2540. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2541. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2542. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2543. 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);
  2544. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2545. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2546. var a1 = this.startAngle.degrees();
  2547. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2548. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2549. // angles correction
  2550. if (a2 - a1 > +180.0)
  2551. a2 -= 360.0;
  2552. if (a2 - a1 < -180.0)
  2553. a2 += 360.0;
  2554. if (a3 - a2 > +180.0)
  2555. a3 -= 360.0;
  2556. if (a3 - a2 < -180.0)
  2557. a3 += 360.0;
  2558. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2559. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2560. }
  2561. return Arc2;
  2562. })();
  2563. BABYLON.Arc2 = Arc2;
  2564. var PathCursor = (function () {
  2565. function PathCursor(path) {
  2566. this.path = path;
  2567. this._onchange = new Array();
  2568. this.value = 0;
  2569. this.animations = new Array();
  2570. }
  2571. PathCursor.prototype.getPoint = function () {
  2572. var point = this.path.getPointAtLengthPosition(this.value);
  2573. return new Vector3(point.x, 0, point.y);
  2574. };
  2575. PathCursor.prototype.moveAhead = function (step) {
  2576. if (step === void 0) { step = 0.002; }
  2577. this.move(step);
  2578. return this;
  2579. };
  2580. PathCursor.prototype.moveBack = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(-step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.move = function (step) {
  2586. if (Math.abs(step) > 1) {
  2587. throw "step size should be less than 1.";
  2588. }
  2589. this.value += step;
  2590. this.ensureLimits();
  2591. this.raiseOnChange();
  2592. return this;
  2593. };
  2594. PathCursor.prototype.ensureLimits = function () {
  2595. while (this.value > 1) {
  2596. this.value -= 1;
  2597. }
  2598. while (this.value < 0) {
  2599. this.value += 1;
  2600. }
  2601. return this;
  2602. };
  2603. // used by animation engine
  2604. PathCursor.prototype.markAsDirty = function (propertyName) {
  2605. this.ensureLimits();
  2606. this.raiseOnChange();
  2607. return this;
  2608. };
  2609. PathCursor.prototype.raiseOnChange = function () {
  2610. var _this = this;
  2611. this._onchange.forEach(function (f) { return f(_this); });
  2612. return this;
  2613. };
  2614. PathCursor.prototype.onchange = function (f) {
  2615. this._onchange.push(f);
  2616. return this;
  2617. };
  2618. return PathCursor;
  2619. })();
  2620. BABYLON.PathCursor = PathCursor;
  2621. var Path2 = (function () {
  2622. function Path2(x, y) {
  2623. this._points = new Array();
  2624. this._length = 0;
  2625. this.closed = false;
  2626. this._points.push(new Vector2(x, y));
  2627. }
  2628. Path2.prototype.addLineTo = function (x, y) {
  2629. if (closed) {
  2630. BABYLON.Tools.Error("cannot add lines to closed paths");
  2631. return this;
  2632. }
  2633. var newPoint = new Vector2(x, y);
  2634. var previousPoint = this._points[this._points.length - 1];
  2635. this._points.push(newPoint);
  2636. this._length += newPoint.subtract(previousPoint).length();
  2637. return this;
  2638. };
  2639. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2640. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2641. if (closed) {
  2642. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2643. return this;
  2644. }
  2645. var startPoint = this._points[this._points.length - 1];
  2646. var midPoint = new Vector2(midX, midY);
  2647. var endPoint = new Vector2(endX, endY);
  2648. var arc = new Arc2(startPoint, midPoint, endPoint);
  2649. var increment = arc.angle.radians() / numberOfSegments;
  2650. if (arc.orientation === Orientation.CW)
  2651. increment *= -1;
  2652. var currentAngle = arc.startAngle.radians() + increment;
  2653. for (var i = 0; i < numberOfSegments; i++) {
  2654. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2655. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2656. this.addLineTo(x, y);
  2657. currentAngle += increment;
  2658. }
  2659. return this;
  2660. };
  2661. Path2.prototype.close = function () {
  2662. this.closed = true;
  2663. return this;
  2664. };
  2665. Path2.prototype.length = function () {
  2666. var result = this._length;
  2667. if (!this.closed) {
  2668. var lastPoint = this._points[this._points.length - 1];
  2669. var firstPoint = this._points[0];
  2670. result += (firstPoint.subtract(lastPoint).length());
  2671. }
  2672. return result;
  2673. };
  2674. Path2.prototype.getPoints = function () {
  2675. return this._points;
  2676. };
  2677. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2678. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2679. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2680. return Vector2.Zero();
  2681. }
  2682. var lengthPosition = normalizedLengthPosition * this.length();
  2683. var previousOffset = 0;
  2684. for (var i = 0; i < this._points.length; i++) {
  2685. var j = (i + 1) % this._points.length;
  2686. var a = this._points[i];
  2687. var b = this._points[j];
  2688. var bToA = b.subtract(a);
  2689. var nextOffset = (bToA.length() + previousOffset);
  2690. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2691. var dir = bToA.normalize();
  2692. var localOffset = lengthPosition - previousOffset;
  2693. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2694. }
  2695. previousOffset = nextOffset;
  2696. }
  2697. BABYLON.Tools.Error("internal error");
  2698. return Vector2.Zero();
  2699. };
  2700. Path2.StartingAt = function (x, y) {
  2701. return new Path2(x, y);
  2702. };
  2703. return Path2;
  2704. })();
  2705. BABYLON.Path2 = Path2;
  2706. var Path3D = (function () {
  2707. /**
  2708. * new Path3D(path, normal, raw)
  2709. * path : an array of Vector3, the curve axis of the Path3D
  2710. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2711. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2712. */
  2713. function Path3D(path, firstNormal, raw) {
  2714. this.path = path;
  2715. this._curve = new Array();
  2716. this._distances = new Array();
  2717. this._tangents = new Array();
  2718. this._normals = new Array();
  2719. this._binormals = new Array();
  2720. for (var p = 0; p < path.length; p++) {
  2721. this._curve[p] = path[p].clone(); // hard copy
  2722. }
  2723. this._raw = raw || false;
  2724. this._compute(firstNormal);
  2725. }
  2726. Path3D.prototype.getCurve = function () {
  2727. return this._curve;
  2728. };
  2729. Path3D.prototype.getTangents = function () {
  2730. return this._tangents;
  2731. };
  2732. Path3D.prototype.getNormals = function () {
  2733. return this._normals;
  2734. };
  2735. Path3D.prototype.getBinormals = function () {
  2736. return this._binormals;
  2737. };
  2738. Path3D.prototype.getDistances = function () {
  2739. return this._distances;
  2740. };
  2741. Path3D.prototype.update = function (path, firstNormal) {
  2742. for (var p = 0; p < path.length; p++) {
  2743. this._curve[p].x = path[p].x;
  2744. this._curve[p].y = path[p].y;
  2745. this._curve[p].z = path[p].z;
  2746. }
  2747. this._compute(firstNormal);
  2748. return this;
  2749. };
  2750. // private function compute() : computes tangents, normals and binormals
  2751. Path3D.prototype._compute = function (firstNormal) {
  2752. var l = this._curve.length;
  2753. // first and last tangents
  2754. this._tangents[0] = this._getFirstNonNullVector(0);
  2755. if (!this._raw) {
  2756. this._tangents[0].normalize();
  2757. }
  2758. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2759. if (!this._raw) {
  2760. this._tangents[l - 1].normalize();
  2761. }
  2762. // normals and binormals at first point : arbitrary vector with _normalVector()
  2763. var tg0 = this._tangents[0];
  2764. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2765. this._normals[0] = pp0;
  2766. if (!this._raw) {
  2767. this._normals[0].normalize();
  2768. }
  2769. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2770. if (!this._raw) {
  2771. this._binormals[0].normalize();
  2772. }
  2773. this._distances[0] = 0;
  2774. // normals and binormals : next points
  2775. var prev; // previous vector (segment)
  2776. var cur; // current vector (segment)
  2777. var curTang; // current tangent
  2778. // previous normal
  2779. var prevBinor; // previous binormal
  2780. for (var i = 1; i < l; i++) {
  2781. // tangents
  2782. prev = this._getLastNonNullVector(i);
  2783. if (i < l - 1) {
  2784. cur = this._getFirstNonNullVector(i);
  2785. this._tangents[i] = prev.add(cur);
  2786. this._tangents[i].normalize();
  2787. }
  2788. this._distances[i] = this._distances[i - 1] + prev.length();
  2789. // normals and binormals
  2790. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2791. curTang = this._tangents[i];
  2792. prevBinor = this._binormals[i - 1];
  2793. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2794. if (!this._raw) {
  2795. this._normals[i].normalize();
  2796. }
  2797. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2798. if (!this._raw) {
  2799. this._binormals[i].normalize();
  2800. }
  2801. }
  2802. };
  2803. // private function getFirstNonNullVector(index)
  2804. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2805. Path3D.prototype._getFirstNonNullVector = function (index) {
  2806. var i = 1;
  2807. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2808. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2809. i++;
  2810. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2811. }
  2812. return nNVector;
  2813. };
  2814. // private function getLastNonNullVector(index)
  2815. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2816. Path3D.prototype._getLastNonNullVector = function (index) {
  2817. var i = 1;
  2818. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2819. while (nLVector.length() === 0 && index > i + 1) {
  2820. i++;
  2821. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2822. }
  2823. return nLVector;
  2824. };
  2825. // private function normalVector(v0, vt, va) :
  2826. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2827. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2828. Path3D.prototype._normalVector = function (v0, vt, va) {
  2829. var normal0;
  2830. if (va === undefined || va === null) {
  2831. var point;
  2832. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2833. point = new Vector3(0, -1, 0);
  2834. }
  2835. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2836. point = new Vector3(1, 0, 0);
  2837. }
  2838. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2839. point = new Vector3(0, 0, 1);
  2840. }
  2841. normal0 = Vector3.Cross(vt, point);
  2842. }
  2843. else {
  2844. normal0 = Vector3.Cross(vt, va);
  2845. Vector3.CrossToRef(normal0, vt, normal0);
  2846. }
  2847. normal0.normalize();
  2848. return normal0;
  2849. };
  2850. return Path3D;
  2851. })();
  2852. BABYLON.Path3D = Path3D;
  2853. var Curve3 = (function () {
  2854. function Curve3(points) {
  2855. this._length = 0;
  2856. this._points = points;
  2857. this._length = this._computeLength(points);
  2858. }
  2859. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2860. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2861. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2862. var bez = new Array();
  2863. var equation = function (t, val0, val1, val2) {
  2864. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2865. return res;
  2866. };
  2867. for (var i = 0; i <= nbPoints; i++) {
  2868. 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)));
  2869. }
  2870. return new Curve3(bez);
  2871. };
  2872. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2873. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2874. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2875. var bez = new Array();
  2876. var equation = function (t, val0, val1, val2, val3) {
  2877. 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;
  2878. return res;
  2879. };
  2880. for (var i = 0; i <= nbPoints; i++) {
  2881. 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)));
  2882. }
  2883. return new Curve3(bez);
  2884. };
  2885. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2886. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2887. var hermite = new Array();
  2888. var step = 1 / nbPoints;
  2889. for (var i = 0; i <= nbPoints; i++) {
  2890. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2891. }
  2892. return new Curve3(hermite);
  2893. };
  2894. Curve3.prototype.getPoints = function () {
  2895. return this._points;
  2896. };
  2897. Curve3.prototype.length = function () {
  2898. return this._length;
  2899. };
  2900. Curve3.prototype.continue = function (curve) {
  2901. var lastPoint = this._points[this._points.length - 1];
  2902. var continuedPoints = this._points.slice();
  2903. var curvePoints = curve.getPoints();
  2904. for (var i = 1; i < curvePoints.length; i++) {
  2905. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2906. }
  2907. var continuedCurve = new Curve3(continuedPoints);
  2908. return continuedCurve;
  2909. };
  2910. Curve3.prototype._computeLength = function (path) {
  2911. var l = 0;
  2912. for (var i = 1; i < path.length; i++) {
  2913. l += (path[i].subtract(path[i - 1])).length();
  2914. }
  2915. return l;
  2916. };
  2917. return Curve3;
  2918. })();
  2919. BABYLON.Curve3 = Curve3;
  2920. // Vertex formats
  2921. var PositionNormalVertex = (function () {
  2922. function PositionNormalVertex(position, normal) {
  2923. if (position === void 0) { position = Vector3.Zero(); }
  2924. if (normal === void 0) { normal = Vector3.Up(); }
  2925. this.position = position;
  2926. this.normal = normal;
  2927. }
  2928. PositionNormalVertex.prototype.clone = function () {
  2929. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2930. };
  2931. return PositionNormalVertex;
  2932. })();
  2933. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2934. var PositionNormalTextureVertex = (function () {
  2935. function PositionNormalTextureVertex(position, normal, uv) {
  2936. if (position === void 0) { position = Vector3.Zero(); }
  2937. if (normal === void 0) { normal = Vector3.Up(); }
  2938. if (uv === void 0) { uv = Vector2.Zero(); }
  2939. this.position = position;
  2940. this.normal = normal;
  2941. this.uv = uv;
  2942. }
  2943. PositionNormalTextureVertex.prototype.clone = function () {
  2944. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2945. };
  2946. return PositionNormalTextureVertex;
  2947. })();
  2948. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. var Database = (function () {
  2953. function Database(urlToScene, callbackManifestChecked) {
  2954. // Handling various flavors of prefixed version of IndexedDB
  2955. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2956. this.callbackManifestChecked = callbackManifestChecked;
  2957. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2958. this.db = null;
  2959. this.enableSceneOffline = false;
  2960. this.enableTexturesOffline = false;
  2961. this.manifestVersionFound = 0;
  2962. this.mustUpdateRessources = false;
  2963. this.hasReachedQuota = false;
  2964. if (!Database.IDBStorageEnabled) {
  2965. this.callbackManifestChecked(true);
  2966. }
  2967. else {
  2968. this.checkManifestFile();
  2969. }
  2970. }
  2971. Database.prototype.checkManifestFile = function () {
  2972. var _this = this;
  2973. function noManifestFile() {
  2974. that.enableSceneOffline = false;
  2975. that.enableTexturesOffline = false;
  2976. that.callbackManifestChecked(false);
  2977. }
  2978. var that = this;
  2979. var manifestURL = this.currentSceneUrl + ".manifest";
  2980. var xhr = new XMLHttpRequest();
  2981. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2982. xhr.open("GET", manifestURLTimeStamped, true);
  2983. xhr.addEventListener("load", function () {
  2984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2985. try {
  2986. var manifestFile = JSON.parse(xhr.response);
  2987. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2988. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2990. _this.manifestVersionFound = manifestFile.version;
  2991. }
  2992. if (_this.callbackManifestChecked) {
  2993. _this.callbackManifestChecked(true);
  2994. }
  2995. }
  2996. catch (ex) {
  2997. noManifestFile();
  2998. }
  2999. }
  3000. else {
  3001. noManifestFile();
  3002. }
  3003. }, false);
  3004. xhr.addEventListener("error", function (event) {
  3005. noManifestFile();
  3006. }, false);
  3007. try {
  3008. xhr.send();
  3009. }
  3010. catch (ex) {
  3011. BABYLON.Tools.Error("Error on XHR send request.");
  3012. that.callbackManifestChecked(false);
  3013. }
  3014. };
  3015. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3016. var _this = this;
  3017. function handleError() {
  3018. that.isSupported = false;
  3019. if (errorCallback)
  3020. errorCallback();
  3021. }
  3022. var that = this;
  3023. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3024. // Your browser doesn't support IndexedDB
  3025. this.isSupported = false;
  3026. if (errorCallback)
  3027. errorCallback();
  3028. }
  3029. else {
  3030. // If the DB hasn't been opened or created yet
  3031. if (!this.db) {
  3032. this.hasReachedQuota = false;
  3033. this.isSupported = true;
  3034. var request = this.idbFactory.open("babylonjs", 1);
  3035. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3036. request.onerror = function (event) {
  3037. handleError();
  3038. };
  3039. // executes when a version change transaction cannot complete due to other active transactions
  3040. request.onblocked = function (event) {
  3041. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3042. handleError();
  3043. };
  3044. // DB has been opened successfully
  3045. request.onsuccess = function (event) {
  3046. _this.db = request.result;
  3047. successCallback();
  3048. };
  3049. // Initialization of the DB. Creating Scenes & Textures stores
  3050. request.onupgradeneeded = function (event) {
  3051. _this.db = (event.target).result;
  3052. try {
  3053. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3054. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3055. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3056. }
  3057. catch (ex) {
  3058. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3059. handleError();
  3060. }
  3061. };
  3062. }
  3063. else {
  3064. if (successCallback)
  3065. successCallback();
  3066. }
  3067. }
  3068. };
  3069. Database.prototype.loadImageFromDB = function (url, image) {
  3070. var _this = this;
  3071. var completeURL = Database.ReturnFullUrlLocation(url);
  3072. var saveAndLoadImage = function () {
  3073. if (!_this.hasReachedQuota && _this.db !== null) {
  3074. // the texture is not yet in the DB, let's try to save it
  3075. _this._saveImageIntoDBAsync(completeURL, image);
  3076. }
  3077. else {
  3078. image.src = url;
  3079. }
  3080. };
  3081. if (!this.mustUpdateRessources) {
  3082. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3083. }
  3084. else {
  3085. saveAndLoadImage();
  3086. }
  3087. };
  3088. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3089. if (this.isSupported && this.db !== null) {
  3090. var texture;
  3091. var transaction = this.db.transaction(["textures"]);
  3092. transaction.onabort = function (event) {
  3093. image.src = url;
  3094. };
  3095. transaction.oncomplete = function (event) {
  3096. var blobTextureURL;
  3097. if (texture) {
  3098. var URL = window.URL || window.webkitURL;
  3099. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3100. image.onerror = function () {
  3101. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3102. image.src = url;
  3103. };
  3104. image.src = blobTextureURL;
  3105. }
  3106. else {
  3107. notInDBCallback();
  3108. }
  3109. };
  3110. var getRequest = transaction.objectStore("textures").get(url);
  3111. getRequest.onsuccess = function (event) {
  3112. texture = (event.target).result;
  3113. };
  3114. getRequest.onerror = function (event) {
  3115. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3116. image.src = url;
  3117. };
  3118. }
  3119. else {
  3120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3121. image.src = url;
  3122. }
  3123. };
  3124. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3125. var _this = this;
  3126. if (this.isSupported) {
  3127. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3128. var generateBlobUrl = function () {
  3129. var blobTextureURL;
  3130. if (blob) {
  3131. var URL = window.URL || window.webkitURL;
  3132. try {
  3133. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3134. }
  3135. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3136. catch (ex) {
  3137. blobTextureURL = URL.createObjectURL(blob);
  3138. }
  3139. }
  3140. image.src = blobTextureURL;
  3141. };
  3142. if (Database.IsUASupportingBlobStorage) {
  3143. var xhr = new XMLHttpRequest(), blob;
  3144. xhr.open("GET", url, true);
  3145. xhr.responseType = "blob";
  3146. xhr.addEventListener("load", function () {
  3147. if (xhr.status === 200) {
  3148. // Blob as response (XHR2)
  3149. blob = xhr.response;
  3150. var transaction = _this.db.transaction(["textures"], "readwrite");
  3151. // the transaction could abort because of a QuotaExceededError error
  3152. transaction.onabort = function (event) {
  3153. try {
  3154. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3155. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3156. this.hasReachedQuota = true;
  3157. }
  3158. }
  3159. catch (ex) { }
  3160. generateBlobUrl();
  3161. };
  3162. transaction.oncomplete = function (event) {
  3163. generateBlobUrl();
  3164. };
  3165. var newTexture = { textureUrl: url, data: blob };
  3166. try {
  3167. // Put the blob into the dabase
  3168. var addRequest = transaction.objectStore("textures").put(newTexture);
  3169. addRequest.onsuccess = function (event) {
  3170. };
  3171. addRequest.onerror = function (event) {
  3172. generateBlobUrl();
  3173. };
  3174. }
  3175. catch (ex) {
  3176. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3177. if (ex.code === 25) {
  3178. Database.IsUASupportingBlobStorage = false;
  3179. }
  3180. image.src = url;
  3181. }
  3182. }
  3183. else {
  3184. image.src = url;
  3185. }
  3186. }, false);
  3187. xhr.addEventListener("error", function (event) {
  3188. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3189. image.src = url;
  3190. }, false);
  3191. xhr.send();
  3192. }
  3193. else {
  3194. image.src = url;
  3195. }
  3196. }
  3197. else {
  3198. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3199. image.src = url;
  3200. }
  3201. };
  3202. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3203. var _this = this;
  3204. var updateVersion = function (event) {
  3205. // the version is not yet in the DB or we need to update it
  3206. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3207. };
  3208. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3209. };
  3210. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3211. var _this = this;
  3212. if (this.isSupported) {
  3213. var version;
  3214. try {
  3215. var transaction = this.db.transaction(["versions"]);
  3216. transaction.oncomplete = function (event) {
  3217. if (version) {
  3218. // If the version in the JSON file is > than the version in DB
  3219. if (_this.manifestVersionFound > version.data) {
  3220. _this.mustUpdateRessources = true;
  3221. updateInDBCallback();
  3222. }
  3223. else {
  3224. callback(version.data);
  3225. }
  3226. }
  3227. else {
  3228. _this.mustUpdateRessources = true;
  3229. updateInDBCallback();
  3230. }
  3231. };
  3232. transaction.onabort = function (event) {
  3233. callback(-1);
  3234. };
  3235. var getRequest = transaction.objectStore("versions").get(url);
  3236. getRequest.onsuccess = function (event) {
  3237. version = (event.target).result;
  3238. };
  3239. getRequest.onerror = function (event) {
  3240. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3241. callback(-1);
  3242. };
  3243. }
  3244. catch (ex) {
  3245. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3246. callback(-1);
  3247. }
  3248. }
  3249. else {
  3250. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3251. callback(-1);
  3252. }
  3253. };
  3254. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3255. var _this = this;
  3256. if (this.isSupported && !this.hasReachedQuota) {
  3257. try {
  3258. // Open a transaction to the database
  3259. var transaction = this.db.transaction(["versions"], "readwrite");
  3260. // the transaction could abort because of a QuotaExceededError error
  3261. transaction.onabort = function (event) {
  3262. try {
  3263. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3264. _this.hasReachedQuota = true;
  3265. }
  3266. }
  3267. catch (ex) { }
  3268. callback(-1);
  3269. };
  3270. transaction.oncomplete = function (event) {
  3271. callback(_this.manifestVersionFound);
  3272. };
  3273. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3274. // Put the scene into the database
  3275. var addRequest = transaction.objectStore("versions").put(newVersion);
  3276. addRequest.onsuccess = function (event) {
  3277. };
  3278. addRequest.onerror = function (event) {
  3279. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3280. };
  3281. }
  3282. catch (ex) {
  3283. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3284. callback(-1);
  3285. }
  3286. }
  3287. else {
  3288. callback(-1);
  3289. }
  3290. };
  3291. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3292. var _this = this;
  3293. var completeUrl = Database.ReturnFullUrlLocation(url);
  3294. var saveAndLoadFile = function (event) {
  3295. // the scene is not yet in the DB, let's try to save it
  3296. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3297. };
  3298. this._checkVersionFromDB(completeUrl, function (version) {
  3299. if (version !== -1) {
  3300. if (!_this.mustUpdateRessources) {
  3301. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3302. }
  3303. else {
  3304. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3305. }
  3306. }
  3307. else {
  3308. errorCallback();
  3309. }
  3310. });
  3311. };
  3312. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3313. if (this.isSupported) {
  3314. var targetStore;
  3315. if (url.indexOf(".babylon") !== -1) {
  3316. targetStore = "scenes";
  3317. }
  3318. else {
  3319. targetStore = "textures";
  3320. }
  3321. var file;
  3322. var transaction = this.db.transaction([targetStore]);
  3323. transaction.oncomplete = function (event) {
  3324. if (file) {
  3325. callback(file.data);
  3326. }
  3327. else {
  3328. notInDBCallback();
  3329. }
  3330. };
  3331. transaction.onabort = function (event) {
  3332. notInDBCallback();
  3333. };
  3334. var getRequest = transaction.objectStore(targetStore).get(url);
  3335. getRequest.onsuccess = function (event) {
  3336. file = (event.target).result;
  3337. };
  3338. getRequest.onerror = function (event) {
  3339. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3340. notInDBCallback();
  3341. };
  3342. }
  3343. else {
  3344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3345. callback();
  3346. }
  3347. };
  3348. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3349. var _this = this;
  3350. if (this.isSupported) {
  3351. var targetStore;
  3352. if (url.indexOf(".babylon") !== -1) {
  3353. targetStore = "scenes";
  3354. }
  3355. else {
  3356. targetStore = "textures";
  3357. }
  3358. // Create XHR
  3359. var xhr = new XMLHttpRequest(), fileData;
  3360. xhr.open("GET", url, true);
  3361. if (useArrayBuffer) {
  3362. xhr.responseType = "arraybuffer";
  3363. }
  3364. xhr.onprogress = progressCallback;
  3365. xhr.addEventListener("load", function () {
  3366. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3367. // Blob as response (XHR2)
  3368. //fileData = xhr.responseText;
  3369. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3370. if (!_this.hasReachedQuota) {
  3371. // Open a transaction to the database
  3372. var transaction = _this.db.transaction([targetStore], "readwrite");
  3373. // the transaction could abort because of a QuotaExceededError error
  3374. transaction.onabort = function (event) {
  3375. try {
  3376. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3377. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3378. this.hasReachedQuota = true;
  3379. }
  3380. }
  3381. catch (ex) { }
  3382. callback(fileData);
  3383. };
  3384. transaction.oncomplete = function (event) {
  3385. callback(fileData);
  3386. };
  3387. var newFile;
  3388. if (targetStore === "scenes") {
  3389. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3390. }
  3391. else {
  3392. newFile = { textureUrl: url, data: fileData };
  3393. }
  3394. try {
  3395. // Put the scene into the database
  3396. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3397. addRequest.onsuccess = function (event) {
  3398. };
  3399. addRequest.onerror = function (event) {
  3400. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3401. };
  3402. }
  3403. catch (ex) {
  3404. callback(fileData);
  3405. }
  3406. }
  3407. else {
  3408. callback(fileData);
  3409. }
  3410. }
  3411. else {
  3412. callback();
  3413. }
  3414. }, false);
  3415. xhr.addEventListener("error", function (event) {
  3416. BABYLON.Tools.Error("error on XHR request.");
  3417. callback();
  3418. }, false);
  3419. xhr.send();
  3420. }
  3421. else {
  3422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3423. callback();
  3424. }
  3425. };
  3426. Database.IsUASupportingBlobStorage = true;
  3427. Database.IDBStorageEnabled = true;
  3428. Database.parseURL = function (url) {
  3429. var a = document.createElement('a');
  3430. a.href = url;
  3431. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3432. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3433. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3434. return absLocation;
  3435. };
  3436. Database.ReturnFullUrlLocation = function (url) {
  3437. if (url.indexOf("http:/") === -1) {
  3438. return (Database.parseURL(window.location.href) + url);
  3439. }
  3440. else {
  3441. return url;
  3442. }
  3443. };
  3444. return Database;
  3445. })();
  3446. BABYLON.Database = Database;
  3447. })(BABYLON || (BABYLON = {}));
  3448. var BABYLON;
  3449. (function (BABYLON) {
  3450. var Internals;
  3451. (function (Internals) {
  3452. /*
  3453. * Based on jsTGALoader - Javascript loader for TGA file
  3454. * By Vincent Thibault
  3455. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3456. */
  3457. var TGATools = (function () {
  3458. function TGATools() {
  3459. }
  3460. TGATools.GetTGAHeader = function (data) {
  3461. var offset = 0;
  3462. var header = {
  3463. id_length: data[offset++],
  3464. colormap_type: data[offset++],
  3465. image_type: data[offset++],
  3466. colormap_index: data[offset++] | data[offset++] << 8,
  3467. colormap_length: data[offset++] | data[offset++] << 8,
  3468. colormap_size: data[offset++],
  3469. origin: [
  3470. data[offset++] | data[offset++] << 8,
  3471. data[offset++] | data[offset++] << 8
  3472. ],
  3473. width: data[offset++] | data[offset++] << 8,
  3474. height: data[offset++] | data[offset++] << 8,
  3475. pixel_size: data[offset++],
  3476. flags: data[offset++]
  3477. };
  3478. return header;
  3479. };
  3480. TGATools.UploadContent = function (gl, data) {
  3481. // Not enough data to contain header ?
  3482. if (data.length < 19) {
  3483. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3484. return;
  3485. }
  3486. // Read Header
  3487. var offset = 18;
  3488. var header = TGATools.GetTGAHeader(data);
  3489. // Assume it's a valid Targa file.
  3490. if (header.id_length + offset > data.length) {
  3491. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3492. return;
  3493. }
  3494. // Skip not needed data
  3495. offset += header.id_length;
  3496. var use_rle = false;
  3497. var use_pal = false;
  3498. var use_rgb = false;
  3499. var use_grey = false;
  3500. // Get some informations.
  3501. switch (header.image_type) {
  3502. case TGATools._TYPE_RLE_INDEXED:
  3503. use_rle = true;
  3504. case TGATools._TYPE_INDEXED:
  3505. use_pal = true;
  3506. break;
  3507. case TGATools._TYPE_RLE_RGB:
  3508. use_rle = true;
  3509. case TGATools._TYPE_RGB:
  3510. use_rgb = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_GREY:
  3513. use_rle = true;
  3514. case TGATools._TYPE_GREY:
  3515. use_grey = true;
  3516. break;
  3517. }
  3518. var pixel_data;
  3519. var numAlphaBits = header.flags & 0xf;
  3520. var pixel_size = header.pixel_size >> 3;
  3521. var pixel_total = header.width * header.height * pixel_size;
  3522. // Read palettes
  3523. var palettes;
  3524. if (use_pal) {
  3525. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3526. }
  3527. // Read LRE
  3528. if (use_rle) {
  3529. pixel_data = new Uint8Array(pixel_total);
  3530. var c, count, i;
  3531. var localOffset = 0;
  3532. var pixels = new Uint8Array(pixel_size);
  3533. while (offset < pixel_total && localOffset < pixel_total) {
  3534. c = data[offset++];
  3535. count = (c & 0x7f) + 1;
  3536. // RLE pixels
  3537. if (c & 0x80) {
  3538. // Bind pixel tmp array
  3539. for (i = 0; i < pixel_size; ++i) {
  3540. pixels[i] = data[offset++];
  3541. }
  3542. // Copy pixel array
  3543. for (i = 0; i < count; ++i) {
  3544. pixel_data.set(pixels, localOffset + i * pixel_size);
  3545. }
  3546. localOffset += pixel_size * count;
  3547. }
  3548. else {
  3549. count *= pixel_size;
  3550. for (i = 0; i < count; ++i) {
  3551. pixel_data[localOffset + i] = data[offset++];
  3552. }
  3553. localOffset += count;
  3554. }
  3555. }
  3556. }
  3557. else {
  3558. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3559. }
  3560. // Load to texture
  3561. var x_start, y_start, x_step, y_step, y_end, x_end;
  3562. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3563. default:
  3564. case TGATools._ORIGIN_UL:
  3565. x_start = 0;
  3566. x_step = 1;
  3567. x_end = header.width;
  3568. y_start = 0;
  3569. y_step = 1;
  3570. y_end = header.height;
  3571. break;
  3572. case TGATools._ORIGIN_BL:
  3573. x_start = 0;
  3574. x_step = 1;
  3575. x_end = header.width;
  3576. y_start = header.height - 1;
  3577. y_step = -1;
  3578. y_end = -1;
  3579. break;
  3580. case TGATools._ORIGIN_UR:
  3581. x_start = header.width - 1;
  3582. x_step = -1;
  3583. x_end = -1;
  3584. y_start = 0;
  3585. y_step = 1;
  3586. y_end = header.height;
  3587. break;
  3588. case TGATools._ORIGIN_BR:
  3589. x_start = header.width - 1;
  3590. x_step = -1;
  3591. x_end = -1;
  3592. y_start = header.height - 1;
  3593. y_step = -1;
  3594. y_end = -1;
  3595. break;
  3596. }
  3597. // Load the specify method
  3598. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3599. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3600. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3601. };
  3602. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3603. var image = pixel_data, colormap = palettes;
  3604. var width = header.width, height = header.height;
  3605. var color, i = 0, x, y;
  3606. var imageData = new Uint8Array(width * height * 4);
  3607. for (y = y_start; y !== y_end; y += y_step) {
  3608. for (x = x_start; x !== x_end; x += x_step, i++) {
  3609. color = image[i];
  3610. imageData[(x + width * y) * 4 + 3] = 255;
  3611. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3612. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3613. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3614. }
  3615. }
  3616. return imageData;
  3617. };
  3618. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3619. var image = pixel_data;
  3620. var width = header.width, height = header.height;
  3621. var color, i = 0, x, y;
  3622. var imageData = new Uint8Array(width * height * 4);
  3623. for (y = y_start; y !== y_end; y += y_step) {
  3624. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3625. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3626. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3627. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3628. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3629. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3630. }
  3631. }
  3632. return imageData;
  3633. };
  3634. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3635. var image = pixel_data;
  3636. var width = header.width, height = header.height;
  3637. var i = 0, x, y;
  3638. var imageData = new Uint8Array(width * height * 4);
  3639. for (y = y_start; y !== y_end; y += y_step) {
  3640. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3641. imageData[(x + width * y) * 4 + 3] = 255;
  3642. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3643. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3644. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3645. }
  3646. }
  3647. return imageData;
  3648. };
  3649. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3650. var image = pixel_data;
  3651. var width = header.width, height = header.height;
  3652. var i = 0, x, y;
  3653. var imageData = new Uint8Array(width * height * 4);
  3654. for (y = y_start; y !== y_end; y += y_step) {
  3655. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3657. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3658. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3659. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3660. }
  3661. }
  3662. return imageData;
  3663. };
  3664. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3665. var image = pixel_data;
  3666. var width = header.width, height = header.height;
  3667. var color, i = 0, x, y;
  3668. var imageData = new Uint8Array(width * height * 4);
  3669. for (y = y_start; y !== y_end; y += y_step) {
  3670. for (x = x_start; x !== x_end; x += x_step, i++) {
  3671. color = image[i];
  3672. imageData[(x + width * y) * 4 + 0] = color;
  3673. imageData[(x + width * y) * 4 + 1] = color;
  3674. imageData[(x + width * y) * 4 + 2] = color;
  3675. imageData[(x + width * y) * 4 + 3] = 255;
  3676. }
  3677. }
  3678. return imageData;
  3679. };
  3680. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3681. var image = pixel_data;
  3682. var width = header.width, height = header.height;
  3683. var i = 0, x, y;
  3684. var imageData = new Uint8Array(width * height * 4);
  3685. for (y = y_start; y !== y_end; y += y_step) {
  3686. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3687. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3688. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3689. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3690. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._TYPE_NO_DATA = 0;
  3696. TGATools._TYPE_INDEXED = 1;
  3697. TGATools._TYPE_RGB = 2;
  3698. TGATools._TYPE_GREY = 3;
  3699. TGATools._TYPE_RLE_INDEXED = 9;
  3700. TGATools._TYPE_RLE_RGB = 10;
  3701. TGATools._TYPE_RLE_GREY = 11;
  3702. TGATools._ORIGIN_MASK = 0x30;
  3703. TGATools._ORIGIN_SHIFT = 0x04;
  3704. TGATools._ORIGIN_BL = 0x00;
  3705. TGATools._ORIGIN_BR = 0x01;
  3706. TGATools._ORIGIN_UL = 0x02;
  3707. TGATools._ORIGIN_UR = 0x03;
  3708. return TGATools;
  3709. })();
  3710. Internals.TGATools = TGATools;
  3711. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3712. })(BABYLON || (BABYLON = {}));
  3713. var BABYLON;
  3714. (function (BABYLON) {
  3715. var SmartArray = (function () {
  3716. function SmartArray(capacity) {
  3717. this.length = 0;
  3718. this._duplicateId = 0;
  3719. this.data = new Array(capacity);
  3720. this._id = SmartArray._GlobalId++;
  3721. }
  3722. SmartArray.prototype.push = function (value) {
  3723. this.data[this.length++] = value;
  3724. if (this.length > this.data.length) {
  3725. this.data.length *= 2;
  3726. }
  3727. if (!value.__smartArrayFlags) {
  3728. value.__smartArrayFlags = {};
  3729. }
  3730. value.__smartArrayFlags[this._id] = this._duplicateId;
  3731. };
  3732. SmartArray.prototype.pushNoDuplicate = function (value) {
  3733. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3734. return;
  3735. }
  3736. this.push(value);
  3737. };
  3738. SmartArray.prototype.sort = function (compareFn) {
  3739. this.data.sort(compareFn);
  3740. };
  3741. SmartArray.prototype.reset = function () {
  3742. this.length = 0;
  3743. this._duplicateId++;
  3744. };
  3745. SmartArray.prototype.concat = function (array) {
  3746. if (array.length === 0) {
  3747. return;
  3748. }
  3749. if (this.length + array.length > this.data.length) {
  3750. this.data.length = (this.length + array.length) * 2;
  3751. }
  3752. for (var index = 0; index < array.length; index++) {
  3753. this.data[this.length++] = (array.data || array)[index];
  3754. }
  3755. };
  3756. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3757. if (array.length === 0) {
  3758. return;
  3759. }
  3760. if (this.length + array.length > this.data.length) {
  3761. this.data.length = (this.length + array.length) * 2;
  3762. }
  3763. for (var index = 0; index < array.length; index++) {
  3764. var item = (array.data || array)[index];
  3765. this.pushNoDuplicate(item);
  3766. }
  3767. };
  3768. SmartArray.prototype.indexOf = function (value) {
  3769. var position = this.data.indexOf(value);
  3770. if (position >= this.length) {
  3771. return -1;
  3772. }
  3773. return position;
  3774. };
  3775. // Statics
  3776. SmartArray._GlobalId = 0;
  3777. return SmartArray;
  3778. })();
  3779. BABYLON.SmartArray = SmartArray;
  3780. })(BABYLON || (BABYLON = {}));
  3781. var BABYLON;
  3782. (function (BABYLON) {
  3783. var SmartCollection = (function () {
  3784. function SmartCollection(capacity) {
  3785. if (capacity === void 0) { capacity = 10; }
  3786. this.count = 0;
  3787. this._initialCapacity = capacity;
  3788. this.items = {};
  3789. this._keys = new Array(this._initialCapacity);
  3790. }
  3791. SmartCollection.prototype.add = function (key, item) {
  3792. if (this.items[key] != undefined) {
  3793. return -1;
  3794. }
  3795. this.items[key] = item;
  3796. //literal keys are always strings, but we keep source type of key in _keys array
  3797. this._keys[this.count++] = key;
  3798. if (this.count > this._keys.length) {
  3799. this._keys.length *= 2;
  3800. }
  3801. return this.count;
  3802. };
  3803. SmartCollection.prototype.remove = function (key) {
  3804. if (this.items[key] == undefined) {
  3805. return -1;
  3806. }
  3807. return this.removeItemOfIndex(this.indexOf(key));
  3808. };
  3809. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3810. if (index < this.count && index > -1) {
  3811. delete this.items[this._keys[index]];
  3812. //here, shifting by hand is better optimised than .splice
  3813. while (index < this.count) {
  3814. this._keys[index] = this._keys[index + 1];
  3815. index++;
  3816. }
  3817. }
  3818. else {
  3819. return -1;
  3820. }
  3821. return --this.count;
  3822. };
  3823. SmartCollection.prototype.indexOf = function (key) {
  3824. for (var i = 0; i !== this.count; i++) {
  3825. if (this._keys[i] === key) {
  3826. return i;
  3827. }
  3828. }
  3829. return -1;
  3830. };
  3831. SmartCollection.prototype.item = function (key) {
  3832. return this.items[key];
  3833. };
  3834. SmartCollection.prototype.getAllKeys = function () {
  3835. if (this.count > 0) {
  3836. var keys = new Array(this.count);
  3837. for (var i = 0; i < this.count; i++) {
  3838. keys[i] = this._keys[i];
  3839. }
  3840. return keys;
  3841. }
  3842. else {
  3843. return undefined;
  3844. }
  3845. };
  3846. SmartCollection.prototype.getKeyByIndex = function (index) {
  3847. if (index < this.count && index > -1) {
  3848. return this._keys[index];
  3849. }
  3850. else {
  3851. return undefined;
  3852. }
  3853. };
  3854. SmartCollection.prototype.getItemByIndex = function (index) {
  3855. if (index < this.count && index > -1) {
  3856. return this.items[this._keys[index]];
  3857. }
  3858. else {
  3859. return undefined;
  3860. }
  3861. };
  3862. SmartCollection.prototype.empty = function () {
  3863. if (this.count > 0) {
  3864. this.count = 0;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. };
  3869. SmartCollection.prototype.forEach = function (block) {
  3870. var key;
  3871. for (key in this.items) {
  3872. if (this.items.hasOwnProperty(key)) {
  3873. block(this.items[key]);
  3874. }
  3875. }
  3876. };
  3877. return SmartCollection;
  3878. })();
  3879. BABYLON.SmartCollection = SmartCollection;
  3880. })(BABYLON || (BABYLON = {}));
  3881. var BABYLON;
  3882. (function (BABYLON) {
  3883. // Screenshots
  3884. var screenshotCanvas;
  3885. var cloneValue = function (source, destinationObject) {
  3886. if (!source)
  3887. return null;
  3888. if (source instanceof BABYLON.Mesh) {
  3889. return null;
  3890. }
  3891. if (source instanceof BABYLON.SubMesh) {
  3892. return source.clone(destinationObject);
  3893. }
  3894. else if (source.clone) {
  3895. return source.clone();
  3896. }
  3897. return null;
  3898. };
  3899. var Tools = (function () {
  3900. function Tools() {
  3901. }
  3902. Tools.Instantiate = function (className) {
  3903. var arr = className.split(".");
  3904. var fn = (window || this);
  3905. for (var i = 0, len = arr.length; i < len; i++) {
  3906. fn = fn[arr[i]];
  3907. }
  3908. if (typeof fn !== "function") {
  3909. return null;
  3910. }
  3911. return fn;
  3912. };
  3913. Tools.GetConstructorName = function (obj) {
  3914. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3915. var cname = str.match(/function\s(\w*)/)[1];
  3916. var aliases = ["", "anonymous", "Anonymous"];
  3917. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3918. };
  3919. Tools.ToHex = function (i) {
  3920. var str = i.toString(16);
  3921. if (i <= 15) {
  3922. return ("0" + str).toUpperCase();
  3923. }
  3924. return str.toUpperCase();
  3925. };
  3926. Tools.SetImmediate = function (action) {
  3927. if (window.setImmediate) {
  3928. window.setImmediate(action);
  3929. }
  3930. else {
  3931. setTimeout(action, 1);
  3932. }
  3933. };
  3934. Tools.IsExponentOfTwo = function (value) {
  3935. var count = 1;
  3936. do {
  3937. count *= 2;
  3938. } while (count < value);
  3939. return count === value;
  3940. };
  3941. Tools.GetExponentOfTwo = function (value, max) {
  3942. var count = 1;
  3943. do {
  3944. count *= 2;
  3945. } while (count < value);
  3946. if (count > max)
  3947. count = max;
  3948. return count;
  3949. };
  3950. Tools.GetFilename = function (path) {
  3951. var index = path.lastIndexOf("/");
  3952. if (index < 0)
  3953. return path;
  3954. return path.substring(index + 1);
  3955. };
  3956. Tools.GetDOMTextContent = function (element) {
  3957. var result = "";
  3958. var child = element.firstChild;
  3959. while (child) {
  3960. if (child.nodeType === 3) {
  3961. result += child.textContent;
  3962. }
  3963. child = child.nextSibling;
  3964. }
  3965. return result;
  3966. };
  3967. Tools.ToDegrees = function (angle) {
  3968. return angle * 180 / Math.PI;
  3969. };
  3970. Tools.ToRadians = function (angle) {
  3971. return angle * Math.PI / 180;
  3972. };
  3973. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3974. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3975. var output = "";
  3976. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3977. var i = 0;
  3978. var bytes = new Uint8Array(buffer);
  3979. while (i < bytes.length) {
  3980. chr1 = bytes[i++];
  3981. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3982. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3983. enc1 = chr1 >> 2;
  3984. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3985. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3986. enc4 = chr3 & 63;
  3987. if (isNaN(chr2)) {
  3988. enc3 = enc4 = 64;
  3989. }
  3990. else if (isNaN(chr3)) {
  3991. enc4 = 64;
  3992. }
  3993. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3994. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3995. }
  3996. return "data:image/png;base64," + output;
  3997. };
  3998. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3999. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4000. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4001. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4002. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4003. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4004. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4005. }
  4006. return {
  4007. minimum: minimum,
  4008. maximum: maximum
  4009. };
  4010. };
  4011. Tools.ExtractMinAndMax = function (positions, start, count) {
  4012. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4013. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4014. for (var index = start; index < start + count; index++) {
  4015. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4016. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4017. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4018. }
  4019. return {
  4020. minimum: minimum,
  4021. maximum: maximum
  4022. };
  4023. };
  4024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4026. return undefined;
  4027. return Array.isArray(obj) ? obj : [obj];
  4028. };
  4029. // Misc.
  4030. Tools.GetPointerPrefix = function () {
  4031. var eventPrefix = "pointer";
  4032. // Check if hand.js is referenced or if the browser natively supports pointer events
  4033. //if (!navigator.pointerEnabled) {
  4034. // eventPrefix = "mouse";
  4035. //}
  4036. return eventPrefix;
  4037. };
  4038. Tools.QueueNewFrame = function (func) {
  4039. if (window.requestAnimationFrame)
  4040. window.requestAnimationFrame(func);
  4041. else if (window.msRequestAnimationFrame)
  4042. window.msRequestAnimationFrame(func);
  4043. else if (window.webkitRequestAnimationFrame)
  4044. window.webkitRequestAnimationFrame(func);
  4045. else if (window.mozRequestAnimationFrame)
  4046. window.mozRequestAnimationFrame(func);
  4047. else if (window.oRequestAnimationFrame)
  4048. window.oRequestAnimationFrame(func);
  4049. else {
  4050. window.setTimeout(func, 16);
  4051. }
  4052. };
  4053. Tools.RequestFullscreen = function (element) {
  4054. if (element.requestFullscreen)
  4055. element.requestFullscreen();
  4056. else if (element.msRequestFullscreen)
  4057. element.msRequestFullscreen();
  4058. else if (element.webkitRequestFullscreen)
  4059. element.webkitRequestFullscreen();
  4060. else if (element.mozRequestFullScreen)
  4061. element.mozRequestFullScreen();
  4062. };
  4063. Tools.ExitFullscreen = function () {
  4064. if (document.exitFullscreen) {
  4065. document.exitFullscreen();
  4066. }
  4067. else if (document.mozCancelFullScreen) {
  4068. document.mozCancelFullScreen();
  4069. }
  4070. else if (document.webkitCancelFullScreen) {
  4071. document.webkitCancelFullScreen();
  4072. }
  4073. else if (document.msCancelFullScreen) {
  4074. document.msCancelFullScreen();
  4075. }
  4076. };
  4077. // External files
  4078. Tools.CleanUrl = function (url) {
  4079. url = url.replace(/#/mg, "%23");
  4080. return url;
  4081. };
  4082. Tools.LoadImage = function (url, onload, onerror, database) {
  4083. if (url instanceof ArrayBuffer) {
  4084. url = Tools.EncodeArrayBufferTobase64(url);
  4085. }
  4086. url = Tools.CleanUrl(url);
  4087. var img = new Image();
  4088. if (url.substr(0, 5) !== "data:") {
  4089. if (Tools.CorsBehavior) {
  4090. switch (typeof (Tools.CorsBehavior)) {
  4091. case "function":
  4092. var result = Tools.CorsBehavior(url);
  4093. if (result) {
  4094. img.crossOrigin = result;
  4095. }
  4096. break;
  4097. case "string":
  4098. default:
  4099. img.crossOrigin = Tools.CorsBehavior;
  4100. break;
  4101. }
  4102. }
  4103. }
  4104. img.onload = function () {
  4105. onload(img);
  4106. };
  4107. img.onerror = function (err) {
  4108. Tools.Error("Error while trying to load texture: " + url);
  4109. 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";
  4110. onload(img);
  4111. };
  4112. var noIndexedDB = function () {
  4113. img.src = url;
  4114. };
  4115. var loadFromIndexedDB = function () {
  4116. database.loadImageFromDB(url, img);
  4117. };
  4118. //ANY database to do!
  4119. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4120. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4121. }
  4122. else {
  4123. if (url.indexOf("file:") === -1) {
  4124. noIndexedDB();
  4125. }
  4126. else {
  4127. try {
  4128. var textureName = url.substring(5);
  4129. var blobURL;
  4130. try {
  4131. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4132. }
  4133. catch (ex) {
  4134. // Chrome doesn't support oneTimeOnly parameter
  4135. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4136. }
  4137. img.src = blobURL;
  4138. }
  4139. catch (e) {
  4140. img.src = null;
  4141. }
  4142. }
  4143. }
  4144. return img;
  4145. };
  4146. //ANY
  4147. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4148. url = Tools.CleanUrl(url);
  4149. var noIndexedDB = function () {
  4150. var request = new XMLHttpRequest();
  4151. var loadUrl = Tools.BaseUrl + url;
  4152. request.open('GET', loadUrl, true);
  4153. if (useArrayBuffer) {
  4154. request.responseType = "arraybuffer";
  4155. }
  4156. request.onprogress = progressCallBack;
  4157. request.onreadystatechange = function () {
  4158. if (request.readyState === 4) {
  4159. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4160. callback(!useArrayBuffer ? request.responseText : request.response);
  4161. }
  4162. else {
  4163. if (onError) {
  4164. onError();
  4165. }
  4166. else {
  4167. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4168. }
  4169. }
  4170. }
  4171. };
  4172. request.send(null);
  4173. };
  4174. var loadFromIndexedDB = function () {
  4175. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4176. };
  4177. if (url.indexOf("file:") !== -1) {
  4178. var fileName = url.substring(5);
  4179. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4180. }
  4181. else {
  4182. // Caching all files
  4183. if (database && database.enableSceneOffline) {
  4184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4185. }
  4186. else {
  4187. noIndexedDB();
  4188. }
  4189. }
  4190. };
  4191. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4192. var reader = new FileReader();
  4193. reader.onload = function (e) {
  4194. //target doesn't have result from ts 1.3
  4195. callback(e.target['result']);
  4196. };
  4197. reader.onprogress = progressCallback;
  4198. reader.readAsDataURL(fileToLoad);
  4199. };
  4200. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4201. var reader = new FileReader();
  4202. reader.onerror = function (e) {
  4203. Tools.Log("Error while reading file: " + fileToLoad.name);
  4204. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4205. };
  4206. reader.onload = function (e) {
  4207. //target doesn't have result from ts 1.3
  4208. callback(e.target['result']);
  4209. };
  4210. reader.onprogress = progressCallBack;
  4211. if (!useArrayBuffer) {
  4212. // Asynchronous read
  4213. reader.readAsText(fileToLoad);
  4214. }
  4215. else {
  4216. reader.readAsArrayBuffer(fileToLoad);
  4217. }
  4218. };
  4219. //returns a downloadable url to a file content.
  4220. Tools.FileAsURL = function (content) {
  4221. var fileBlob = new Blob([content]);
  4222. var url = window.URL || window.webkitURL;
  4223. var link = url.createObjectURL(fileBlob);
  4224. return link;
  4225. };
  4226. // Misc.
  4227. Tools.Clamp = function (value, min, max) {
  4228. if (min === void 0) { min = 0; }
  4229. if (max === void 0) { max = 1; }
  4230. return Math.min(max, Math.max(min, value));
  4231. };
  4232. // Returns -1 when value is a negative number and
  4233. // +1 when value is a positive number.
  4234. Tools.Sign = function (value) {
  4235. value = +value; // convert to a number
  4236. if (value === 0 || isNaN(value))
  4237. return value;
  4238. return value > 0 ? 1 : -1;
  4239. };
  4240. Tools.Format = function (value, decimals) {
  4241. if (decimals === void 0) { decimals = 2; }
  4242. return value.toFixed(decimals);
  4243. };
  4244. Tools.CheckExtends = function (v, min, max) {
  4245. if (v.x < min.x)
  4246. min.x = v.x;
  4247. if (v.y < min.y)
  4248. min.y = v.y;
  4249. if (v.z < min.z)
  4250. min.z = v.z;
  4251. if (v.x > max.x)
  4252. max.x = v.x;
  4253. if (v.y > max.y)
  4254. max.y = v.y;
  4255. if (v.z > max.z)
  4256. max.z = v.z;
  4257. };
  4258. Tools.WithinEpsilon = function (a, b, epsilon) {
  4259. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4260. var num = a - b;
  4261. return -epsilon <= num && num <= epsilon;
  4262. };
  4263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4264. for (var prop in source) {
  4265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4266. continue;
  4267. }
  4268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4269. continue;
  4270. }
  4271. var sourceValue = source[prop];
  4272. var typeOfSourceValue = typeof sourceValue;
  4273. if (typeOfSourceValue === "function") {
  4274. continue;
  4275. }
  4276. if (typeOfSourceValue === "object") {
  4277. if (sourceValue instanceof Array) {
  4278. destination[prop] = [];
  4279. if (sourceValue.length > 0) {
  4280. if (typeof sourceValue[0] == "object") {
  4281. for (var index = 0; index < sourceValue.length; index++) {
  4282. var clonedValue = cloneValue(sourceValue[index], destination);
  4283. if (destination[prop].indexOf(clonedValue) === -1) {
  4284. destination[prop].push(clonedValue);
  4285. }
  4286. }
  4287. }
  4288. else {
  4289. destination[prop] = sourceValue.slice(0);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = cloneValue(sourceValue, destination);
  4295. }
  4296. }
  4297. else {
  4298. destination[prop] = sourceValue;
  4299. }
  4300. }
  4301. };
  4302. Tools.IsEmpty = function (obj) {
  4303. for (var i in obj) {
  4304. return false;
  4305. }
  4306. return true;
  4307. };
  4308. Tools.RegisterTopRootEvents = function (events) {
  4309. for (var index = 0; index < events.length; index++) {
  4310. var event = events[index];
  4311. window.addEventListener(event.name, event.handler, false);
  4312. try {
  4313. if (window.parent) {
  4314. window.parent.addEventListener(event.name, event.handler, false);
  4315. }
  4316. }
  4317. catch (e) {
  4318. }
  4319. }
  4320. };
  4321. Tools.UnregisterTopRootEvents = function (events) {
  4322. for (var index = 0; index < events.length; index++) {
  4323. var event = events[index];
  4324. window.removeEventListener(event.name, event.handler);
  4325. try {
  4326. if (window.parent) {
  4327. window.parent.removeEventListener(event.name, event.handler);
  4328. }
  4329. }
  4330. catch (e) {
  4331. }
  4332. }
  4333. };
  4334. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4335. // Read the contents of the framebuffer
  4336. var numberOfChannelsByLine = width * 4;
  4337. var halfHeight = height / 2;
  4338. //Reading datas from WebGL
  4339. var data = engine.readPixels(0, 0, width, height);
  4340. //To flip image on Y axis.
  4341. for (var i = 0; i < halfHeight; i++) {
  4342. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4343. var currentCell = j + i * numberOfChannelsByLine;
  4344. var targetLine = height - i - 1;
  4345. var targetCell = j + targetLine * numberOfChannelsByLine;
  4346. var temp = data[currentCell];
  4347. data[currentCell] = data[targetCell];
  4348. data[targetCell] = temp;
  4349. }
  4350. }
  4351. // Create a 2D canvas to store the result
  4352. if (!screenshotCanvas) {
  4353. screenshotCanvas = document.createElement('canvas');
  4354. }
  4355. screenshotCanvas.width = width;
  4356. screenshotCanvas.height = height;
  4357. var context = screenshotCanvas.getContext('2d');
  4358. // Copy the pixels to a 2D canvas
  4359. var imageData = context.createImageData(width, height);
  4360. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4361. var castData = imageData.data;
  4362. castData.set(data);
  4363. context.putImageData(imageData, 0, 0);
  4364. var base64Image = screenshotCanvas.toDataURL();
  4365. if (successCallback) {
  4366. successCallback(base64Image);
  4367. }
  4368. else {
  4369. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4370. if (("download" in document.createElement("a"))) {
  4371. var a = window.document.createElement("a");
  4372. a.href = base64Image;
  4373. var date = new Date();
  4374. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4375. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4376. window.document.body.appendChild(a);
  4377. a.addEventListener("click", function () {
  4378. a.parentElement.removeChild(a);
  4379. });
  4380. a.click();
  4381. }
  4382. else {
  4383. var newWindow = window.open("");
  4384. var img = newWindow.document.createElement("img");
  4385. img.src = base64Image;
  4386. newWindow.document.body.appendChild(img);
  4387. }
  4388. }
  4389. };
  4390. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4391. var width;
  4392. var height;
  4393. //If a precision value is specified
  4394. if (size.precision) {
  4395. width = Math.round(engine.getRenderWidth() * size.precision);
  4396. height = Math.round(width / engine.getAspectRatio(camera));
  4397. size = { width: width, height: height };
  4398. }
  4399. else if (size.width && size.height) {
  4400. width = size.width;
  4401. height = size.height;
  4402. }
  4403. else if (size.width && !size.height) {
  4404. width = size.width;
  4405. height = Math.round(width / engine.getAspectRatio(camera));
  4406. size = { width: width, height: height };
  4407. }
  4408. else if (size.height && !size.width) {
  4409. height = size.height;
  4410. width = Math.round(height * engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (!isNaN(size)) {
  4414. height = size;
  4415. width = size;
  4416. }
  4417. else {
  4418. Tools.Error("Invalid 'size' parameter !");
  4419. return;
  4420. }
  4421. var scene = camera.getScene();
  4422. var previousCamera = null;
  4423. if (scene.activeCamera !== camera) {
  4424. previousCamera = scene.activeCamera;
  4425. scene.activeCamera = camera;
  4426. }
  4427. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4428. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4429. texture.renderList = scene.meshes;
  4430. texture.onAfterRender = function () {
  4431. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4432. };
  4433. scene.incrementRenderId();
  4434. texture.render(true);
  4435. texture.dispose();
  4436. if (previousCamera) {
  4437. scene.activeCamera = previousCamera;
  4438. }
  4439. };
  4440. // XHR response validator for local file scenario
  4441. Tools.ValidateXHRData = function (xhr, dataType) {
  4442. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4443. if (dataType === void 0) { dataType = 7; }
  4444. try {
  4445. if (dataType & 1) {
  4446. if (xhr.responseText && xhr.responseText.length > 0) {
  4447. return true;
  4448. }
  4449. else if (dataType === 1) {
  4450. return false;
  4451. }
  4452. }
  4453. if (dataType & 2) {
  4454. // Check header width and height since there is no "TGA" magic number
  4455. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4456. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4457. return true;
  4458. }
  4459. else if (dataType === 2) {
  4460. return false;
  4461. }
  4462. }
  4463. if (dataType & 4) {
  4464. // Check for the "DDS" magic number
  4465. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4466. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4467. return true;
  4468. }
  4469. else {
  4470. return false;
  4471. }
  4472. }
  4473. }
  4474. catch (e) {
  4475. }
  4476. return false;
  4477. };
  4478. Object.defineProperty(Tools, "NoneLogLevel", {
  4479. get: function () {
  4480. return Tools._NoneLogLevel;
  4481. },
  4482. enumerable: true,
  4483. configurable: true
  4484. });
  4485. Object.defineProperty(Tools, "MessageLogLevel", {
  4486. get: function () {
  4487. return Tools._MessageLogLevel;
  4488. },
  4489. enumerable: true,
  4490. configurable: true
  4491. });
  4492. Object.defineProperty(Tools, "WarningLogLevel", {
  4493. get: function () {
  4494. return Tools._WarningLogLevel;
  4495. },
  4496. enumerable: true,
  4497. configurable: true
  4498. });
  4499. Object.defineProperty(Tools, "ErrorLogLevel", {
  4500. get: function () {
  4501. return Tools._ErrorLogLevel;
  4502. },
  4503. enumerable: true,
  4504. configurable: true
  4505. });
  4506. Object.defineProperty(Tools, "AllLogLevel", {
  4507. get: function () {
  4508. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. Tools._AddLogEntry = function (entry) {
  4514. Tools._LogCache = entry + Tools._LogCache;
  4515. if (Tools.OnNewCacheEntry) {
  4516. Tools.OnNewCacheEntry(entry);
  4517. }
  4518. };
  4519. Tools._FormatMessage = function (message) {
  4520. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4521. var date = new Date();
  4522. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4523. };
  4524. Tools._LogDisabled = function (message) {
  4525. // nothing to do
  4526. };
  4527. Tools._LogEnabled = function (message) {
  4528. var formattedMessage = Tools._FormatMessage(message);
  4529. console.log("BJS - " + formattedMessage);
  4530. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4531. Tools._AddLogEntry(entry);
  4532. };
  4533. Tools._WarnDisabled = function (message) {
  4534. // nothing to do
  4535. };
  4536. Tools._WarnEnabled = function (message) {
  4537. var formattedMessage = Tools._FormatMessage(message);
  4538. console.warn("BJS - " + formattedMessage);
  4539. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4540. Tools._AddLogEntry(entry);
  4541. };
  4542. Tools._ErrorDisabled = function (message) {
  4543. // nothing to do
  4544. };
  4545. Tools._ErrorEnabled = function (message) {
  4546. Tools.errorsCount++;
  4547. var formattedMessage = Tools._FormatMessage(message);
  4548. console.error("BJS - " + formattedMessage);
  4549. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4550. Tools._AddLogEntry(entry);
  4551. };
  4552. Object.defineProperty(Tools, "LogCache", {
  4553. get: function () {
  4554. return Tools._LogCache;
  4555. },
  4556. enumerable: true,
  4557. configurable: true
  4558. });
  4559. Tools.ClearLogCache = function () {
  4560. Tools._LogCache = "";
  4561. Tools.errorsCount = 0;
  4562. };
  4563. Object.defineProperty(Tools, "LogLevels", {
  4564. set: function (level) {
  4565. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4566. Tools.Log = Tools._LogEnabled;
  4567. }
  4568. else {
  4569. Tools.Log = Tools._LogDisabled;
  4570. }
  4571. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4572. Tools.Warn = Tools._WarnEnabled;
  4573. }
  4574. else {
  4575. Tools.Warn = Tools._WarnDisabled;
  4576. }
  4577. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4578. Tools.Error = Tools._ErrorEnabled;
  4579. }
  4580. else {
  4581. Tools.Error = Tools._ErrorDisabled;
  4582. }
  4583. },
  4584. enumerable: true,
  4585. configurable: true
  4586. });
  4587. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4588. get: function () {
  4589. return Tools._PerformanceNoneLogLevel;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4595. get: function () {
  4596. return Tools._PerformanceUserMarkLogLevel;
  4597. },
  4598. enumerable: true,
  4599. configurable: true
  4600. });
  4601. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4602. get: function () {
  4603. return Tools._PerformanceConsoleLogLevel;
  4604. },
  4605. enumerable: true,
  4606. configurable: true
  4607. });
  4608. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4609. set: function (level) {
  4610. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4611. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4612. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4613. return;
  4614. }
  4615. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4616. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4617. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4618. return;
  4619. }
  4620. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4621. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4622. },
  4623. enumerable: true,
  4624. configurable: true
  4625. });
  4626. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4627. };
  4628. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4629. };
  4630. Tools._StartUserMark = function (counterName, condition) {
  4631. if (condition === void 0) { condition = true; }
  4632. if (!condition || !Tools._performance.mark) {
  4633. return;
  4634. }
  4635. Tools._performance.mark(counterName + "-Begin");
  4636. };
  4637. Tools._EndUserMark = function (counterName, condition) {
  4638. if (condition === void 0) { condition = true; }
  4639. if (!condition || !Tools._performance.mark) {
  4640. return;
  4641. }
  4642. Tools._performance.mark(counterName + "-End");
  4643. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4644. };
  4645. Tools._StartPerformanceConsole = function (counterName, condition) {
  4646. if (condition === void 0) { condition = true; }
  4647. if (!condition) {
  4648. return;
  4649. }
  4650. Tools._StartUserMark(counterName, condition);
  4651. if (console.time) {
  4652. console.time(counterName);
  4653. }
  4654. };
  4655. Tools._EndPerformanceConsole = function (counterName, condition) {
  4656. if (condition === void 0) { condition = true; }
  4657. if (!condition) {
  4658. return;
  4659. }
  4660. Tools._EndUserMark(counterName, condition);
  4661. if (console.time) {
  4662. console.timeEnd(counterName);
  4663. }
  4664. };
  4665. Object.defineProperty(Tools, "Now", {
  4666. get: function () {
  4667. if (window.performance && window.performance.now) {
  4668. return window.performance.now();
  4669. }
  4670. return new Date().getTime();
  4671. },
  4672. enumerable: true,
  4673. configurable: true
  4674. });
  4675. Tools.BaseUrl = "";
  4676. Tools.CorsBehavior = "anonymous";
  4677. // Logs
  4678. Tools._NoneLogLevel = 0;
  4679. Tools._MessageLogLevel = 1;
  4680. Tools._WarningLogLevel = 2;
  4681. Tools._ErrorLogLevel = 4;
  4682. Tools._LogCache = "";
  4683. Tools.errorsCount = 0;
  4684. Tools.Log = Tools._LogEnabled;
  4685. Tools.Warn = Tools._WarnEnabled;
  4686. Tools.Error = Tools._ErrorEnabled;
  4687. // Performances
  4688. Tools._PerformanceNoneLogLevel = 0;
  4689. Tools._PerformanceUserMarkLogLevel = 1;
  4690. Tools._PerformanceConsoleLogLevel = 2;
  4691. Tools._performance = window.performance;
  4692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4694. return Tools;
  4695. })();
  4696. BABYLON.Tools = Tools;
  4697. /**
  4698. * An implementation of a loop for asynchronous functions.
  4699. */
  4700. var AsyncLoop = (function () {
  4701. /**
  4702. * Constroctor.
  4703. * @param iterations the number of iterations.
  4704. * @param _fn the function to run each iteration
  4705. * @param _successCallback the callback that will be called upon succesful execution
  4706. * @param offset starting offset.
  4707. */
  4708. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4709. if (offset === void 0) { offset = 0; }
  4710. this.iterations = iterations;
  4711. this._fn = _fn;
  4712. this._successCallback = _successCallback;
  4713. this.index = offset - 1;
  4714. this._done = false;
  4715. }
  4716. /**
  4717. * Execute the next iteration. Must be called after the last iteration was finished.
  4718. */
  4719. AsyncLoop.prototype.executeNext = function () {
  4720. if (!this._done) {
  4721. if (this.index + 1 < this.iterations) {
  4722. ++this.index;
  4723. this._fn(this);
  4724. }
  4725. else {
  4726. this.breakLoop();
  4727. }
  4728. }
  4729. };
  4730. /**
  4731. * Break the loop and run the success callback.
  4732. */
  4733. AsyncLoop.prototype.breakLoop = function () {
  4734. this._done = true;
  4735. this._successCallback();
  4736. };
  4737. /**
  4738. * Helper function
  4739. */
  4740. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4741. if (offset === void 0) { offset = 0; }
  4742. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4743. loop.executeNext();
  4744. return loop;
  4745. };
  4746. /**
  4747. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4748. * @param iterations total number of iterations
  4749. * @param syncedIterations number of synchronous iterations in each async iteration.
  4750. * @param fn the function to call each iteration.
  4751. * @param callback a success call back that will be called when iterating stops.
  4752. * @param breakFunction a break condition (optional)
  4753. * @param timeout timeout settings for the setTimeout function. default - 0.
  4754. * @constructor
  4755. */
  4756. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4757. if (timeout === void 0) { timeout = 0; }
  4758. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4759. if (breakFunction && breakFunction())
  4760. loop.breakLoop();
  4761. else {
  4762. setTimeout(function () {
  4763. for (var i = 0; i < syncedIterations; ++i) {
  4764. var iteration = (loop.index * syncedIterations) + i;
  4765. if (iteration >= iterations)
  4766. break;
  4767. fn(iteration);
  4768. if (breakFunction && breakFunction()) {
  4769. loop.breakLoop();
  4770. break;
  4771. }
  4772. }
  4773. loop.executeNext();
  4774. }, timeout);
  4775. }
  4776. }, callback);
  4777. };
  4778. return AsyncLoop;
  4779. })();
  4780. BABYLON.AsyncLoop = AsyncLoop;
  4781. })(BABYLON || (BABYLON = {}));
  4782. var BABYLON;
  4783. (function (BABYLON) {
  4784. var _DepthCullingState = (function () {
  4785. function _DepthCullingState() {
  4786. this._isDepthTestDirty = false;
  4787. this._isDepthMaskDirty = false;
  4788. this._isDepthFuncDirty = false;
  4789. this._isCullFaceDirty = false;
  4790. this._isCullDirty = false;
  4791. this._isZOffsetDirty = false;
  4792. }
  4793. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4794. get: function () {
  4795. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4801. get: function () {
  4802. return this._zOffset;
  4803. },
  4804. set: function (value) {
  4805. if (this._zOffset === value) {
  4806. return;
  4807. }
  4808. this._zOffset = value;
  4809. this._isZOffsetDirty = true;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4815. get: function () {
  4816. return this._cullFace;
  4817. },
  4818. set: function (value) {
  4819. if (this._cullFace === value) {
  4820. return;
  4821. }
  4822. this._cullFace = value;
  4823. this._isCullFaceDirty = true;
  4824. },
  4825. enumerable: true,
  4826. configurable: true
  4827. });
  4828. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4829. get: function () {
  4830. return this._cull;
  4831. },
  4832. set: function (value) {
  4833. if (this._cull === value) {
  4834. return;
  4835. }
  4836. this._cull = value;
  4837. this._isCullDirty = true;
  4838. },
  4839. enumerable: true,
  4840. configurable: true
  4841. });
  4842. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4843. get: function () {
  4844. return this._depthFunc;
  4845. },
  4846. set: function (value) {
  4847. if (this._depthFunc === value) {
  4848. return;
  4849. }
  4850. this._depthFunc = value;
  4851. this._isDepthFuncDirty = true;
  4852. },
  4853. enumerable: true,
  4854. configurable: true
  4855. });
  4856. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4857. get: function () {
  4858. return this._depthMask;
  4859. },
  4860. set: function (value) {
  4861. if (this._depthMask === value) {
  4862. return;
  4863. }
  4864. this._depthMask = value;
  4865. this._isDepthMaskDirty = true;
  4866. },
  4867. enumerable: true,
  4868. configurable: true
  4869. });
  4870. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4871. get: function () {
  4872. return this._depthTest;
  4873. },
  4874. set: function (value) {
  4875. if (this._depthTest === value) {
  4876. return;
  4877. }
  4878. this._depthTest = value;
  4879. this._isDepthTestDirty = true;
  4880. },
  4881. enumerable: true,
  4882. configurable: true
  4883. });
  4884. _DepthCullingState.prototype.reset = function () {
  4885. this._depthMask = true;
  4886. this._depthTest = true;
  4887. this._depthFunc = null;
  4888. this._cull = null;
  4889. this._cullFace = null;
  4890. this._zOffset = 0;
  4891. this._isDepthTestDirty = true;
  4892. this._isDepthMaskDirty = true;
  4893. this._isDepthFuncDirty = false;
  4894. this._isCullFaceDirty = false;
  4895. this._isCullDirty = false;
  4896. this._isZOffsetDirty = false;
  4897. };
  4898. _DepthCullingState.prototype.apply = function (gl) {
  4899. if (!this.isDirty) {
  4900. return;
  4901. }
  4902. // Cull
  4903. if (this._isCullDirty) {
  4904. if (this.cull) {
  4905. gl.enable(gl.CULL_FACE);
  4906. }
  4907. else {
  4908. gl.disable(gl.CULL_FACE);
  4909. }
  4910. this._isCullDirty = false;
  4911. }
  4912. // Cull face
  4913. if (this._isCullFaceDirty) {
  4914. gl.cullFace(this.cullFace);
  4915. this._isCullFaceDirty = false;
  4916. }
  4917. // Depth mask
  4918. if (this._isDepthMaskDirty) {
  4919. gl.depthMask(this.depthMask);
  4920. this._isDepthMaskDirty = false;
  4921. }
  4922. // Depth test
  4923. if (this._isDepthTestDirty) {
  4924. if (this.depthTest) {
  4925. gl.enable(gl.DEPTH_TEST);
  4926. }
  4927. else {
  4928. gl.disable(gl.DEPTH_TEST);
  4929. }
  4930. this._isDepthTestDirty = false;
  4931. }
  4932. // Depth func
  4933. if (this._isDepthFuncDirty) {
  4934. gl.depthFunc(this.depthFunc);
  4935. this._isDepthFuncDirty = false;
  4936. }
  4937. // zOffset
  4938. if (this._isZOffsetDirty) {
  4939. if (this.zOffset) {
  4940. gl.enable(gl.POLYGON_OFFSET_FILL);
  4941. gl.polygonOffset(this.zOffset, 0);
  4942. }
  4943. else {
  4944. gl.disable(gl.POLYGON_OFFSET_FILL);
  4945. }
  4946. this._isZOffsetDirty = false;
  4947. }
  4948. };
  4949. return _DepthCullingState;
  4950. })();
  4951. BABYLON._DepthCullingState = _DepthCullingState;
  4952. var _AlphaState = (function () {
  4953. function _AlphaState() {
  4954. this._isAlphaBlendDirty = false;
  4955. this._isBlendFunctionParametersDirty = false;
  4956. this._alphaBlend = false;
  4957. this._blendFunctionParameters = new Array(4);
  4958. }
  4959. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4960. get: function () {
  4961. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4967. get: function () {
  4968. return this._alphaBlend;
  4969. },
  4970. set: function (value) {
  4971. if (this._alphaBlend === value) {
  4972. return;
  4973. }
  4974. this._alphaBlend = value;
  4975. this._isAlphaBlendDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4981. if (this._blendFunctionParameters[0] === value0 &&
  4982. this._blendFunctionParameters[1] === value1 &&
  4983. this._blendFunctionParameters[2] === value2 &&
  4984. this._blendFunctionParameters[3] === value3) {
  4985. return;
  4986. }
  4987. this._blendFunctionParameters[0] = value0;
  4988. this._blendFunctionParameters[1] = value1;
  4989. this._blendFunctionParameters[2] = value2;
  4990. this._blendFunctionParameters[3] = value3;
  4991. this._isBlendFunctionParametersDirty = true;
  4992. };
  4993. _AlphaState.prototype.reset = function () {
  4994. this._alphaBlend = false;
  4995. this._blendFunctionParameters[0] = null;
  4996. this._blendFunctionParameters[1] = null;
  4997. this._blendFunctionParameters[2] = null;
  4998. this._blendFunctionParameters[3] = null;
  4999. this._isAlphaBlendDirty = true;
  5000. this._isBlendFunctionParametersDirty = false;
  5001. };
  5002. _AlphaState.prototype.apply = function (gl) {
  5003. if (!this.isDirty) {
  5004. return;
  5005. }
  5006. // Alpha blend
  5007. if (this._isAlphaBlendDirty) {
  5008. if (this._alphaBlend) {
  5009. gl.enable(gl.BLEND);
  5010. }
  5011. else {
  5012. gl.disable(gl.BLEND);
  5013. }
  5014. this._isAlphaBlendDirty = false;
  5015. }
  5016. // Alpha function
  5017. if (this._isBlendFunctionParametersDirty) {
  5018. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5019. this._isBlendFunctionParametersDirty = false;
  5020. }
  5021. };
  5022. return _AlphaState;
  5023. })();
  5024. BABYLON._AlphaState = _AlphaState;
  5025. var compileShader = function (gl, source, type, defines) {
  5026. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5027. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5028. gl.compileShader(shader);
  5029. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5030. throw new Error(gl.getShaderInfoLog(shader));
  5031. }
  5032. return shader;
  5033. };
  5034. var getWebGLTextureType = function (gl, type) {
  5035. var textureType = gl.UNSIGNED_BYTE;
  5036. if (type === Engine.TEXTURETYPE_FLOAT)
  5037. textureType = gl.FLOAT;
  5038. return textureType;
  5039. };
  5040. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5041. var magFilter = gl.NEAREST;
  5042. var minFilter = gl.NEAREST;
  5043. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5044. magFilter = gl.LINEAR;
  5045. if (generateMipMaps) {
  5046. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5047. }
  5048. else {
  5049. minFilter = gl.LINEAR;
  5050. }
  5051. }
  5052. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5053. magFilter = gl.LINEAR;
  5054. if (generateMipMaps) {
  5055. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5056. }
  5057. else {
  5058. minFilter = gl.LINEAR;
  5059. }
  5060. }
  5061. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5062. magFilter = gl.NEAREST;
  5063. if (generateMipMaps) {
  5064. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5065. }
  5066. else {
  5067. minFilter = gl.NEAREST;
  5068. }
  5069. }
  5070. return {
  5071. min: minFilter,
  5072. mag: magFilter
  5073. };
  5074. };
  5075. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5077. var engine = scene.getEngine();
  5078. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5079. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5080. gl.bindTexture(gl.TEXTURE_2D, texture);
  5081. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5082. texture._baseWidth = width;
  5083. texture._baseHeight = height;
  5084. texture._width = potWidth;
  5085. texture._height = potHeight;
  5086. texture.isReady = true;
  5087. processFunction(potWidth, potHeight);
  5088. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5091. if (!noMipmap && !isCompressed) {
  5092. gl.generateMipmap(gl.TEXTURE_2D);
  5093. }
  5094. gl.bindTexture(gl.TEXTURE_2D, null);
  5095. engine.resetTextureCache();
  5096. scene._removePendingData(texture);
  5097. };
  5098. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5099. var img;
  5100. var onload = function () {
  5101. loadedImages[index] = img;
  5102. loadedImages._internalCount++;
  5103. scene._removePendingData(img);
  5104. if (loadedImages._internalCount === 6) {
  5105. onfinish(loadedImages);
  5106. }
  5107. };
  5108. var onerror = function () {
  5109. scene._removePendingData(img);
  5110. };
  5111. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5112. scene._addPendingData(img);
  5113. };
  5114. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5115. var loadedImages = [];
  5116. loadedImages._internalCount = 0;
  5117. for (var index = 0; index < 6; index++) {
  5118. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5119. }
  5120. };
  5121. var EngineCapabilities = (function () {
  5122. function EngineCapabilities() {
  5123. }
  5124. return EngineCapabilities;
  5125. })();
  5126. BABYLON.EngineCapabilities = EngineCapabilities;
  5127. /**
  5128. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5129. */
  5130. var Engine = (function () {
  5131. /**
  5132. * @constructor
  5133. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5134. * @param {boolean} [antialias] - enable antialias
  5135. * @param options - further options to be sent to the getContext function
  5136. */
  5137. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5138. var _this = this;
  5139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5140. // Public members
  5141. this.isFullscreen = false;
  5142. this.isPointerLock = false;
  5143. this.cullBackFaces = true;
  5144. this.renderEvenInBackground = true;
  5145. // To enable/disable IDB support and avoid XHR on .manifest
  5146. this.enableOfflineSupport = true;
  5147. this.scenes = new Array();
  5148. this._windowIsBackground = false;
  5149. this._drawCalls = 0;
  5150. this._renderingQueueLaunched = false;
  5151. this._activeRenderLoops = [];
  5152. // FPS
  5153. this.fpsRange = 60;
  5154. this.previousFramesDuration = [];
  5155. this.fps = 60;
  5156. this.deltaTime = 0;
  5157. // States
  5158. this._depthCullingState = new _DepthCullingState();
  5159. this._alphaState = new _AlphaState();
  5160. this._alphaMode = Engine.ALPHA_DISABLE;
  5161. // Cache
  5162. this._loadedTexturesCache = new Array();
  5163. this._maxTextureChannels = 16;
  5164. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5165. this._compiledEffects = {};
  5166. this._uintIndicesCurrentlySet = false;
  5167. this._renderingCanvas = canvas;
  5168. options = options || {};
  5169. options.antialias = antialias;
  5170. if (options.preserveDrawingBuffer === undefined) {
  5171. options.preserveDrawingBuffer = false;
  5172. }
  5173. // GL
  5174. try {
  5175. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5176. }
  5177. catch (e) {
  5178. throw new Error("WebGL not supported");
  5179. }
  5180. if (!this._gl) {
  5181. throw new Error("WebGL not supported");
  5182. }
  5183. this._onBlur = function () {
  5184. _this._windowIsBackground = true;
  5185. };
  5186. this._onFocus = function () {
  5187. _this._windowIsBackground = false;
  5188. };
  5189. window.addEventListener("blur", this._onBlur);
  5190. window.addEventListener("focus", this._onFocus);
  5191. // Viewport
  5192. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5193. this.resize();
  5194. // Caps
  5195. this._caps = new EngineCapabilities();
  5196. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5197. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5198. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5199. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5200. // Infos
  5201. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5202. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5203. if (rendererInfo != null) {
  5204. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5205. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5206. }
  5207. if (!this._glVendor) {
  5208. this._glVendor = "Unknown vendor";
  5209. }
  5210. if (!this._glRenderer) {
  5211. this._glRenderer = "Unknown renderer";
  5212. }
  5213. // Extensions
  5214. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5215. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5216. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5217. 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');
  5218. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5219. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5220. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5221. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5222. this._caps.highPrecisionShaderSupported = true;
  5223. if (this._gl.getShaderPrecisionFormat) {
  5224. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5225. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5226. }
  5227. // Depth buffer
  5228. this.setDepthBuffer(true);
  5229. this.setDepthFunctionToLessOrEqual();
  5230. this.setDepthWrite(true);
  5231. // Fullscreen
  5232. this._onFullscreenChange = function () {
  5233. if (document.fullscreen !== undefined) {
  5234. _this.isFullscreen = document.fullscreen;
  5235. }
  5236. else if (document.mozFullScreen !== undefined) {
  5237. _this.isFullscreen = document.mozFullScreen;
  5238. }
  5239. else if (document.webkitIsFullScreen !== undefined) {
  5240. _this.isFullscreen = document.webkitIsFullScreen;
  5241. }
  5242. else if (document.msIsFullScreen !== undefined) {
  5243. _this.isFullscreen = document.msIsFullScreen;
  5244. }
  5245. // Pointer lock
  5246. if (_this.isFullscreen && _this._pointerLockRequested) {
  5247. canvas.requestPointerLock = canvas.requestPointerLock ||
  5248. canvas.msRequestPointerLock ||
  5249. canvas.mozRequestPointerLock ||
  5250. canvas.webkitRequestPointerLock;
  5251. if (canvas.requestPointerLock) {
  5252. canvas.requestPointerLock();
  5253. }
  5254. }
  5255. };
  5256. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5257. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5258. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5259. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5260. // Pointer lock
  5261. this._onPointerLockChange = function () {
  5262. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5263. document.webkitPointerLockElement === canvas ||
  5264. document.msPointerLockElement === canvas ||
  5265. document.pointerLockElement === canvas);
  5266. };
  5267. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5268. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5269. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5270. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5271. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5272. Engine.audioEngine = new BABYLON.AudioEngine();
  5273. }
  5274. //default loading screen
  5275. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5276. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5277. }
  5278. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5279. get: function () {
  5280. return Engine._ALPHA_DISABLE;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5286. get: function () {
  5287. return Engine._ALPHA_ONEONE;
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Object.defineProperty(Engine, "ALPHA_ADD", {
  5293. get: function () {
  5294. return Engine._ALPHA_ADD;
  5295. },
  5296. enumerable: true,
  5297. configurable: true
  5298. });
  5299. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5300. get: function () {
  5301. return Engine._ALPHA_COMBINE;
  5302. },
  5303. enumerable: true,
  5304. configurable: true
  5305. });
  5306. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5307. get: function () {
  5308. return Engine._ALPHA_SUBTRACT;
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5314. get: function () {
  5315. return Engine._ALPHA_MULTIPLY;
  5316. },
  5317. enumerable: true,
  5318. configurable: true
  5319. });
  5320. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5321. get: function () {
  5322. return Engine._ALPHA_MAXIMIZED;
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5328. get: function () {
  5329. return Engine._DELAYLOADSTATE_NONE;
  5330. },
  5331. enumerable: true,
  5332. configurable: true
  5333. });
  5334. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5335. get: function () {
  5336. return Engine._DELAYLOADSTATE_LOADED;
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5342. get: function () {
  5343. return Engine._DELAYLOADSTATE_LOADING;
  5344. },
  5345. enumerable: true,
  5346. configurable: true
  5347. });
  5348. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5349. get: function () {
  5350. return Engine._DELAYLOADSTATE_NOTLOADED;
  5351. },
  5352. enumerable: true,
  5353. configurable: true
  5354. });
  5355. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5356. get: function () {
  5357. return Engine._TEXTUREFORMAT_ALPHA;
  5358. },
  5359. enumerable: true,
  5360. configurable: true
  5361. });
  5362. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5363. get: function () {
  5364. return Engine._TEXTUREFORMAT_LUMINANCE;
  5365. },
  5366. enumerable: true,
  5367. configurable: true
  5368. });
  5369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5370. get: function () {
  5371. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5372. },
  5373. enumerable: true,
  5374. configurable: true
  5375. });
  5376. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5377. get: function () {
  5378. return Engine._TEXTUREFORMAT_RGB;
  5379. },
  5380. enumerable: true,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5384. get: function () {
  5385. return Engine._TEXTUREFORMAT_RGBA;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5391. get: function () {
  5392. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5398. get: function () {
  5399. return Engine._TEXTURETYPE_FLOAT;
  5400. },
  5401. enumerable: true,
  5402. configurable: true
  5403. });
  5404. Object.defineProperty(Engine, "Version", {
  5405. get: function () {
  5406. return "2.3.0-alpha";
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Engine.prototype._prepareWorkingCanvas = function () {
  5412. if (this._workingCanvas) {
  5413. return;
  5414. }
  5415. this._workingCanvas = document.createElement("canvas");
  5416. this._workingContext = this._workingCanvas.getContext("2d");
  5417. };
  5418. Engine.prototype.resetTextureCache = function () {
  5419. for (var index = 0; index < this._maxTextureChannels; index++) {
  5420. this._activeTexturesCache[index] = null;
  5421. }
  5422. };
  5423. Engine.prototype.getGlInfo = function () {
  5424. return {
  5425. vendor: this._glVendor,
  5426. renderer: this._glRenderer,
  5427. version: this._glVersion
  5428. };
  5429. };
  5430. Engine.prototype.getAspectRatio = function (camera) {
  5431. var viewport = camera.viewport;
  5432. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5433. };
  5434. Engine.prototype.getRenderWidth = function () {
  5435. if (this._currentRenderTarget) {
  5436. return this._currentRenderTarget._width;
  5437. }
  5438. return this._renderingCanvas.width;
  5439. };
  5440. Engine.prototype.getRenderHeight = function () {
  5441. if (this._currentRenderTarget) {
  5442. return this._currentRenderTarget._height;
  5443. }
  5444. return this._renderingCanvas.height;
  5445. };
  5446. Engine.prototype.getRenderingCanvas = function () {
  5447. return this._renderingCanvas;
  5448. };
  5449. Engine.prototype.getRenderingCanvasClientRect = function () {
  5450. return this._renderingCanvas.getBoundingClientRect();
  5451. };
  5452. Engine.prototype.setHardwareScalingLevel = function (level) {
  5453. this._hardwareScalingLevel = level;
  5454. this.resize();
  5455. };
  5456. Engine.prototype.getHardwareScalingLevel = function () {
  5457. return this._hardwareScalingLevel;
  5458. };
  5459. Engine.prototype.getLoadedTexturesCache = function () {
  5460. return this._loadedTexturesCache;
  5461. };
  5462. Engine.prototype.getCaps = function () {
  5463. return this._caps;
  5464. };
  5465. Object.defineProperty(Engine.prototype, "drawCalls", {
  5466. get: function () {
  5467. return this._drawCalls;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. // Methods
  5473. Engine.prototype.resetDrawCalls = function () {
  5474. this._drawCalls = 0;
  5475. };
  5476. Engine.prototype.setDepthFunctionToGreater = function () {
  5477. this._depthCullingState.depthFunc = this._gl.GREATER;
  5478. };
  5479. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5480. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5481. };
  5482. Engine.prototype.setDepthFunctionToLess = function () {
  5483. this._depthCullingState.depthFunc = this._gl.LESS;
  5484. };
  5485. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5486. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5487. };
  5488. /**
  5489. * stop executing a render loop function and remove it from the execution array
  5490. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5491. */
  5492. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5493. if (!renderFunction) {
  5494. this._activeRenderLoops = [];
  5495. return;
  5496. }
  5497. var index = this._activeRenderLoops.indexOf(renderFunction);
  5498. if (index >= 0) {
  5499. this._activeRenderLoops.splice(index, 1);
  5500. }
  5501. };
  5502. Engine.prototype._renderLoop = function () {
  5503. var shouldRender = true;
  5504. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5505. shouldRender = false;
  5506. }
  5507. if (shouldRender) {
  5508. // Start new frame
  5509. this.beginFrame();
  5510. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5511. var renderFunction = this._activeRenderLoops[index];
  5512. renderFunction();
  5513. }
  5514. // Present
  5515. this.endFrame();
  5516. }
  5517. if (this._activeRenderLoops.length > 0) {
  5518. // Register new frame
  5519. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5520. }
  5521. else {
  5522. this._renderingQueueLaunched = false;
  5523. }
  5524. };
  5525. /**
  5526. * Register and execute a render loop. The engine can have more than one render function.
  5527. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5528. * @example
  5529. * engine.runRenderLoop(function () {
  5530. * scene.render()
  5531. * })
  5532. */
  5533. Engine.prototype.runRenderLoop = function (renderFunction) {
  5534. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5535. return;
  5536. }
  5537. this._activeRenderLoops.push(renderFunction);
  5538. if (!this._renderingQueueLaunched) {
  5539. this._renderingQueueLaunched = true;
  5540. this._bindedRenderFunction = this._renderLoop.bind(this);
  5541. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5542. }
  5543. };
  5544. /**
  5545. * Toggle full screen mode.
  5546. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5547. */
  5548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5549. if (this.isFullscreen) {
  5550. BABYLON.Tools.ExitFullscreen();
  5551. }
  5552. else {
  5553. this._pointerLockRequested = requestPointerLock;
  5554. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5555. }
  5556. };
  5557. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5558. this.applyStates();
  5559. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5560. if (this._depthCullingState.depthMask) {
  5561. this._gl.clearDepth(1.0);
  5562. }
  5563. var mode = 0;
  5564. if (backBuffer)
  5565. mode |= this._gl.COLOR_BUFFER_BIT;
  5566. if (depthStencil && this._depthCullingState.depthMask)
  5567. mode |= this._gl.DEPTH_BUFFER_BIT;
  5568. this._gl.clear(mode);
  5569. };
  5570. /**
  5571. * Set the WebGL's viewport
  5572. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5573. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5574. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5575. */
  5576. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5577. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5578. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5579. var x = viewport.x || 0;
  5580. var y = viewport.y || 0;
  5581. this._cachedViewport = viewport;
  5582. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5583. };
  5584. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5585. this._cachedViewport = null;
  5586. this._gl.viewport(x, y, width, height);
  5587. };
  5588. Engine.prototype.beginFrame = function () {
  5589. this._measureFps();
  5590. };
  5591. Engine.prototype.endFrame = function () {
  5592. //this.flushFramebuffer();
  5593. };
  5594. /**
  5595. * resize the view according to the canvas' size.
  5596. * @example
  5597. * window.addEventListener("resize", function () {
  5598. * engine.resize();
  5599. * });
  5600. */
  5601. Engine.prototype.resize = function () {
  5602. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5603. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5604. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5605. for (var index = 0; index < this.scenes.length; index++) {
  5606. var scene = this.scenes[index];
  5607. if (scene.debugLayer.isVisible()) {
  5608. scene.debugLayer._syncPositions();
  5609. }
  5610. }
  5611. };
  5612. /**
  5613. * force a specific size of the canvas
  5614. * @param {number} width - the new canvas' width
  5615. * @param {number} height - the new canvas' height
  5616. */
  5617. Engine.prototype.setSize = function (width, height) {
  5618. this._renderingCanvas.width = width;
  5619. this._renderingCanvas.height = height;
  5620. for (var index = 0; index < this.scenes.length; index++) {
  5621. var scene = this.scenes[index];
  5622. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5623. var cam = scene.cameras[camIndex];
  5624. cam._currentRenderId = 0;
  5625. }
  5626. }
  5627. };
  5628. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5629. this._currentRenderTarget = texture;
  5630. var gl = this._gl;
  5631. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5632. if (texture.isCube) {
  5633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5634. }
  5635. else {
  5636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5637. }
  5638. this._gl.viewport(0, 0, texture._width, texture._height);
  5639. this.wipeCaches();
  5640. };
  5641. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5642. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5643. this._currentRenderTarget = null;
  5644. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5645. var gl = this._gl;
  5646. gl.bindTexture(gl.TEXTURE_2D, texture);
  5647. gl.generateMipmap(gl.TEXTURE_2D);
  5648. gl.bindTexture(gl.TEXTURE_2D, null);
  5649. }
  5650. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5651. };
  5652. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5653. if (texture.generateMipMaps) {
  5654. var gl = this._gl;
  5655. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5657. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5658. }
  5659. };
  5660. Engine.prototype.flushFramebuffer = function () {
  5661. this._gl.flush();
  5662. };
  5663. Engine.prototype.restoreDefaultFramebuffer = function () {
  5664. this._currentRenderTarget = null;
  5665. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5666. this.setViewport(this._cachedViewport);
  5667. this.wipeCaches();
  5668. };
  5669. // VBOs
  5670. Engine.prototype._resetVertexBufferBinding = function () {
  5671. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5672. this._cachedVertexBuffers = null;
  5673. };
  5674. Engine.prototype.createVertexBuffer = function (vertices) {
  5675. var vbo = this._gl.createBuffer();
  5676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5677. if (vertices instanceof Float32Array) {
  5678. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5679. }
  5680. else {
  5681. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5682. }
  5683. this._resetVertexBufferBinding();
  5684. vbo.references = 1;
  5685. return vbo;
  5686. };
  5687. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5688. var vbo = this._gl.createBuffer();
  5689. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5690. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5691. this._resetVertexBufferBinding();
  5692. vbo.references = 1;
  5693. return vbo;
  5694. };
  5695. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5696. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5697. if (offset === undefined) {
  5698. offset = 0;
  5699. }
  5700. if (vertices instanceof Float32Array) {
  5701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5702. }
  5703. else {
  5704. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5705. }
  5706. this._resetVertexBufferBinding();
  5707. };
  5708. Engine.prototype._resetIndexBufferBinding = function () {
  5709. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5710. this._cachedIndexBuffer = null;
  5711. };
  5712. Engine.prototype.createIndexBuffer = function (indices) {
  5713. var vbo = this._gl.createBuffer();
  5714. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5715. // Check for 32 bits indices
  5716. var arrayBuffer;
  5717. var need32Bits = false;
  5718. if (this._caps.uintIndices) {
  5719. for (var index = 0; index < indices.length; index++) {
  5720. if (indices[index] > 65535) {
  5721. need32Bits = true;
  5722. break;
  5723. }
  5724. }
  5725. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5726. }
  5727. else {
  5728. arrayBuffer = new Uint16Array(indices);
  5729. }
  5730. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5731. this._resetIndexBufferBinding();
  5732. vbo.references = 1;
  5733. vbo.is32Bits = need32Bits;
  5734. return vbo;
  5735. };
  5736. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5737. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5738. this._cachedVertexBuffers = vertexBuffer;
  5739. this._cachedEffectForVertexBuffers = effect;
  5740. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5741. var offset = 0;
  5742. for (var index = 0; index < vertexDeclaration.length; index++) {
  5743. var order = effect.getAttributeLocation(index);
  5744. if (order >= 0) {
  5745. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5746. }
  5747. offset += vertexDeclaration[index] * 4;
  5748. }
  5749. }
  5750. if (this._cachedIndexBuffer !== indexBuffer) {
  5751. this._cachedIndexBuffer = indexBuffer;
  5752. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5753. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5754. }
  5755. };
  5756. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5757. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5758. this._cachedVertexBuffers = vertexBuffers;
  5759. this._cachedEffectForVertexBuffers = effect;
  5760. var attributes = effect.getAttributesNames();
  5761. for (var index = 0; index < attributes.length; index++) {
  5762. var order = effect.getAttributeLocation(index);
  5763. if (order >= 0) {
  5764. var vertexBuffer = vertexBuffers[attributes[index]];
  5765. if (!vertexBuffer) {
  5766. continue;
  5767. }
  5768. var stride = vertexBuffer.getStrideSize();
  5769. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5770. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5771. }
  5772. }
  5773. }
  5774. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5775. this._cachedIndexBuffer = indexBuffer;
  5776. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5777. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5778. }
  5779. };
  5780. Engine.prototype._releaseBuffer = function (buffer) {
  5781. buffer.references--;
  5782. if (buffer.references === 0) {
  5783. this._gl.deleteBuffer(buffer);
  5784. return true;
  5785. }
  5786. return false;
  5787. };
  5788. Engine.prototype.createInstancesBuffer = function (capacity) {
  5789. var buffer = this._gl.createBuffer();
  5790. buffer.capacity = capacity;
  5791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5792. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5793. return buffer;
  5794. };
  5795. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5796. this._gl.deleteBuffer(buffer);
  5797. };
  5798. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5799. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5801. for (var index = 0; index < 4; index++) {
  5802. var offsetLocation = offsetLocations[index];
  5803. this._gl.enableVertexAttribArray(offsetLocation);
  5804. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5805. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5806. }
  5807. };
  5808. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5809. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5810. for (var index = 0; index < 4; index++) {
  5811. var offsetLocation = offsetLocations[index];
  5812. this._gl.disableVertexAttribArray(offsetLocation);
  5813. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5814. }
  5815. };
  5816. Engine.prototype.applyStates = function () {
  5817. this._depthCullingState.apply(this._gl);
  5818. this._alphaState.apply(this._gl);
  5819. };
  5820. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5821. // Apply states
  5822. this.applyStates();
  5823. this._drawCalls++;
  5824. // Render
  5825. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5826. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5827. if (instancesCount) {
  5828. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5829. return;
  5830. }
  5831. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5832. };
  5833. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5834. // Apply states
  5835. this.applyStates();
  5836. this._drawCalls++;
  5837. if (instancesCount) {
  5838. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5839. return;
  5840. }
  5841. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5842. };
  5843. // Shaders
  5844. Engine.prototype._releaseEffect = function (effect) {
  5845. if (this._compiledEffects[effect._key]) {
  5846. delete this._compiledEffects[effect._key];
  5847. if (effect.getProgram()) {
  5848. this._gl.deleteProgram(effect.getProgram());
  5849. }
  5850. }
  5851. };
  5852. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5853. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5854. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5855. var name = vertex + "+" + fragment + "@" + defines;
  5856. if (this._compiledEffects[name]) {
  5857. return this._compiledEffects[name];
  5858. }
  5859. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5860. effect._key = name;
  5861. this._compiledEffects[name] = effect;
  5862. return effect;
  5863. };
  5864. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5865. if (uniformsNames === void 0) { uniformsNames = []; }
  5866. if (samplers === void 0) { samplers = []; }
  5867. if (defines === void 0) { defines = ""; }
  5868. return this.createEffect({
  5869. vertex: "particles",
  5870. fragmentElement: fragmentName
  5871. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5872. };
  5873. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5874. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5875. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5876. var shaderProgram = this._gl.createProgram();
  5877. this._gl.attachShader(shaderProgram, vertexShader);
  5878. this._gl.attachShader(shaderProgram, fragmentShader);
  5879. this._gl.linkProgram(shaderProgram);
  5880. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5881. if (!linked) {
  5882. var error = this._gl.getProgramInfoLog(shaderProgram);
  5883. if (error) {
  5884. throw new Error(error);
  5885. }
  5886. }
  5887. this._gl.deleteShader(vertexShader);
  5888. this._gl.deleteShader(fragmentShader);
  5889. return shaderProgram;
  5890. };
  5891. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5892. var results = [];
  5893. for (var index = 0; index < uniformsNames.length; index++) {
  5894. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5895. }
  5896. return results;
  5897. };
  5898. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5899. var results = [];
  5900. for (var index = 0; index < attributesNames.length; index++) {
  5901. try {
  5902. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5903. }
  5904. catch (e) {
  5905. results.push(-1);
  5906. }
  5907. }
  5908. return results;
  5909. };
  5910. Engine.prototype.enableEffect = function (effect) {
  5911. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5912. if (effect && effect.onBind) {
  5913. effect.onBind(effect);
  5914. }
  5915. return;
  5916. }
  5917. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5918. // Use program
  5919. this._gl.useProgram(effect.getProgram());
  5920. for (var i in this._vertexAttribArrays) {
  5921. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5922. continue;
  5923. }
  5924. this._vertexAttribArrays[i] = false;
  5925. this._gl.disableVertexAttribArray(i);
  5926. }
  5927. var attributesCount = effect.getAttributesCount();
  5928. for (var index = 0; index < attributesCount; index++) {
  5929. // Attributes
  5930. var order = effect.getAttributeLocation(index);
  5931. if (order >= 0) {
  5932. this._vertexAttribArrays[order] = true;
  5933. this._gl.enableVertexAttribArray(order);
  5934. }
  5935. }
  5936. this._currentEffect = effect;
  5937. if (effect.onBind) {
  5938. effect.onBind(effect);
  5939. }
  5940. };
  5941. Engine.prototype.setArray = function (uniform, array) {
  5942. if (!uniform)
  5943. return;
  5944. this._gl.uniform1fv(uniform, array);
  5945. };
  5946. Engine.prototype.setArray2 = function (uniform, array) {
  5947. if (!uniform || array.length % 2 !== 0)
  5948. return;
  5949. this._gl.uniform2fv(uniform, array);
  5950. };
  5951. Engine.prototype.setArray3 = function (uniform, array) {
  5952. if (!uniform || array.length % 3 !== 0)
  5953. return;
  5954. this._gl.uniform3fv(uniform, array);
  5955. };
  5956. Engine.prototype.setArray4 = function (uniform, array) {
  5957. if (!uniform || array.length % 4 !== 0)
  5958. return;
  5959. this._gl.uniform4fv(uniform, array);
  5960. };
  5961. Engine.prototype.setMatrices = function (uniform, matrices) {
  5962. if (!uniform)
  5963. return;
  5964. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5965. };
  5966. Engine.prototype.setMatrix = function (uniform, matrix) {
  5967. if (!uniform)
  5968. return;
  5969. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5970. };
  5971. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5972. if (!uniform)
  5973. return;
  5974. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5975. };
  5976. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5977. if (!uniform)
  5978. return;
  5979. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5980. };
  5981. Engine.prototype.setFloat = function (uniform, value) {
  5982. if (!uniform)
  5983. return;
  5984. this._gl.uniform1f(uniform, value);
  5985. };
  5986. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5987. if (!uniform)
  5988. return;
  5989. this._gl.uniform2f(uniform, x, y);
  5990. };
  5991. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5992. if (!uniform)
  5993. return;
  5994. this._gl.uniform3f(uniform, x, y, z);
  5995. };
  5996. Engine.prototype.setBool = function (uniform, bool) {
  5997. if (!uniform)
  5998. return;
  5999. this._gl.uniform1i(uniform, bool);
  6000. };
  6001. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6002. if (!uniform)
  6003. return;
  6004. this._gl.uniform4f(uniform, x, y, z, w);
  6005. };
  6006. Engine.prototype.setColor3 = function (uniform, color3) {
  6007. if (!uniform)
  6008. return;
  6009. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6010. };
  6011. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6012. if (!uniform)
  6013. return;
  6014. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6015. };
  6016. // States
  6017. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6018. if (zOffset === void 0) { zOffset = 0; }
  6019. if (reverseSide === void 0) { reverseSide = false; }
  6020. // Culling
  6021. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6022. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6023. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6024. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6025. if (culling) {
  6026. this._depthCullingState.cullFace = cullFace;
  6027. this._depthCullingState.cull = true;
  6028. }
  6029. else {
  6030. this._depthCullingState.cull = false;
  6031. }
  6032. }
  6033. // Z offset
  6034. this._depthCullingState.zOffset = zOffset;
  6035. };
  6036. Engine.prototype.setDepthBuffer = function (enable) {
  6037. this._depthCullingState.depthTest = enable;
  6038. };
  6039. Engine.prototype.getDepthWrite = function () {
  6040. return this._depthCullingState.depthMask;
  6041. };
  6042. Engine.prototype.setDepthWrite = function (enable) {
  6043. this._depthCullingState.depthMask = enable;
  6044. };
  6045. Engine.prototype.setColorWrite = function (enable) {
  6046. this._gl.colorMask(enable, enable, enable, enable);
  6047. };
  6048. Engine.prototype.setAlphaMode = function (mode) {
  6049. if (this._alphaMode === mode) {
  6050. return;
  6051. }
  6052. switch (mode) {
  6053. case Engine.ALPHA_DISABLE:
  6054. this.setDepthWrite(true);
  6055. this._alphaState.alphaBlend = false;
  6056. break;
  6057. case Engine.ALPHA_COMBINE:
  6058. this.setDepthWrite(false);
  6059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6060. this._alphaState.alphaBlend = true;
  6061. break;
  6062. case Engine.ALPHA_ONEONE:
  6063. this.setDepthWrite(false);
  6064. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6065. this._alphaState.alphaBlend = true;
  6066. break;
  6067. case Engine.ALPHA_ADD:
  6068. this.setDepthWrite(false);
  6069. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6070. this._alphaState.alphaBlend = true;
  6071. break;
  6072. case Engine.ALPHA_SUBTRACT:
  6073. this.setDepthWrite(false);
  6074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6075. this._alphaState.alphaBlend = true;
  6076. break;
  6077. case Engine.ALPHA_MULTIPLY:
  6078. this.setDepthWrite(false);
  6079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6080. this._alphaState.alphaBlend = true;
  6081. break;
  6082. case Engine.ALPHA_MAXIMIZED:
  6083. this.setDepthWrite(false);
  6084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6085. this._alphaState.alphaBlend = true;
  6086. break;
  6087. }
  6088. this._alphaMode = mode;
  6089. };
  6090. Engine.prototype.getAlphaMode = function () {
  6091. return this._alphaMode;
  6092. };
  6093. Engine.prototype.setAlphaTesting = function (enable) {
  6094. this._alphaTest = enable;
  6095. };
  6096. Engine.prototype.getAlphaTesting = function () {
  6097. return this._alphaTest;
  6098. };
  6099. // Textures
  6100. Engine.prototype.wipeCaches = function () {
  6101. this.resetTextureCache();
  6102. this._currentEffect = null;
  6103. this._depthCullingState.reset();
  6104. this._alphaState.reset();
  6105. this._cachedVertexBuffers = null;
  6106. this._cachedIndexBuffer = null;
  6107. this._cachedEffectForVertexBuffers = null;
  6108. };
  6109. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6110. var gl = this._gl;
  6111. gl.bindTexture(gl.TEXTURE_2D, texture);
  6112. var magFilter = gl.NEAREST;
  6113. var minFilter = gl.NEAREST;
  6114. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6115. magFilter = gl.LINEAR;
  6116. minFilter = gl.LINEAR;
  6117. }
  6118. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6119. magFilter = gl.LINEAR;
  6120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6121. }
  6122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6124. gl.bindTexture(gl.TEXTURE_2D, null);
  6125. texture.samplingMode = samplingMode;
  6126. };
  6127. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6128. var _this = this;
  6129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6130. if (onLoad === void 0) { onLoad = null; }
  6131. if (onError === void 0) { onError = null; }
  6132. if (buffer === void 0) { buffer = null; }
  6133. var texture = this._gl.createTexture();
  6134. var extension;
  6135. var fromData = false;
  6136. if (url.substr(0, 5) === "data:") {
  6137. fromData = true;
  6138. }
  6139. if (!fromData)
  6140. extension = url.substr(url.length - 4, 4).toLowerCase();
  6141. else {
  6142. var oldUrl = url;
  6143. fromData = oldUrl.split(':');
  6144. url = oldUrl;
  6145. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6146. }
  6147. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6148. var isTGA = (extension === ".tga");
  6149. scene._addPendingData(texture);
  6150. texture.url = url;
  6151. texture.noMipmap = noMipmap;
  6152. texture.references = 1;
  6153. texture.samplingMode = samplingMode;
  6154. this._loadedTexturesCache.push(texture);
  6155. var onerror = function () {
  6156. scene._removePendingData(texture);
  6157. if (onError) {
  6158. onError();
  6159. }
  6160. };
  6161. var callback;
  6162. if (isTGA) {
  6163. callback = function (arrayBuffer) {
  6164. var data = new Uint8Array(arrayBuffer);
  6165. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6166. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6167. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6168. if (onLoad) {
  6169. onLoad();
  6170. }
  6171. }, samplingMode);
  6172. };
  6173. if (!(fromData instanceof Array))
  6174. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6175. callback(arrayBuffer);
  6176. }, onerror, scene.database, true);
  6177. else
  6178. callback(buffer);
  6179. }
  6180. else if (isDDS) {
  6181. callback = function (data) {
  6182. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6183. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6184. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6185. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6186. if (onLoad) {
  6187. onLoad();
  6188. }
  6189. }, samplingMode);
  6190. };
  6191. if (!(fromData instanceof Array))
  6192. BABYLON.Tools.LoadFile(url, function (data) {
  6193. callback(data);
  6194. }, onerror, scene.database, true);
  6195. else
  6196. callback(buffer);
  6197. }
  6198. else {
  6199. var onload = function (img) {
  6200. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6201. var isPot = (img.width === potWidth && img.height === potHeight);
  6202. if (!isPot) {
  6203. _this._prepareWorkingCanvas();
  6204. _this._workingCanvas.width = potWidth;
  6205. _this._workingCanvas.height = potHeight;
  6206. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6207. _this._workingContext.imageSmoothingEnabled = false;
  6208. _this._workingContext.mozImageSmoothingEnabled = false;
  6209. _this._workingContext.oImageSmoothingEnabled = false;
  6210. _this._workingContext.webkitImageSmoothingEnabled = false;
  6211. _this._workingContext.msImageSmoothingEnabled = false;
  6212. }
  6213. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6214. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6215. _this._workingContext.imageSmoothingEnabled = true;
  6216. _this._workingContext.mozImageSmoothingEnabled = true;
  6217. _this._workingContext.oImageSmoothingEnabled = true;
  6218. _this._workingContext.webkitImageSmoothingEnabled = true;
  6219. _this._workingContext.msImageSmoothingEnabled = true;
  6220. }
  6221. }
  6222. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6223. if (onLoad) {
  6224. onLoad();
  6225. }
  6226. }, samplingMode);
  6227. };
  6228. if (!(fromData instanceof Array))
  6229. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6230. else
  6231. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6232. }
  6233. return texture;
  6234. };
  6235. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6236. if (compression === void 0) { compression = null; }
  6237. var internalFormat = this._gl.RGBA;
  6238. switch (format) {
  6239. case Engine.TEXTUREFORMAT_ALPHA:
  6240. internalFormat = this._gl.ALPHA;
  6241. break;
  6242. case Engine.TEXTUREFORMAT_LUMINANCE:
  6243. internalFormat = this._gl.LUMINANCE;
  6244. break;
  6245. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6246. internalFormat = this._gl.LUMINANCE_ALPHA;
  6247. break;
  6248. case Engine.TEXTUREFORMAT_RGB:
  6249. internalFormat = this._gl.RGB;
  6250. break;
  6251. case Engine.TEXTUREFORMAT_RGBA:
  6252. internalFormat = this._gl.RGBA;
  6253. break;
  6254. }
  6255. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6256. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6257. if (compression) {
  6258. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6259. }
  6260. else {
  6261. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6262. }
  6263. if (texture.generateMipMaps) {
  6264. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6265. }
  6266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6267. this.resetTextureCache();
  6268. texture.isReady = true;
  6269. };
  6270. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6271. if (compression === void 0) { compression = null; }
  6272. var texture = this._gl.createTexture();
  6273. texture._baseWidth = width;
  6274. texture._baseHeight = height;
  6275. texture._width = width;
  6276. texture._height = height;
  6277. texture.references = 1;
  6278. this.updateRawTexture(texture, data, format, invertY, compression);
  6279. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6280. // Filters
  6281. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6282. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6285. texture.samplingMode = samplingMode;
  6286. this._loadedTexturesCache.push(texture);
  6287. return texture;
  6288. };
  6289. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6290. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6291. var texture = this._gl.createTexture();
  6292. texture._baseWidth = width;
  6293. texture._baseHeight = height;
  6294. if (forceExponantOfTwo) {
  6295. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6296. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6297. }
  6298. this.resetTextureCache();
  6299. texture._width = width;
  6300. texture._height = height;
  6301. texture.isReady = false;
  6302. texture.generateMipMaps = generateMipMaps;
  6303. texture.references = 1;
  6304. texture.samplingMode = samplingMode;
  6305. this.updateTextureSamplingMode(samplingMode, texture);
  6306. this._loadedTexturesCache.push(texture);
  6307. return texture;
  6308. };
  6309. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6310. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6311. if (texture.isCube) {
  6312. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6315. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6316. }
  6317. else {
  6318. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6322. }
  6323. };
  6324. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6325. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6326. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6328. if (texture.generateMipMaps) {
  6329. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6330. }
  6331. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6332. this.resetTextureCache();
  6333. texture.isReady = true;
  6334. };
  6335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6336. if (texture._isDisabled) {
  6337. return;
  6338. }
  6339. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6341. try {
  6342. // Testing video texture support
  6343. if (this._videoTextureSupported === undefined) {
  6344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6345. if (this._gl.getError() !== 0) {
  6346. this._videoTextureSupported = false;
  6347. }
  6348. else {
  6349. this._videoTextureSupported = true;
  6350. }
  6351. }
  6352. // Copy video through the current working canvas if video texture is not supported
  6353. if (!this._videoTextureSupported) {
  6354. if (!texture._workingCanvas) {
  6355. texture._workingCanvas = document.createElement("canvas");
  6356. texture._workingContext = texture._workingCanvas.getContext("2d");
  6357. texture._workingCanvas.width = texture._width;
  6358. texture._workingCanvas.height = texture._height;
  6359. }
  6360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6362. }
  6363. else {
  6364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6365. }
  6366. if (texture.generateMipMaps) {
  6367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6368. }
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. this.resetTextureCache();
  6371. texture.isReady = true;
  6372. }
  6373. catch (ex) {
  6374. // Something unexpected
  6375. // Let's disable the texture
  6376. texture._isDisabled = true;
  6377. }
  6378. };
  6379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6380. // old version had a "generateMipMaps" arg instead of options.
  6381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6382. // in the same way, generateDepthBuffer is defaulted to true
  6383. var generateMipMaps = false;
  6384. var generateDepthBuffer = true;
  6385. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6386. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6387. if (options !== undefined) {
  6388. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6389. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6390. type = options.type === undefined ? type : options.type;
  6391. if (options.samplingMode !== undefined) {
  6392. samplingMode = options.samplingMode;
  6393. }
  6394. if (type === Engine.TEXTURETYPE_FLOAT) {
  6395. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6396. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6397. }
  6398. }
  6399. var gl = this._gl;
  6400. var texture = gl.createTexture();
  6401. gl.bindTexture(gl.TEXTURE_2D, texture);
  6402. var width = size.width || size;
  6403. var height = size.height || size;
  6404. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6405. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6406. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6407. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6408. }
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6414. var depthBuffer;
  6415. // Create the depth buffer
  6416. if (generateDepthBuffer) {
  6417. depthBuffer = gl.createRenderbuffer();
  6418. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6419. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6420. }
  6421. // Create the framebuffer
  6422. var framebuffer = gl.createFramebuffer();
  6423. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6424. if (generateDepthBuffer) {
  6425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6426. }
  6427. if (generateMipMaps) {
  6428. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6429. }
  6430. // Unbind
  6431. gl.bindTexture(gl.TEXTURE_2D, null);
  6432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6433. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6434. texture._framebuffer = framebuffer;
  6435. if (generateDepthBuffer) {
  6436. texture._depthBuffer = depthBuffer;
  6437. }
  6438. texture._width = width;
  6439. texture._height = height;
  6440. texture.isReady = true;
  6441. texture.generateMipMaps = generateMipMaps;
  6442. texture.references = 1;
  6443. texture.samplingMode = samplingMode;
  6444. this.resetTextureCache();
  6445. this._loadedTexturesCache.push(texture);
  6446. return texture;
  6447. };
  6448. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6449. var gl = this._gl;
  6450. var texture = gl.createTexture();
  6451. var generateMipMaps = true;
  6452. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6453. if (options !== undefined) {
  6454. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6455. if (options.samplingMode !== undefined) {
  6456. samplingMode = options.samplingMode;
  6457. }
  6458. }
  6459. texture.isCube = true;
  6460. texture.references = 1;
  6461. texture.generateMipMaps = generateMipMaps;
  6462. texture.references = 1;
  6463. texture.samplingMode = samplingMode;
  6464. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6465. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6466. for (var face = 0; face < 6; face++) {
  6467. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6468. }
  6469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6473. // Create the depth buffer
  6474. var depthBuffer = gl.createRenderbuffer();
  6475. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6476. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6477. // Create the framebuffer
  6478. var framebuffer = gl.createFramebuffer();
  6479. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6480. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6481. // mipmaps
  6482. if (texture.generateMipMaps) {
  6483. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6484. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6485. }
  6486. // Unbind
  6487. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6489. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6490. texture._framebuffer = framebuffer;
  6491. texture._depthBuffer = depthBuffer;
  6492. this.resetTextureCache();
  6493. texture._width = size;
  6494. texture._height = size;
  6495. texture.isReady = true;
  6496. return texture;
  6497. };
  6498. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6499. var _this = this;
  6500. var gl = this._gl;
  6501. var texture = gl.createTexture();
  6502. texture.isCube = true;
  6503. texture.url = rootUrl;
  6504. texture.references = 1;
  6505. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6506. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6507. if (isDDS) {
  6508. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6509. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6510. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6511. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6512. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6513. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6514. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6515. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6516. }
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6522. _this.resetTextureCache();
  6523. texture._width = info.width;
  6524. texture._height = info.height;
  6525. texture.isReady = true;
  6526. }, null, null, true);
  6527. }
  6528. else {
  6529. cascadeLoad(rootUrl, scene, function (imgs) {
  6530. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6531. var height = width;
  6532. _this._prepareWorkingCanvas();
  6533. _this._workingCanvas.width = width;
  6534. _this._workingCanvas.height = height;
  6535. var faces = [
  6536. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6537. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6538. ];
  6539. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6540. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6541. for (var index = 0; index < faces.length; index++) {
  6542. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6543. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6544. }
  6545. if (!noMipmap) {
  6546. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6547. }
  6548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6552. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6553. _this.resetTextureCache();
  6554. texture._width = width;
  6555. texture._height = height;
  6556. texture.isReady = true;
  6557. }, extensions);
  6558. }
  6559. return texture;
  6560. };
  6561. Engine.prototype._releaseTexture = function (texture) {
  6562. var gl = this._gl;
  6563. if (texture._framebuffer) {
  6564. gl.deleteFramebuffer(texture._framebuffer);
  6565. }
  6566. if (texture._depthBuffer) {
  6567. gl.deleteRenderbuffer(texture._depthBuffer);
  6568. }
  6569. gl.deleteTexture(texture);
  6570. // Unbind channels
  6571. this.unbindAllTextures();
  6572. var index = this._loadedTexturesCache.indexOf(texture);
  6573. if (index !== -1) {
  6574. this._loadedTexturesCache.splice(index, 1);
  6575. }
  6576. };
  6577. Engine.prototype.bindSamplers = function (effect) {
  6578. this._gl.useProgram(effect.getProgram());
  6579. var samplers = effect.getSamplers();
  6580. for (var index = 0; index < samplers.length; index++) {
  6581. var uniform = effect.getUniform(samplers[index]);
  6582. this._gl.uniform1i(uniform, index);
  6583. }
  6584. this._currentEffect = null;
  6585. };
  6586. Engine.prototype._bindTexture = function (channel, texture) {
  6587. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6588. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6589. this._activeTexturesCache[channel] = null;
  6590. };
  6591. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6592. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6593. };
  6594. Engine.prototype.unbindAllTextures = function () {
  6595. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6596. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6598. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6599. this._activeTexturesCache[channel] = null;
  6600. }
  6601. };
  6602. Engine.prototype.setTexture = function (channel, texture) {
  6603. if (channel < 0) {
  6604. return;
  6605. }
  6606. // Not ready?
  6607. if (!texture || !texture.isReady()) {
  6608. if (this._activeTexturesCache[channel] != null) {
  6609. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6610. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6611. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6612. this._activeTexturesCache[channel] = null;
  6613. }
  6614. return;
  6615. }
  6616. // Video
  6617. var alreadyActivated = false;
  6618. if (texture instanceof BABYLON.VideoTexture) {
  6619. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6620. alreadyActivated = true;
  6621. texture.update();
  6622. }
  6623. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6624. texture.delayLoad();
  6625. return;
  6626. }
  6627. if (this._activeTexturesCache[channel] === texture) {
  6628. return;
  6629. }
  6630. this._activeTexturesCache[channel] = texture;
  6631. var internalTexture = texture.getInternalTexture();
  6632. if (!alreadyActivated) {
  6633. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6634. }
  6635. if (internalTexture.isCube) {
  6636. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6637. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6638. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6639. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6640. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6641. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6642. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6643. }
  6644. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6645. }
  6646. else {
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6648. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6649. internalTexture._cachedWrapU = texture.wrapU;
  6650. switch (texture.wrapU) {
  6651. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6653. break;
  6654. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6655. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6656. break;
  6657. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6658. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6659. break;
  6660. }
  6661. }
  6662. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6663. internalTexture._cachedWrapV = texture.wrapV;
  6664. switch (texture.wrapV) {
  6665. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6667. break;
  6668. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6670. break;
  6671. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6673. break;
  6674. }
  6675. }
  6676. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6677. }
  6678. };
  6679. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6681. var value = texture.anisotropicFilteringLevel;
  6682. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6683. value = 1;
  6684. }
  6685. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6686. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6687. texture._cachedAnisotropicFilteringLevel = value;
  6688. }
  6689. };
  6690. Engine.prototype.readPixels = function (x, y, width, height) {
  6691. var data = new Uint8Array(height * width * 4);
  6692. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6693. return data;
  6694. };
  6695. Engine.prototype.releaseInternalTexture = function (texture) {
  6696. if (!texture) {
  6697. return;
  6698. }
  6699. texture.references--;
  6700. // Final reference ?
  6701. if (texture.references === 0) {
  6702. var texturesCache = this.getLoadedTexturesCache();
  6703. var index = texturesCache.indexOf(texture);
  6704. if (index > -1) {
  6705. texturesCache.splice(index, 1);
  6706. }
  6707. this._releaseTexture(texture);
  6708. }
  6709. };
  6710. // Dispose
  6711. Engine.prototype.dispose = function () {
  6712. this.hideLoadingUI();
  6713. this.stopRenderLoop();
  6714. // Release scenes
  6715. while (this.scenes.length) {
  6716. this.scenes[0].dispose();
  6717. }
  6718. // Release audio engine
  6719. Engine.audioEngine.dispose();
  6720. // Release effects
  6721. for (var name in this._compiledEffects) {
  6722. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6723. }
  6724. // Unbind
  6725. for (var i in this._vertexAttribArrays) {
  6726. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6727. continue;
  6728. }
  6729. this._gl.disableVertexAttribArray(i);
  6730. }
  6731. this._gl = null;
  6732. // Events
  6733. window.removeEventListener("blur", this._onBlur);
  6734. window.removeEventListener("focus", this._onFocus);
  6735. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6736. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6737. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6738. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6739. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6740. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6741. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6742. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6743. };
  6744. // Loading screen
  6745. Engine.prototype.displayLoadingUI = function () {
  6746. this._loadingScreen.displayLoadingUI();
  6747. };
  6748. Engine.prototype.hideLoadingUI = function () {
  6749. this._loadingScreen.hideLoadingUI();
  6750. };
  6751. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6752. get: function () {
  6753. return this._loadingScreen;
  6754. },
  6755. set: function (loadingScreen) {
  6756. this._loadingScreen = loadingScreen;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6762. set: function (text) {
  6763. this._loadingScreen.loadingUIText = text;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6769. set: function (color) {
  6770. this._loadingScreen.loadingUIBackgroundColor = color;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. // FPS
  6776. Engine.prototype.getFps = function () {
  6777. return this.fps;
  6778. };
  6779. Engine.prototype.getDeltaTime = function () {
  6780. return this.deltaTime;
  6781. };
  6782. Engine.prototype._measureFps = function () {
  6783. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6784. var length = this.previousFramesDuration.length;
  6785. if (length >= 2) {
  6786. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6787. }
  6788. if (length >= this.fpsRange) {
  6789. if (length > this.fpsRange) {
  6790. this.previousFramesDuration.splice(0, 1);
  6791. length = this.previousFramesDuration.length;
  6792. }
  6793. var sum = 0;
  6794. for (var id = 0; id < length - 1; id++) {
  6795. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6796. }
  6797. this.fps = 1000.0 / (sum / (length - 1));
  6798. }
  6799. };
  6800. // Statics
  6801. Engine.isSupported = function () {
  6802. try {
  6803. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6804. if (navigator.isCocoonJS) {
  6805. return true;
  6806. }
  6807. var tempcanvas = document.createElement("canvas");
  6808. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6809. return gl != null && !!window.WebGLRenderingContext;
  6810. }
  6811. catch (e) {
  6812. return false;
  6813. }
  6814. };
  6815. // Const statics
  6816. Engine._ALPHA_DISABLE = 0;
  6817. Engine._ALPHA_ADD = 1;
  6818. Engine._ALPHA_COMBINE = 2;
  6819. Engine._ALPHA_SUBTRACT = 3;
  6820. Engine._ALPHA_MULTIPLY = 4;
  6821. Engine._ALPHA_MAXIMIZED = 5;
  6822. Engine._ALPHA_ONEONE = 6;
  6823. Engine._DELAYLOADSTATE_NONE = 0;
  6824. Engine._DELAYLOADSTATE_LOADED = 1;
  6825. Engine._DELAYLOADSTATE_LOADING = 2;
  6826. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6827. Engine._TEXTUREFORMAT_ALPHA = 0;
  6828. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6829. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6830. Engine._TEXTUREFORMAT_RGB = 4;
  6831. Engine._TEXTUREFORMAT_RGBA = 5;
  6832. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6833. Engine._TEXTURETYPE_FLOAT = 1;
  6834. // Updatable statics so stick with vars here
  6835. Engine.Epsilon = 0.001;
  6836. Engine.CollisionsEpsilon = 0.001;
  6837. Engine.CodeRepository = "src/";
  6838. Engine.ShadersRepository = "src/Shaders/";
  6839. return Engine;
  6840. })();
  6841. BABYLON.Engine = Engine;
  6842. })(BABYLON || (BABYLON = {}));
  6843. var BABYLON;
  6844. (function (BABYLON) {
  6845. /**
  6846. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6847. */
  6848. var Node = (function () {
  6849. /**
  6850. * @constructor
  6851. * @param {string} name - the name and id to be given to this node
  6852. * @param {BABYLON.Scene} the scene this node will be added to
  6853. */
  6854. function Node(name, scene) {
  6855. this.state = "";
  6856. this.animations = new Array();
  6857. this._childrenFlag = -1;
  6858. this._isEnabled = true;
  6859. this._isReady = true;
  6860. this._currentRenderId = -1;
  6861. this._parentRenderId = -1;
  6862. this.name = name;
  6863. this.id = name;
  6864. this._scene = scene;
  6865. this._initCache();
  6866. }
  6867. Node.prototype.getScene = function () {
  6868. return this._scene;
  6869. };
  6870. Node.prototype.getEngine = function () {
  6871. return this._scene.getEngine();
  6872. };
  6873. // override it in derived class
  6874. Node.prototype.getWorldMatrix = function () {
  6875. return BABYLON.Matrix.Identity();
  6876. };
  6877. // override it in derived class if you add new variables to the cache
  6878. // and call the parent class method
  6879. Node.prototype._initCache = function () {
  6880. this._cache = {};
  6881. this._cache.parent = undefined;
  6882. };
  6883. Node.prototype.updateCache = function (force) {
  6884. if (!force && this.isSynchronized())
  6885. return;
  6886. this._cache.parent = this.parent;
  6887. this._updateCache();
  6888. };
  6889. // override it in derived class if you add new variables to the cache
  6890. // and call the parent class method if !ignoreParentClass
  6891. Node.prototype._updateCache = function (ignoreParentClass) {
  6892. };
  6893. // override it in derived class if you add new variables to the cache
  6894. Node.prototype._isSynchronized = function () {
  6895. return true;
  6896. };
  6897. Node.prototype._markSyncedWithParent = function () {
  6898. this._parentRenderId = this.parent._currentRenderId;
  6899. };
  6900. Node.prototype.isSynchronizedWithParent = function () {
  6901. if (!this.parent) {
  6902. return true;
  6903. }
  6904. if (this._parentRenderId !== this.parent._currentRenderId) {
  6905. return false;
  6906. }
  6907. return this.parent.isSynchronized();
  6908. };
  6909. Node.prototype.isSynchronized = function (updateCache) {
  6910. var check = this.hasNewParent();
  6911. check = check || !this.isSynchronizedWithParent();
  6912. check = check || !this._isSynchronized();
  6913. if (updateCache)
  6914. this.updateCache(true);
  6915. return !check;
  6916. };
  6917. Node.prototype.hasNewParent = function (update) {
  6918. if (this._cache.parent === this.parent)
  6919. return false;
  6920. if (update)
  6921. this._cache.parent = this.parent;
  6922. return true;
  6923. };
  6924. /**
  6925. * Is this node ready to be used/rendered
  6926. * @return {boolean} is it ready
  6927. */
  6928. Node.prototype.isReady = function () {
  6929. return this._isReady;
  6930. };
  6931. /**
  6932. * Is this node enabled.
  6933. * If the node has a parent and is enabled, the parent will be inspected as well.
  6934. * @return {boolean} whether this node (and its parent) is enabled.
  6935. * @see setEnabled
  6936. */
  6937. Node.prototype.isEnabled = function () {
  6938. if (!this._isEnabled) {
  6939. return false;
  6940. }
  6941. if (this.parent) {
  6942. return this.parent.isEnabled();
  6943. }
  6944. return true;
  6945. };
  6946. /**
  6947. * Set the enabled state of this node.
  6948. * @param {boolean} value - the new enabled state
  6949. * @see isEnabled
  6950. */
  6951. Node.prototype.setEnabled = function (value) {
  6952. this._isEnabled = value;
  6953. };
  6954. /**
  6955. * Is this node a descendant of the given node.
  6956. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6957. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6958. * @see parent
  6959. */
  6960. Node.prototype.isDescendantOf = function (ancestor) {
  6961. if (this.parent) {
  6962. if (this.parent === ancestor) {
  6963. return true;
  6964. }
  6965. return this.parent.isDescendantOf(ancestor);
  6966. }
  6967. return false;
  6968. };
  6969. Node.prototype._getDescendants = function (list, results) {
  6970. for (var index = 0; index < list.length; index++) {
  6971. var item = list[index];
  6972. if (item.isDescendantOf(this)) {
  6973. results.push(item);
  6974. }
  6975. }
  6976. };
  6977. /**
  6978. * Will return all nodes that have this node as parent.
  6979. * @return {BABYLON.Node[]} all children nodes of all types.
  6980. */
  6981. Node.prototype.getDescendants = function () {
  6982. var results = [];
  6983. this._getDescendants(this._scene.meshes, results);
  6984. this._getDescendants(this._scene.lights, results);
  6985. this._getDescendants(this._scene.cameras, results);
  6986. return results;
  6987. };
  6988. Node.prototype._setReady = function (state) {
  6989. if (state === this._isReady) {
  6990. return;
  6991. }
  6992. if (!state) {
  6993. this._isReady = false;
  6994. return;
  6995. }
  6996. this._isReady = true;
  6997. if (this.onReady) {
  6998. this.onReady(this);
  6999. }
  7000. };
  7001. Node.prototype.getAnimationByName = function (name) {
  7002. for (var i = 0; i < this.animations.length; i++) {
  7003. var animation = this.animations[i];
  7004. if (animation.name === name) {
  7005. return animation;
  7006. }
  7007. }
  7008. return null;
  7009. };
  7010. return Node;
  7011. })();
  7012. BABYLON.Node = Node;
  7013. })(BABYLON || (BABYLON = {}));
  7014. var BABYLON;
  7015. (function (BABYLON) {
  7016. var FilesInput = (function () {
  7017. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7018. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7019. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7020. this._engine = p_engine;
  7021. this._canvas = p_canvas;
  7022. this._currentScene = p_scene;
  7023. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7024. this._progressCallback = p_progressCallback;
  7025. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7026. this._textureLoadingCallback = p_textureLoadingCallback;
  7027. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7028. }
  7029. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7030. var _this = this;
  7031. if (p_elementToMonitor) {
  7032. this._elementToMonitor = p_elementToMonitor;
  7033. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7034. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7035. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7036. }
  7037. };
  7038. FilesInput.prototype.renderFunction = function () {
  7039. if (this._additionnalRenderLoopLogicCallback) {
  7040. this._additionnalRenderLoopLogicCallback();
  7041. }
  7042. if (this._currentScene) {
  7043. if (this._textureLoadingCallback) {
  7044. var remaining = this._currentScene.getWaitingItemsCount();
  7045. if (remaining > 0) {
  7046. this._textureLoadingCallback(remaining);
  7047. }
  7048. }
  7049. this._currentScene.render();
  7050. }
  7051. };
  7052. FilesInput.prototype.drag = function (e) {
  7053. e.stopPropagation();
  7054. e.preventDefault();
  7055. };
  7056. FilesInput.prototype.drop = function (eventDrop) {
  7057. eventDrop.stopPropagation();
  7058. eventDrop.preventDefault();
  7059. this.loadFiles(eventDrop);
  7060. };
  7061. FilesInput.prototype.loadFiles = function (event) {
  7062. if (this._startingProcessingFilesCallback)
  7063. this._startingProcessingFilesCallback();
  7064. // Handling data transfer via drag'n'drop
  7065. if (event && event.dataTransfer && event.dataTransfer.files) {
  7066. this._filesToLoad = event.dataTransfer.files;
  7067. }
  7068. // Handling files from input files
  7069. if (event && event.target && event.target.files) {
  7070. this._filesToLoad = event.target.files;
  7071. }
  7072. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7073. for (var i = 0; i < this._filesToLoad.length; i++) {
  7074. switch (this._filesToLoad[i].type) {
  7075. case "image/jpeg":
  7076. case "image/png":
  7077. case "image/bmp":
  7078. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7079. break;
  7080. case "image/targa":
  7081. case "image/vnd.ms-dds":
  7082. case "audio/wav":
  7083. case "audio/x-wav":
  7084. case "audio/mp3":
  7085. case "audio/mpeg":
  7086. case "audio/mpeg3":
  7087. case "audio/x-mpeg-3":
  7088. case "audio/ogg":
  7089. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7090. break;
  7091. default:
  7092. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7093. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7094. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7095. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7096. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7097. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7098. this._sceneFileToLoad = this._filesToLoad[i];
  7099. }
  7100. break;
  7101. }
  7102. }
  7103. this.reload();
  7104. }
  7105. };
  7106. FilesInput.prototype.reload = function () {
  7107. var _this = this;
  7108. var that = this;
  7109. // If a ".babylon" file has been provided
  7110. if (this._sceneFileToLoad) {
  7111. if (this._currentScene) {
  7112. if (BABYLON.Tools.errorsCount > 0) {
  7113. BABYLON.Tools.ClearLogCache();
  7114. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7115. }
  7116. this._engine.stopRenderLoop();
  7117. this._currentScene.dispose();
  7118. }
  7119. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7120. that._currentScene = newScene;
  7121. // Wait for textures and shaders to be ready
  7122. that._currentScene.executeWhenReady(function () {
  7123. // Attach camera to canvas inputs
  7124. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7125. that._currentScene.createDefaultCameraOrLight();
  7126. }
  7127. that._currentScene.activeCamera.attachControl(that._canvas);
  7128. if (that._sceneLoadedCallback) {
  7129. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7130. }
  7131. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7132. });
  7133. }, function (progress) {
  7134. if (_this._progressCallback) {
  7135. _this._progressCallback(progress);
  7136. }
  7137. });
  7138. }
  7139. else {
  7140. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7141. }
  7142. };
  7143. FilesInput.FilesTextures = new Array();
  7144. FilesInput.FilesToLoad = new Array();
  7145. return FilesInput;
  7146. })();
  7147. BABYLON.FilesInput = FilesInput;
  7148. })(BABYLON || (BABYLON = {}));
  7149. var BABYLON;
  7150. (function (BABYLON) {
  7151. var IntersectionInfo = (function () {
  7152. function IntersectionInfo(bu, bv, distance) {
  7153. this.bu = bu;
  7154. this.bv = bv;
  7155. this.distance = distance;
  7156. this.faceId = 0;
  7157. this.subMeshId = 0;
  7158. }
  7159. return IntersectionInfo;
  7160. })();
  7161. BABYLON.IntersectionInfo = IntersectionInfo;
  7162. var PickingInfo = (function () {
  7163. function PickingInfo() {
  7164. this.hit = false;
  7165. this.distance = 0;
  7166. this.pickedPoint = null;
  7167. this.pickedMesh = null;
  7168. this.bu = 0;
  7169. this.bv = 0;
  7170. this.faceId = -1;
  7171. this.subMeshId = 0;
  7172. this.pickedSprite = null;
  7173. }
  7174. // Methods
  7175. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7176. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7177. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7178. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7179. return null;
  7180. }
  7181. var indices = this.pickedMesh.getIndices();
  7182. var result;
  7183. if (useVerticesNormals) {
  7184. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7185. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7186. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7187. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7188. normal0 = normal0.scale(this.bu);
  7189. normal1 = normal1.scale(this.bv);
  7190. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7191. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7192. }
  7193. else {
  7194. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7195. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7196. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7197. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7198. var p1p2 = vertex1.subtract(vertex2);
  7199. var p3p2 = vertex3.subtract(vertex2);
  7200. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7201. }
  7202. if (useWorldCoordinates) {
  7203. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7204. }
  7205. return BABYLON.Vector3.Normalize(result);
  7206. };
  7207. PickingInfo.prototype.getTextureCoordinates = function () {
  7208. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7209. return null;
  7210. }
  7211. var indices = this.pickedMesh.getIndices();
  7212. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7213. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7214. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7215. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7216. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7217. uv1 = uv1.scale(this.bu);
  7218. uv2 = uv2.scale(this.bv);
  7219. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7220. };
  7221. return PickingInfo;
  7222. })();
  7223. BABYLON.PickingInfo = PickingInfo;
  7224. })(BABYLON || (BABYLON = {}));
  7225. var BABYLON;
  7226. (function (BABYLON) {
  7227. var BoundingSphere = (function () {
  7228. function BoundingSphere(minimum, maximum) {
  7229. this.minimum = minimum;
  7230. this.maximum = maximum;
  7231. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7232. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7233. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7234. this.radius = distance * 0.5;
  7235. this.centerWorld = BABYLON.Vector3.Zero();
  7236. this._update(BABYLON.Matrix.Identity());
  7237. }
  7238. // Methods
  7239. BoundingSphere.prototype._update = function (world) {
  7240. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7241. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7242. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7243. };
  7244. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7245. for (var i = 0; i < 6; i++) {
  7246. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7247. return false;
  7248. }
  7249. return true;
  7250. };
  7251. BoundingSphere.prototype.intersectsPoint = function (point) {
  7252. var x = this.centerWorld.x - point.x;
  7253. var y = this.centerWorld.y - point.y;
  7254. var z = this.centerWorld.z - point.z;
  7255. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7256. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7257. return false;
  7258. return true;
  7259. };
  7260. // Statics
  7261. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7262. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7263. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7264. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7266. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7267. return false;
  7268. return true;
  7269. };
  7270. return BoundingSphere;
  7271. })();
  7272. BABYLON.BoundingSphere = BoundingSphere;
  7273. })(BABYLON || (BABYLON = {}));
  7274. var BABYLON;
  7275. (function (BABYLON) {
  7276. var BoundingBox = (function () {
  7277. function BoundingBox(minimum, maximum) {
  7278. this.minimum = minimum;
  7279. this.maximum = maximum;
  7280. this.vectors = new Array();
  7281. this.vectorsWorld = new Array();
  7282. // Bounding vectors
  7283. this.vectors.push(this.minimum.clone());
  7284. this.vectors.push(this.maximum.clone());
  7285. this.vectors.push(this.minimum.clone());
  7286. this.vectors[2].x = this.maximum.x;
  7287. this.vectors.push(this.minimum.clone());
  7288. this.vectors[3].y = this.maximum.y;
  7289. this.vectors.push(this.minimum.clone());
  7290. this.vectors[4].z = this.maximum.z;
  7291. this.vectors.push(this.maximum.clone());
  7292. this.vectors[5].z = this.minimum.z;
  7293. this.vectors.push(this.maximum.clone());
  7294. this.vectors[6].x = this.minimum.x;
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors[7].y = this.minimum.y;
  7297. // OBB
  7298. this.center = this.maximum.add(this.minimum).scale(0.5);
  7299. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7300. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7301. // World
  7302. for (var index = 0; index < this.vectors.length; index++) {
  7303. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7304. }
  7305. this.minimumWorld = BABYLON.Vector3.Zero();
  7306. this.maximumWorld = BABYLON.Vector3.Zero();
  7307. this._update(BABYLON.Matrix.Identity());
  7308. }
  7309. // Methods
  7310. BoundingBox.prototype.getWorldMatrix = function () {
  7311. return this._worldMatrix;
  7312. };
  7313. BoundingBox.prototype._update = function (world) {
  7314. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7315. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7316. for (var index = 0; index < this.vectors.length; index++) {
  7317. var v = this.vectorsWorld[index];
  7318. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7319. if (v.x < this.minimumWorld.x)
  7320. this.minimumWorld.x = v.x;
  7321. if (v.y < this.minimumWorld.y)
  7322. this.minimumWorld.y = v.y;
  7323. if (v.z < this.minimumWorld.z)
  7324. this.minimumWorld.z = v.z;
  7325. if (v.x > this.maximumWorld.x)
  7326. this.maximumWorld.x = v.x;
  7327. if (v.y > this.maximumWorld.y)
  7328. this.maximumWorld.y = v.y;
  7329. if (v.z > this.maximumWorld.z)
  7330. this.maximumWorld.z = v.z;
  7331. }
  7332. // OBB
  7333. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7334. this.center.scaleInPlace(0.5);
  7335. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7336. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7337. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7338. this._worldMatrix = world;
  7339. };
  7340. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7341. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7342. };
  7343. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7344. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7345. };
  7346. BoundingBox.prototype.intersectsPoint = function (point) {
  7347. var delta = -BABYLON.Engine.Epsilon;
  7348. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7349. return false;
  7350. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7351. return false;
  7352. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7353. return false;
  7354. return true;
  7355. };
  7356. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7357. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7358. };
  7359. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7360. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7361. return false;
  7362. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7363. return false;
  7364. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7365. return false;
  7366. return true;
  7367. };
  7368. // Statics
  7369. BoundingBox.Intersects = function (box0, box1) {
  7370. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7371. return false;
  7372. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7373. return false;
  7374. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7375. return false;
  7376. return true;
  7377. };
  7378. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7379. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7380. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7381. return (num <= (sphereRadius * sphereRadius));
  7382. };
  7383. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7384. for (var p = 0; p < 6; p++) {
  7385. for (var i = 0; i < 8; i++) {
  7386. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7387. return false;
  7388. }
  7389. }
  7390. }
  7391. return true;
  7392. };
  7393. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7394. for (var p = 0; p < 6; p++) {
  7395. var inCount = 8;
  7396. for (var i = 0; i < 8; i++) {
  7397. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7398. --inCount;
  7399. }
  7400. else {
  7401. break;
  7402. }
  7403. }
  7404. if (inCount === 0)
  7405. return false;
  7406. }
  7407. return true;
  7408. };
  7409. return BoundingBox;
  7410. })();
  7411. BABYLON.BoundingBox = BoundingBox;
  7412. })(BABYLON || (BABYLON = {}));
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var computeBoxExtents = function (axis, box) {
  7416. var p = BABYLON.Vector3.Dot(box.center, axis);
  7417. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7418. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7419. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7420. var r = r0 + r1 + r2;
  7421. return {
  7422. min: p - r,
  7423. max: p + r
  7424. };
  7425. };
  7426. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7427. var axisOverlap = function (axis, box0, box1) {
  7428. var result0 = computeBoxExtents(axis, box0);
  7429. var result1 = computeBoxExtents(axis, box1);
  7430. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7431. };
  7432. var BoundingInfo = (function () {
  7433. function BoundingInfo(minimum, maximum) {
  7434. this.minimum = minimum;
  7435. this.maximum = maximum;
  7436. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7437. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7438. }
  7439. // Methods
  7440. BoundingInfo.prototype._update = function (world) {
  7441. this.boundingBox._update(world);
  7442. this.boundingSphere._update(world);
  7443. };
  7444. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7445. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7446. return false;
  7447. return this.boundingBox.isInFrustum(frustumPlanes);
  7448. };
  7449. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7450. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7451. };
  7452. BoundingInfo.prototype._checkCollision = function (collider) {
  7453. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7454. };
  7455. BoundingInfo.prototype.intersectsPoint = function (point) {
  7456. if (!this.boundingSphere.centerWorld) {
  7457. return false;
  7458. }
  7459. if (!this.boundingSphere.intersectsPoint(point)) {
  7460. return false;
  7461. }
  7462. if (!this.boundingBox.intersectsPoint(point)) {
  7463. return false;
  7464. }
  7465. return true;
  7466. };
  7467. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7468. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7472. return false;
  7473. }
  7474. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7475. return false;
  7476. }
  7477. if (!precise) {
  7478. return true;
  7479. }
  7480. var box0 = this.boundingBox;
  7481. var box1 = boundingInfo.boundingBox;
  7482. if (!axisOverlap(box0.directions[0], box0, box1))
  7483. return false;
  7484. if (!axisOverlap(box0.directions[1], box0, box1))
  7485. return false;
  7486. if (!axisOverlap(box0.directions[2], box0, box1))
  7487. return false;
  7488. if (!axisOverlap(box1.directions[0], box0, box1))
  7489. return false;
  7490. if (!axisOverlap(box1.directions[1], box0, box1))
  7491. return false;
  7492. if (!axisOverlap(box1.directions[2], box0, box1))
  7493. return false;
  7494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7495. return false;
  7496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7497. return false;
  7498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7499. return false;
  7500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7501. return false;
  7502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7503. return false;
  7504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7511. return false;
  7512. return true;
  7513. };
  7514. return BoundingInfo;
  7515. })();
  7516. BABYLON.BoundingInfo = BoundingInfo;
  7517. })(BABYLON || (BABYLON = {}));
  7518. var BABYLON;
  7519. (function (BABYLON) {
  7520. var AbstractMesh = (function (_super) {
  7521. __extends(AbstractMesh, _super);
  7522. function AbstractMesh(name, scene) {
  7523. var _this = this;
  7524. _super.call(this, name, scene);
  7525. // Properties
  7526. this.definedFacingForward = true; // orientation for POV movement & rotation
  7527. this.position = new BABYLON.Vector3(0, 0, 0);
  7528. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7529. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7530. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7531. this.visibility = 1.0;
  7532. this.alphaIndex = Number.MAX_VALUE;
  7533. this.infiniteDistance = false;
  7534. this.isVisible = true;
  7535. this.isPickable = true;
  7536. this.showBoundingBox = false;
  7537. this.showSubMeshesBoundingBox = false;
  7538. this.onDispose = null;
  7539. this.isBlocker = false;
  7540. this.renderingGroupId = 0;
  7541. this.receiveShadows = false;
  7542. this.renderOutline = false;
  7543. this.outlineColor = BABYLON.Color3.Red();
  7544. this.outlineWidth = 0.02;
  7545. this.renderOverlay = false;
  7546. this.overlayColor = BABYLON.Color3.Red();
  7547. this.overlayAlpha = 0.5;
  7548. this.hasVertexAlpha = false;
  7549. this.useVertexColors = true;
  7550. this.applyFog = true;
  7551. this.computeBonesUsingShaders = true;
  7552. this.scalingDeterminant = 1;
  7553. this.numBoneInfluencers = 4;
  7554. this.useOctreeForRenderingSelection = true;
  7555. this.useOctreeForPicking = true;
  7556. this.useOctreeForCollisions = true;
  7557. this.layerMask = 0x0FFFFFFF;
  7558. this.alwaysSelectAsActiveMesh = false;
  7559. // Physics
  7560. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7561. // Collisions
  7562. this._checkCollisions = false;
  7563. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7564. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7565. this._collider = new BABYLON.Collider();
  7566. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7567. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7568. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7569. // Edges
  7570. this.edgesWidth = 1;
  7571. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7572. // Cache
  7573. this._localScaling = BABYLON.Matrix.Zero();
  7574. this._localRotation = BABYLON.Matrix.Zero();
  7575. this._localTranslation = BABYLON.Matrix.Zero();
  7576. this._localBillboard = BABYLON.Matrix.Zero();
  7577. this._localPivotScaling = BABYLON.Matrix.Zero();
  7578. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7579. this._localWorld = BABYLON.Matrix.Zero();
  7580. this._worldMatrix = BABYLON.Matrix.Zero();
  7581. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7582. this._absolutePosition = BABYLON.Vector3.Zero();
  7583. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7584. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7585. this._isDirty = false;
  7586. this._pivotMatrix = BABYLON.Matrix.Identity();
  7587. this._isDisposed = false;
  7588. this._renderId = 0;
  7589. this._intersectionsInProgress = new Array();
  7590. this._onAfterWorldMatrixUpdate = new Array();
  7591. this._isWorldMatrixFrozen = false;
  7592. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7593. if (collidedMesh === void 0) { collidedMesh = null; }
  7594. //TODO move this to the collision coordinator!
  7595. if (_this.getScene().workerCollisions)
  7596. newPosition.multiplyInPlace(_this._collider.radius);
  7597. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7598. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7599. _this.position.addInPlace(_this._diffPositionForCollisions);
  7600. }
  7601. if (_this.onCollide && collidedMesh) {
  7602. _this.onCollide(collidedMesh);
  7603. }
  7604. if (_this.onCollisionPositionChange) {
  7605. _this.onCollisionPositionChange(_this.position);
  7606. }
  7607. };
  7608. scene.addMesh(this);
  7609. }
  7610. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7611. get: function () {
  7612. return AbstractMesh._BILLBOARDMODE_NONE;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7618. get: function () {
  7619. return AbstractMesh._BILLBOARDMODE_X;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7625. get: function () {
  7626. return AbstractMesh._BILLBOARDMODE_Y;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7632. get: function () {
  7633. return AbstractMesh._BILLBOARDMODE_Z;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7639. get: function () {
  7640. return AbstractMesh._BILLBOARDMODE_ALL;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. // Methods
  7646. AbstractMesh.prototype.disableEdgesRendering = function () {
  7647. if (this._edgesRenderer !== undefined) {
  7648. this._edgesRenderer.dispose();
  7649. this._edgesRenderer = undefined;
  7650. }
  7651. };
  7652. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7653. if (epsilon === void 0) { epsilon = 0.95; }
  7654. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7655. this.disableEdgesRendering();
  7656. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7657. };
  7658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7659. get: function () {
  7660. return false;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. AbstractMesh.prototype.getLOD = function (camera) {
  7666. return this;
  7667. };
  7668. AbstractMesh.prototype.getTotalVertices = function () {
  7669. return 0;
  7670. };
  7671. AbstractMesh.prototype.getIndices = function () {
  7672. return null;
  7673. };
  7674. AbstractMesh.prototype.getVerticesData = function (kind) {
  7675. return null;
  7676. };
  7677. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7678. return false;
  7679. };
  7680. AbstractMesh.prototype.getBoundingInfo = function () {
  7681. if (this._masterMesh) {
  7682. return this._masterMesh.getBoundingInfo();
  7683. }
  7684. if (!this._boundingInfo) {
  7685. this._updateBoundingInfo();
  7686. }
  7687. return this._boundingInfo;
  7688. };
  7689. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7690. get: function () {
  7691. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. AbstractMesh.prototype._preActivate = function () {
  7697. };
  7698. AbstractMesh.prototype._activate = function (renderId) {
  7699. this._renderId = renderId;
  7700. };
  7701. AbstractMesh.prototype.getWorldMatrix = function () {
  7702. if (this._masterMesh) {
  7703. return this._masterMesh.getWorldMatrix();
  7704. }
  7705. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7706. this.computeWorldMatrix();
  7707. }
  7708. return this._worldMatrix;
  7709. };
  7710. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7711. get: function () {
  7712. return this._worldMatrix;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7718. get: function () {
  7719. return this._absolutePosition;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7725. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7726. this.computeWorldMatrix(true);
  7727. this._isWorldMatrixFrozen = true;
  7728. };
  7729. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7730. this._isWorldMatrixFrozen = false;
  7731. this.computeWorldMatrix(true);
  7732. };
  7733. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7734. get: function () {
  7735. return this._isWorldMatrixFrozen;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7741. axis.normalize();
  7742. if (!this.rotationQuaternion) {
  7743. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7744. this.rotation = BABYLON.Vector3.Zero();
  7745. }
  7746. var rotationQuaternion;
  7747. if (!space || space === BABYLON.Space.LOCAL) {
  7748. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7749. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7750. }
  7751. else {
  7752. if (this.parent) {
  7753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7754. invertParentWorldMatrix.invert();
  7755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7756. }
  7757. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7758. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7759. }
  7760. };
  7761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7762. var displacementVector = axis.scale(distance);
  7763. if (!space || space === BABYLON.Space.LOCAL) {
  7764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7765. this.setPositionWithLocalVector(tempV3);
  7766. }
  7767. else {
  7768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7769. }
  7770. };
  7771. AbstractMesh.prototype.getAbsolutePosition = function () {
  7772. this.computeWorldMatrix();
  7773. return this._absolutePosition;
  7774. };
  7775. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7776. if (!absolutePosition) {
  7777. return;
  7778. }
  7779. var absolutePositionX;
  7780. var absolutePositionY;
  7781. var absolutePositionZ;
  7782. if (absolutePosition.x === undefined) {
  7783. if (arguments.length < 3) {
  7784. return;
  7785. }
  7786. absolutePositionX = arguments[0];
  7787. absolutePositionY = arguments[1];
  7788. absolutePositionZ = arguments[2];
  7789. }
  7790. else {
  7791. absolutePositionX = absolutePosition.x;
  7792. absolutePositionY = absolutePosition.y;
  7793. absolutePositionZ = absolutePosition.z;
  7794. }
  7795. if (this.parent) {
  7796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7797. invertParentWorldMatrix.invert();
  7798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7800. }
  7801. else {
  7802. this.position.x = absolutePositionX;
  7803. this.position.y = absolutePositionY;
  7804. this.position.z = absolutePositionZ;
  7805. }
  7806. };
  7807. // ================================== Point of View Movement =================================
  7808. /**
  7809. * Perform relative position change from the point of view of behind the front of the mesh.
  7810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7811. * Supports definition of mesh facing forward or backward.
  7812. * @param {number} amountRight
  7813. * @param {number} amountUp
  7814. * @param {number} amountForward
  7815. */
  7816. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7817. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7818. };
  7819. /**
  7820. * Calculate relative position change from the point of view of behind the front of the mesh.
  7821. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7822. * Supports definition of mesh facing forward or backward.
  7823. * @param {number} amountRight
  7824. * @param {number} amountUp
  7825. * @param {number} amountForward
  7826. */
  7827. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7828. var rotMatrix = new BABYLON.Matrix();
  7829. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7830. rotQuaternion.toRotationMatrix(rotMatrix);
  7831. var translationDelta = BABYLON.Vector3.Zero();
  7832. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7834. return translationDelta;
  7835. };
  7836. // ================================== Point of View Rotation =================================
  7837. /**
  7838. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7839. * Supports definition of mesh facing forward or backward.
  7840. * @param {number} flipBack
  7841. * @param {number} twirlClockwise
  7842. * @param {number} tiltRight
  7843. */
  7844. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7845. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7846. };
  7847. /**
  7848. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7849. * Supports definition of mesh facing forward or backward.
  7850. * @param {number} flipBack
  7851. * @param {number} twirlClockwise
  7852. * @param {number} tiltRight
  7853. */
  7854. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7855. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7856. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7857. };
  7858. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7859. this._pivotMatrix = matrix;
  7860. this._cache.pivotMatrixUpdated = true;
  7861. };
  7862. AbstractMesh.prototype.getPivotMatrix = function () {
  7863. return this._pivotMatrix;
  7864. };
  7865. AbstractMesh.prototype._isSynchronized = function () {
  7866. if (this._isDirty) {
  7867. return false;
  7868. }
  7869. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7870. return false;
  7871. if (this._cache.pivotMatrixUpdated) {
  7872. return false;
  7873. }
  7874. if (this.infiniteDistance) {
  7875. return false;
  7876. }
  7877. if (!this._cache.position.equals(this.position))
  7878. return false;
  7879. if (this.rotationQuaternion) {
  7880. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7881. return false;
  7882. }
  7883. else {
  7884. if (!this._cache.rotation.equals(this.rotation))
  7885. return false;
  7886. }
  7887. if (!this._cache.scaling.equals(this.scaling))
  7888. return false;
  7889. return true;
  7890. };
  7891. AbstractMesh.prototype._initCache = function () {
  7892. _super.prototype._initCache.call(this);
  7893. this._cache.localMatrixUpdated = false;
  7894. this._cache.position = BABYLON.Vector3.Zero();
  7895. this._cache.scaling = BABYLON.Vector3.Zero();
  7896. this._cache.rotation = BABYLON.Vector3.Zero();
  7897. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7898. this._cache.billboardMode = -1;
  7899. };
  7900. AbstractMesh.prototype.markAsDirty = function (property) {
  7901. if (property === "rotation") {
  7902. this.rotationQuaternion = null;
  7903. }
  7904. this._currentRenderId = Number.MAX_VALUE;
  7905. this._isDirty = true;
  7906. };
  7907. AbstractMesh.prototype._updateBoundingInfo = function () {
  7908. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7909. this._boundingInfo._update(this.worldMatrixFromCache);
  7910. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7911. };
  7912. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7913. if (!this.subMeshes) {
  7914. return;
  7915. }
  7916. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7917. var subMesh = this.subMeshes[subIndex];
  7918. subMesh.updateBoundingInfo(matrix);
  7919. }
  7920. };
  7921. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7922. if (this._isWorldMatrixFrozen) {
  7923. return this._worldMatrix;
  7924. }
  7925. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7926. return this._worldMatrix;
  7927. }
  7928. this._cache.position.copyFrom(this.position);
  7929. this._cache.scaling.copyFrom(this.scaling);
  7930. this._cache.pivotMatrixUpdated = false;
  7931. this._cache.billboardMode = this.billboardMode;
  7932. this._currentRenderId = this.getScene().getRenderId();
  7933. this._isDirty = false;
  7934. // Scaling
  7935. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7936. // Rotation
  7937. if (this.rotationQuaternion) {
  7938. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7939. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7940. }
  7941. else {
  7942. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7943. this._cache.rotation.copyFrom(this.rotation);
  7944. }
  7945. // Translation
  7946. if (this.infiniteDistance && !this.parent) {
  7947. var camera = this.getScene().activeCamera;
  7948. if (camera) {
  7949. var cameraWorldMatrix = camera.getWorldMatrix();
  7950. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7951. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7952. }
  7953. }
  7954. else {
  7955. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7956. }
  7957. // Composing transformations
  7958. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7959. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7960. // Billboarding
  7961. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7962. var localPosition = this.position.clone();
  7963. var zero = this.getScene().activeCamera.globalPosition.clone();
  7964. if (this.parent && this.parent.position) {
  7965. localPosition.addInPlace(this.parent.position);
  7966. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7967. }
  7968. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7969. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7970. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7971. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7972. zero.y = localPosition.y + 0.001;
  7973. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7974. zero.z = localPosition.z + 0.001;
  7975. }
  7976. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7977. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7978. this._localBillboard.invert();
  7979. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7980. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7981. }
  7982. // Local world
  7983. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7984. // Parent
  7985. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7986. this._markSyncedWithParent();
  7987. if (this._meshToBoneReferal) {
  7988. if (!this._localMeshReferalTransform) {
  7989. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7990. }
  7991. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7992. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7993. }
  7994. else {
  7995. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7996. }
  7997. }
  7998. else {
  7999. this._worldMatrix.copyFrom(this._localWorld);
  8000. }
  8001. // Bounding info
  8002. this._updateBoundingInfo();
  8003. // Absolute position
  8004. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8005. // Callbacks
  8006. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8007. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8008. }
  8009. return this._worldMatrix;
  8010. };
  8011. /**
  8012. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8013. * @param func: callback function to add
  8014. */
  8015. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8016. this._onAfterWorldMatrixUpdate.push(func);
  8017. };
  8018. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8019. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8020. if (index > -1) {
  8021. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8022. }
  8023. };
  8024. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8025. this.computeWorldMatrix();
  8026. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8027. };
  8028. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8029. this.computeWorldMatrix();
  8030. var invLocalWorldMatrix = this._localWorld.clone();
  8031. invLocalWorldMatrix.invert();
  8032. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8033. };
  8034. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8035. this.computeWorldMatrix(true);
  8036. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8037. };
  8038. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8039. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8040. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8041. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8042. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8043. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8044. /// <returns>Mesh oriented towards targetMesh</returns>
  8045. yawCor = yawCor || 0; // default to zero if undefined
  8046. pitchCor = pitchCor || 0;
  8047. rollCor = rollCor || 0;
  8048. var dv = targetPoint.subtract(this.position);
  8049. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8050. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8051. var pitch = Math.atan2(dv.y, len);
  8052. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8053. };
  8054. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8055. this._meshToBoneReferal = affectedMesh;
  8056. this.parent = bone;
  8057. if (bone.getWorldMatrix().determinant() < 0) {
  8058. this.scalingDeterminant *= -1;
  8059. }
  8060. };
  8061. AbstractMesh.prototype.detachFromBone = function () {
  8062. if (this.parent.getWorldMatrix().determinant() < 0) {
  8063. this.scalingDeterminant *= -1;
  8064. }
  8065. this._meshToBoneReferal = null;
  8066. this.parent = null;
  8067. };
  8068. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8069. return this._boundingInfo.isInFrustum(frustumPlanes);
  8070. };
  8071. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8072. if (!camera) {
  8073. camera = this.getScene().activeCamera;
  8074. }
  8075. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8076. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8077. return false;
  8078. }
  8079. return true;
  8080. };
  8081. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8082. if (!this._boundingInfo || !mesh._boundingInfo) {
  8083. return false;
  8084. }
  8085. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8086. };
  8087. AbstractMesh.prototype.intersectsPoint = function (point) {
  8088. if (!this._boundingInfo) {
  8089. return false;
  8090. }
  8091. return this._boundingInfo.intersectsPoint(point);
  8092. };
  8093. // Physics
  8094. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8095. var physicsEngine = this.getScene().getPhysicsEngine();
  8096. if (!physicsEngine) {
  8097. return null;
  8098. }
  8099. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8100. if (impostor.impostor) {
  8101. // Old API
  8102. options = impostor;
  8103. impostor = impostor.impostor;
  8104. }
  8105. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8106. physicsEngine._unregisterMesh(this);
  8107. return null;
  8108. }
  8109. if (!options) {
  8110. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8111. }
  8112. else {
  8113. if (!options.mass && options.mass !== 0)
  8114. options.mass = 0;
  8115. if (!options.friction && options.friction !== 0)
  8116. options.friction = 0.2;
  8117. if (!options.restitution && options.restitution !== 0)
  8118. options.restitution = 0.2;
  8119. }
  8120. this._physicImpostor = impostor;
  8121. this._physicsMass = options.mass;
  8122. this._physicsFriction = options.friction;
  8123. this._physicRestitution = options.restitution;
  8124. return physicsEngine._registerMesh(this, impostor, options);
  8125. };
  8126. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8127. if (!this._physicImpostor) {
  8128. return BABYLON.PhysicsEngine.NoImpostor;
  8129. }
  8130. return this._physicImpostor;
  8131. };
  8132. AbstractMesh.prototype.getPhysicsMass = function () {
  8133. if (!this._physicsMass) {
  8134. return 0;
  8135. }
  8136. return this._physicsMass;
  8137. };
  8138. AbstractMesh.prototype.getPhysicsFriction = function () {
  8139. if (!this._physicsFriction) {
  8140. return 0;
  8141. }
  8142. return this._physicsFriction;
  8143. };
  8144. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8145. if (!this._physicRestitution) {
  8146. return 0;
  8147. }
  8148. return this._physicRestitution;
  8149. };
  8150. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8151. if (!camera) {
  8152. camera = this.getScene().activeCamera;
  8153. }
  8154. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8155. };
  8156. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8157. if (!camera) {
  8158. camera = this.getScene().activeCamera;
  8159. }
  8160. return this.absolutePosition.subtract(camera.position).length();
  8161. };
  8162. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8163. if (!this._physicImpostor) {
  8164. return;
  8165. }
  8166. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8167. };
  8168. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8169. if (!this._physicImpostor) {
  8170. return;
  8171. }
  8172. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8173. };
  8174. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8175. if (!this._physicImpostor) {
  8176. return;
  8177. }
  8178. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8179. };
  8180. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8181. // Collisions
  8182. get: function () {
  8183. return this._checkCollisions;
  8184. },
  8185. set: function (collisionEnabled) {
  8186. this._checkCollisions = collisionEnabled;
  8187. if (this.getScene().workerCollisions) {
  8188. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8189. }
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8195. var globalPosition = this.getAbsolutePosition();
  8196. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8197. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8198. this._collider.radius = this.ellipsoid;
  8199. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8200. };
  8201. // Submeshes octree
  8202. /**
  8203. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8204. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8205. */
  8206. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8207. if (maxCapacity === void 0) { maxCapacity = 64; }
  8208. if (maxDepth === void 0) { maxDepth = 2; }
  8209. if (!this._submeshesOctree) {
  8210. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8211. }
  8212. this.computeWorldMatrix(true);
  8213. // Update octree
  8214. var bbox = this.getBoundingInfo().boundingBox;
  8215. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8216. return this._submeshesOctree;
  8217. };
  8218. // Collisions
  8219. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8220. this._generatePointsArray();
  8221. // Transformation
  8222. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8223. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8224. subMesh._lastColliderWorldVertices = [];
  8225. subMesh._trianglePlanes = [];
  8226. var start = subMesh.verticesStart;
  8227. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8228. for (var i = start; i < end; i++) {
  8229. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8230. }
  8231. }
  8232. // Collide
  8233. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8234. if (collider.collisionFound) {
  8235. collider.collidedMesh = this;
  8236. }
  8237. };
  8238. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8239. var subMeshes;
  8240. var len;
  8241. // Octrees
  8242. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8243. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8244. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8245. len = intersections.length;
  8246. subMeshes = intersections.data;
  8247. }
  8248. else {
  8249. subMeshes = this.subMeshes;
  8250. len = subMeshes.length;
  8251. }
  8252. for (var index = 0; index < len; index++) {
  8253. var subMesh = subMeshes[index];
  8254. // Bounding test
  8255. if (len > 1 && !subMesh._checkCollision(collider))
  8256. continue;
  8257. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8258. }
  8259. };
  8260. AbstractMesh.prototype._checkCollision = function (collider) {
  8261. // Bounding box test
  8262. if (!this._boundingInfo._checkCollision(collider))
  8263. return;
  8264. // Transformation matrix
  8265. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8266. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8267. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8268. };
  8269. // Picking
  8270. AbstractMesh.prototype._generatePointsArray = function () {
  8271. return false;
  8272. };
  8273. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8274. var pickingInfo = new BABYLON.PickingInfo();
  8275. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8276. return pickingInfo;
  8277. }
  8278. if (!this._generatePointsArray()) {
  8279. return pickingInfo;
  8280. }
  8281. var intersectInfo = null;
  8282. // Octrees
  8283. var subMeshes;
  8284. var len;
  8285. if (this._submeshesOctree && this.useOctreeForPicking) {
  8286. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8287. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8288. len = intersections.length;
  8289. subMeshes = intersections.data;
  8290. }
  8291. else {
  8292. subMeshes = this.subMeshes;
  8293. len = subMeshes.length;
  8294. }
  8295. for (var index = 0; index < len; index++) {
  8296. var subMesh = subMeshes[index];
  8297. // Bounding test
  8298. if (len > 1 && !subMesh.canIntersects(ray))
  8299. continue;
  8300. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8301. if (currentIntersectInfo) {
  8302. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8303. intersectInfo = currentIntersectInfo;
  8304. intersectInfo.subMeshId = index;
  8305. if (fastCheck) {
  8306. break;
  8307. }
  8308. }
  8309. }
  8310. }
  8311. if (intersectInfo) {
  8312. // Get picked point
  8313. var world = this.getWorldMatrix();
  8314. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8315. var direction = ray.direction.clone();
  8316. direction = direction.scale(intersectInfo.distance);
  8317. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8318. var pickedPoint = worldOrigin.add(worldDirection);
  8319. // Return result
  8320. pickingInfo.hit = true;
  8321. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8322. pickingInfo.pickedPoint = pickedPoint;
  8323. pickingInfo.pickedMesh = this;
  8324. pickingInfo.bu = intersectInfo.bu;
  8325. pickingInfo.bv = intersectInfo.bv;
  8326. pickingInfo.faceId = intersectInfo.faceId;
  8327. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8328. return pickingInfo;
  8329. }
  8330. return pickingInfo;
  8331. };
  8332. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8333. return null;
  8334. };
  8335. AbstractMesh.prototype.releaseSubMeshes = function () {
  8336. if (this.subMeshes) {
  8337. while (this.subMeshes.length) {
  8338. this.subMeshes[0].dispose();
  8339. }
  8340. }
  8341. else {
  8342. this.subMeshes = new Array();
  8343. }
  8344. };
  8345. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8346. var index;
  8347. // Animations
  8348. this.getScene().stopAnimation(this);
  8349. // Physics
  8350. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8351. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8352. }
  8353. // Intersections in progress
  8354. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8355. var other = this._intersectionsInProgress[index];
  8356. var pos = other._intersectionsInProgress.indexOf(this);
  8357. other._intersectionsInProgress.splice(pos, 1);
  8358. }
  8359. this._intersectionsInProgress = [];
  8360. // Edges
  8361. if (this._edgesRenderer) {
  8362. this._edgesRenderer.dispose();
  8363. this._edgesRenderer = null;
  8364. }
  8365. // SubMeshes
  8366. this.releaseSubMeshes();
  8367. // Remove from scene
  8368. this.getScene().removeMesh(this);
  8369. if (!doNotRecurse) {
  8370. // Particles
  8371. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8372. if (this.getScene().particleSystems[index].emitter === this) {
  8373. this.getScene().particleSystems[index].dispose();
  8374. index--;
  8375. }
  8376. }
  8377. // Children
  8378. var objects = this.getScene().meshes.slice(0);
  8379. for (index = 0; index < objects.length; index++) {
  8380. if (objects[index].parent === this) {
  8381. objects[index].dispose();
  8382. }
  8383. }
  8384. }
  8385. else {
  8386. for (index = 0; index < this.getScene().meshes.length; index++) {
  8387. var obj = this.getScene().meshes[index];
  8388. if (obj.parent === this) {
  8389. obj.parent = null;
  8390. obj.computeWorldMatrix(true);
  8391. }
  8392. }
  8393. }
  8394. this._onAfterWorldMatrixUpdate = [];
  8395. this._isDisposed = true;
  8396. // Callback
  8397. if (this.onDispose) {
  8398. this.onDispose();
  8399. }
  8400. };
  8401. // Statics
  8402. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8403. AbstractMesh._BILLBOARDMODE_X = 1;
  8404. AbstractMesh._BILLBOARDMODE_Y = 2;
  8405. AbstractMesh._BILLBOARDMODE_Z = 4;
  8406. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8407. return AbstractMesh;
  8408. })(BABYLON.Node);
  8409. BABYLON.AbstractMesh = AbstractMesh;
  8410. })(BABYLON || (BABYLON = {}));
  8411. var BABYLON;
  8412. (function (BABYLON) {
  8413. var Light = (function (_super) {
  8414. __extends(Light, _super);
  8415. function Light(name, scene) {
  8416. _super.call(this, name, scene);
  8417. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8418. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8419. this.intensity = 1.0;
  8420. this.range = Number.MAX_VALUE;
  8421. this.includeOnlyWithLayerMask = 0;
  8422. this.includedOnlyMeshes = new Array();
  8423. this.excludedMeshes = new Array();
  8424. this.excludeWithLayerMask = 0;
  8425. this._excludedMeshesIds = new Array();
  8426. this._includedOnlyMeshesIds = new Array();
  8427. scene.addLight(this);
  8428. }
  8429. Light.prototype.getShadowGenerator = function () {
  8430. return this._shadowGenerator;
  8431. };
  8432. Light.prototype.getAbsolutePosition = function () {
  8433. return BABYLON.Vector3.Zero();
  8434. };
  8435. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8436. };
  8437. Light.prototype._getWorldMatrix = function () {
  8438. return BABYLON.Matrix.Identity();
  8439. };
  8440. Light.prototype.canAffectMesh = function (mesh) {
  8441. if (!mesh) {
  8442. return true;
  8443. }
  8444. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8445. return false;
  8446. }
  8447. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8448. return false;
  8449. }
  8450. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8451. return false;
  8452. }
  8453. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8454. return false;
  8455. }
  8456. return true;
  8457. };
  8458. Light.prototype.getWorldMatrix = function () {
  8459. this._currentRenderId = this.getScene().getRenderId();
  8460. var worldMatrix = this._getWorldMatrix();
  8461. if (this.parent && this.parent.getWorldMatrix) {
  8462. if (!this._parentedWorldMatrix) {
  8463. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8464. }
  8465. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8466. this._markSyncedWithParent();
  8467. return this._parentedWorldMatrix;
  8468. }
  8469. return worldMatrix;
  8470. };
  8471. Light.prototype.dispose = function () {
  8472. if (this._shadowGenerator) {
  8473. this._shadowGenerator.dispose();
  8474. this._shadowGenerator = null;
  8475. }
  8476. // Animations
  8477. this.getScene().stopAnimation(this);
  8478. // Remove from scene
  8479. this.getScene().removeLight(this);
  8480. };
  8481. Light.prototype.serialize = function () {
  8482. var serializationObject = {};
  8483. serializationObject.name = this.name;
  8484. serializationObject.id = this.id;
  8485. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8486. if (this.intensity) {
  8487. serializationObject.intensity = this.intensity;
  8488. }
  8489. serializationObject.range = this.range;
  8490. serializationObject.diffuse = this.diffuse.asArray();
  8491. serializationObject.specular = this.specular.asArray();
  8492. return serializationObject;
  8493. };
  8494. Light.Parse = function (parsedLight, scene) {
  8495. var light;
  8496. switch (parsedLight.type) {
  8497. case 0:
  8498. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8499. break;
  8500. case 1:
  8501. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8502. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8503. break;
  8504. case 2:
  8505. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8506. break;
  8507. case 3:
  8508. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8509. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8510. break;
  8511. }
  8512. light.id = parsedLight.id;
  8513. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8514. if (parsedLight.intensity !== undefined) {
  8515. light.intensity = parsedLight.intensity;
  8516. }
  8517. if (parsedLight.range) {
  8518. light.range = parsedLight.range;
  8519. }
  8520. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8521. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8522. if (parsedLight.excludedMeshesIds) {
  8523. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8524. }
  8525. // Parent
  8526. if (parsedLight.parentId) {
  8527. light._waitingParentId = parsedLight.parentId;
  8528. }
  8529. if (parsedLight.includedOnlyMeshesIds) {
  8530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8531. }
  8532. // Animations
  8533. if (parsedLight.animations) {
  8534. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8535. var parsedAnimation = parsedLight.animations[animationIndex];
  8536. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8537. }
  8538. }
  8539. if (parsedLight.autoAnimate) {
  8540. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8541. }
  8542. return light;
  8543. };
  8544. return Light;
  8545. })(BABYLON.Node);
  8546. BABYLON.Light = Light;
  8547. })(BABYLON || (BABYLON = {}));
  8548. var BABYLON;
  8549. (function (BABYLON) {
  8550. var PointLight = (function (_super) {
  8551. __extends(PointLight, _super);
  8552. function PointLight(name, position, scene) {
  8553. _super.call(this, name, scene);
  8554. this.position = position;
  8555. }
  8556. PointLight.prototype.getAbsolutePosition = function () {
  8557. return this.transformedPosition ? this.transformedPosition : this.position;
  8558. };
  8559. PointLight.prototype.computeTransformedPosition = function () {
  8560. if (this.parent && this.parent.getWorldMatrix) {
  8561. if (!this.transformedPosition) {
  8562. this.transformedPosition = BABYLON.Vector3.Zero();
  8563. }
  8564. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8565. return true;
  8566. }
  8567. return false;
  8568. };
  8569. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8570. if (this.parent && this.parent.getWorldMatrix) {
  8571. this.computeTransformedPosition();
  8572. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8573. return;
  8574. }
  8575. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8576. };
  8577. PointLight.prototype.needCube = function () {
  8578. return true;
  8579. };
  8580. PointLight.prototype.supportsVSM = function () {
  8581. return false;
  8582. };
  8583. PointLight.prototype.needRefreshPerFrame = function () {
  8584. return false;
  8585. };
  8586. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8587. switch (faceIndex) {
  8588. case 0:
  8589. return new BABYLON.Vector3(1, 0, 0);
  8590. case 1:
  8591. return new BABYLON.Vector3(-1, 0, 0);
  8592. case 2:
  8593. return new BABYLON.Vector3(0, -1, 0);
  8594. case 3:
  8595. return new BABYLON.Vector3(0, 1, 0);
  8596. case 4:
  8597. return new BABYLON.Vector3(0, 0, 1);
  8598. case 5:
  8599. return new BABYLON.Vector3(0, 0, -1);
  8600. }
  8601. return BABYLON.Vector3.Zero();
  8602. };
  8603. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8604. var activeCamera = this.getScene().activeCamera;
  8605. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8606. };
  8607. PointLight.prototype._getWorldMatrix = function () {
  8608. if (!this._worldMatrix) {
  8609. this._worldMatrix = BABYLON.Matrix.Identity();
  8610. }
  8611. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8612. return this._worldMatrix;
  8613. };
  8614. PointLight.prototype.serialize = function () {
  8615. var serializationObject = _super.prototype.serialize.call(this);
  8616. serializationObject.type = 0;
  8617. serializationObject.position = this.position.asArray();
  8618. return serializationObject;
  8619. };
  8620. return PointLight;
  8621. })(BABYLON.Light);
  8622. BABYLON.PointLight = PointLight;
  8623. })(BABYLON || (BABYLON = {}));
  8624. var BABYLON;
  8625. (function (BABYLON) {
  8626. var SpotLight = (function (_super) {
  8627. __extends(SpotLight, _super);
  8628. function SpotLight(name, position, direction, angle, exponent, scene) {
  8629. _super.call(this, name, scene);
  8630. this.position = position;
  8631. this.direction = direction;
  8632. this.angle = angle;
  8633. this.exponent = exponent;
  8634. }
  8635. SpotLight.prototype.getAbsolutePosition = function () {
  8636. return this.transformedPosition ? this.transformedPosition : this.position;
  8637. };
  8638. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8639. var activeCamera = this.getScene().activeCamera;
  8640. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8641. };
  8642. SpotLight.prototype.needCube = function () {
  8643. return false;
  8644. };
  8645. SpotLight.prototype.supportsVSM = function () {
  8646. return true;
  8647. };
  8648. SpotLight.prototype.needRefreshPerFrame = function () {
  8649. return false;
  8650. };
  8651. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8652. return this.direction;
  8653. };
  8654. SpotLight.prototype.setDirectionToTarget = function (target) {
  8655. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8656. return this.direction;
  8657. };
  8658. SpotLight.prototype.computeTransformedPosition = function () {
  8659. if (this.parent && this.parent.getWorldMatrix) {
  8660. if (!this.transformedPosition) {
  8661. this.transformedPosition = BABYLON.Vector3.Zero();
  8662. }
  8663. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8664. return true;
  8665. }
  8666. return false;
  8667. };
  8668. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8669. var normalizeDirection;
  8670. if (this.parent && this.parent.getWorldMatrix) {
  8671. if (!this._transformedDirection) {
  8672. this._transformedDirection = BABYLON.Vector3.Zero();
  8673. }
  8674. this.computeTransformedPosition();
  8675. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8676. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8677. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8678. }
  8679. else {
  8680. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8681. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8682. }
  8683. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8684. };
  8685. SpotLight.prototype._getWorldMatrix = function () {
  8686. if (!this._worldMatrix) {
  8687. this._worldMatrix = BABYLON.Matrix.Identity();
  8688. }
  8689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8690. return this._worldMatrix;
  8691. };
  8692. SpotLight.prototype.serialize = function () {
  8693. var serializationObject = _super.prototype.serialize.call(this);
  8694. serializationObject.type = 2;
  8695. serializationObject.position = this.position.asArray();
  8696. serializationObject.direction = this.position.asArray();
  8697. serializationObject.angle = this.angle;
  8698. serializationObject.exponent = this.exponent;
  8699. return serializationObject;
  8700. };
  8701. return SpotLight;
  8702. })(BABYLON.Light);
  8703. BABYLON.SpotLight = SpotLight;
  8704. })(BABYLON || (BABYLON = {}));
  8705. var BABYLON;
  8706. (function (BABYLON) {
  8707. var HemisphericLight = (function (_super) {
  8708. __extends(HemisphericLight, _super);
  8709. function HemisphericLight(name, direction, scene) {
  8710. _super.call(this, name, scene);
  8711. this.direction = direction;
  8712. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8713. }
  8714. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8715. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8716. return this.direction;
  8717. };
  8718. HemisphericLight.prototype.getShadowGenerator = function () {
  8719. return null;
  8720. };
  8721. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8722. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8723. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8724. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8725. };
  8726. HemisphericLight.prototype._getWorldMatrix = function () {
  8727. if (!this._worldMatrix) {
  8728. this._worldMatrix = BABYLON.Matrix.Identity();
  8729. }
  8730. return this._worldMatrix;
  8731. };
  8732. HemisphericLight.prototype.serialize = function () {
  8733. var serializationObject = _super.prototype.serialize.call(this);
  8734. serializationObject.type = 3;
  8735. serializationObject.direction = this.direction.asArray();
  8736. serializationObject.groundColor = this.groundColor.asArray();
  8737. return serializationObject;
  8738. };
  8739. return HemisphericLight;
  8740. })(BABYLON.Light);
  8741. BABYLON.HemisphericLight = HemisphericLight;
  8742. })(BABYLON || (BABYLON = {}));
  8743. var BABYLON;
  8744. (function (BABYLON) {
  8745. var DirectionalLight = (function (_super) {
  8746. __extends(DirectionalLight, _super);
  8747. function DirectionalLight(name, direction, scene) {
  8748. _super.call(this, name, scene);
  8749. this.direction = direction;
  8750. this.shadowOrthoScale = 0.5;
  8751. this.autoUpdateExtends = true;
  8752. // Cache
  8753. this._orthoLeft = Number.MAX_VALUE;
  8754. this._orthoRight = Number.MIN_VALUE;
  8755. this._orthoTop = Number.MIN_VALUE;
  8756. this._orthoBottom = Number.MAX_VALUE;
  8757. this.position = direction.scale(-1);
  8758. }
  8759. DirectionalLight.prototype.getAbsolutePosition = function () {
  8760. return this.transformedPosition ? this.transformedPosition : this.position;
  8761. };
  8762. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8763. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8764. return this.direction;
  8765. };
  8766. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8767. var activeCamera = this.getScene().activeCamera;
  8768. // Check extends
  8769. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8770. var tempVector3 = BABYLON.Vector3.Zero();
  8771. this._orthoLeft = Number.MAX_VALUE;
  8772. this._orthoRight = Number.MIN_VALUE;
  8773. this._orthoTop = Number.MIN_VALUE;
  8774. this._orthoBottom = Number.MAX_VALUE;
  8775. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8776. var mesh = renderList[meshIndex];
  8777. if (!mesh) {
  8778. continue;
  8779. }
  8780. var boundingInfo = mesh.getBoundingInfo();
  8781. if (!boundingInfo) {
  8782. continue;
  8783. }
  8784. var boundingBox = boundingInfo.boundingBox;
  8785. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8786. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8787. if (tempVector3.x < this._orthoLeft)
  8788. this._orthoLeft = tempVector3.x;
  8789. if (tempVector3.y < this._orthoBottom)
  8790. this._orthoBottom = tempVector3.y;
  8791. if (tempVector3.x > this._orthoRight)
  8792. this._orthoRight = tempVector3.x;
  8793. if (tempVector3.y > this._orthoTop)
  8794. this._orthoTop = tempVector3.y;
  8795. }
  8796. }
  8797. }
  8798. var xOffset = this._orthoRight - this._orthoLeft;
  8799. var yOffset = this._orthoTop - this._orthoBottom;
  8800. 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);
  8801. };
  8802. DirectionalLight.prototype.supportsVSM = function () {
  8803. return true;
  8804. };
  8805. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8806. return true;
  8807. };
  8808. DirectionalLight.prototype.needCube = function () {
  8809. return false;
  8810. };
  8811. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8812. return this.direction;
  8813. };
  8814. DirectionalLight.prototype.computeTransformedPosition = function () {
  8815. if (this.parent && this.parent.getWorldMatrix) {
  8816. if (!this.transformedPosition) {
  8817. this.transformedPosition = BABYLON.Vector3.Zero();
  8818. }
  8819. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8820. return true;
  8821. }
  8822. return false;
  8823. };
  8824. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8825. if (this.parent && this.parent.getWorldMatrix) {
  8826. if (!this._transformedDirection) {
  8827. this._transformedDirection = BABYLON.Vector3.Zero();
  8828. }
  8829. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8830. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8831. return;
  8832. }
  8833. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8834. };
  8835. DirectionalLight.prototype._getWorldMatrix = function () {
  8836. if (!this._worldMatrix) {
  8837. this._worldMatrix = BABYLON.Matrix.Identity();
  8838. }
  8839. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8840. return this._worldMatrix;
  8841. };
  8842. DirectionalLight.prototype.serialize = function () {
  8843. var serializationObject = _super.prototype.serialize.call(this);
  8844. serializationObject.type = 1;
  8845. serializationObject.position = this.position.asArray();
  8846. serializationObject.direction = this.direction.asArray();
  8847. return serializationObject;
  8848. };
  8849. return DirectionalLight;
  8850. })(BABYLON.Light);
  8851. BABYLON.DirectionalLight = DirectionalLight;
  8852. })(BABYLON || (BABYLON = {}));
  8853. var BABYLON;
  8854. (function (BABYLON) {
  8855. var ShadowGenerator = (function () {
  8856. function ShadowGenerator(mapSize, light) {
  8857. var _this = this;
  8858. // Members
  8859. this._filter = ShadowGenerator.FILTER_NONE;
  8860. this.blurScale = 2;
  8861. this._blurBoxOffset = 0;
  8862. this._bias = 0.00005;
  8863. this._lightDirection = BABYLON.Vector3.Zero();
  8864. this._darkness = 0;
  8865. this._transparencyShadow = false;
  8866. this._viewMatrix = BABYLON.Matrix.Zero();
  8867. this._projectionMatrix = BABYLON.Matrix.Zero();
  8868. this._transformMatrix = BABYLON.Matrix.Zero();
  8869. this._worldViewProjection = BABYLON.Matrix.Zero();
  8870. this._currentFaceIndex = 0;
  8871. this._currentFaceIndexCache = 0;
  8872. this._light = light;
  8873. this._scene = light.getScene();
  8874. this._mapSize = mapSize;
  8875. light._shadowGenerator = this;
  8876. // Render target
  8877. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8878. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8879. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8880. this._shadowMap.anisotropicFilteringLevel = 1;
  8881. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8882. this._shadowMap.renderParticles = false;
  8883. this._shadowMap.onBeforeRender = function (faceIndex) {
  8884. _this._currentFaceIndex = faceIndex;
  8885. };
  8886. this._shadowMap.onAfterUnbind = function () {
  8887. if (!_this.useBlurVarianceShadowMap) {
  8888. return;
  8889. }
  8890. if (!_this._shadowMap2) {
  8891. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8892. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8893. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8894. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8895. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8896. _this._downSamplePostprocess.onApply = function (effect) {
  8897. effect.setTexture("textureSampler", _this._shadowMap);
  8898. };
  8899. _this.blurBoxOffset = 1;
  8900. }
  8901. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8902. };
  8903. // Custom render function
  8904. var renderSubMesh = function (subMesh) {
  8905. var mesh = subMesh.getRenderingMesh();
  8906. var scene = _this._scene;
  8907. var engine = scene.getEngine();
  8908. // Culling
  8909. engine.setState(subMesh.getMaterial().backFaceCulling);
  8910. // Managing instances
  8911. var batch = mesh._getInstancesRenderList(subMesh._id);
  8912. if (batch.mustReturn) {
  8913. return;
  8914. }
  8915. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8916. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8917. engine.enableEffect(_this._effect);
  8918. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8919. var material = subMesh.getMaterial();
  8920. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8921. // Alpha test
  8922. if (material && material.needAlphaTesting()) {
  8923. var alphaTexture = material.getAlphaTestTexture();
  8924. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8925. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8926. }
  8927. // Bones
  8928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8929. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8930. }
  8931. // Draw
  8932. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8933. }
  8934. else {
  8935. // Need to reset refresh rate of the shadowMap
  8936. _this._shadowMap.resetRefreshCounter();
  8937. }
  8938. };
  8939. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8940. var index;
  8941. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8942. renderSubMesh(opaqueSubMeshes.data[index]);
  8943. }
  8944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8945. renderSubMesh(alphaTestSubMeshes.data[index]);
  8946. }
  8947. if (_this._transparencyShadow) {
  8948. for (index = 0; index < transparentSubMeshes.length; index++) {
  8949. renderSubMesh(transparentSubMeshes.data[index]);
  8950. }
  8951. }
  8952. };
  8953. this._shadowMap.onClear = function (engine) {
  8954. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8955. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8956. }
  8957. else {
  8958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8959. }
  8960. };
  8961. }
  8962. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8963. // Static
  8964. get: function () {
  8965. return ShadowGenerator._FILTER_NONE;
  8966. },
  8967. enumerable: true,
  8968. configurable: true
  8969. });
  8970. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8971. get: function () {
  8972. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8973. },
  8974. enumerable: true,
  8975. configurable: true
  8976. });
  8977. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8978. get: function () {
  8979. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8985. get: function () {
  8986. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8987. },
  8988. enumerable: true,
  8989. configurable: true
  8990. });
  8991. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8992. get: function () {
  8993. return this._bias;
  8994. },
  8995. set: function (bias) {
  8996. this._bias = bias;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9002. get: function () {
  9003. return this._blurBoxOffset;
  9004. },
  9005. set: function (value) {
  9006. var _this = this;
  9007. if (this._blurBoxOffset === value) {
  9008. return;
  9009. }
  9010. this._blurBoxOffset = value;
  9011. if (this._boxBlurPostprocess) {
  9012. this._boxBlurPostprocess.dispose();
  9013. }
  9014. 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);
  9015. this._boxBlurPostprocess.onApply = function (effect) {
  9016. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9017. };
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9023. get: function () {
  9024. return this._filter;
  9025. },
  9026. set: function (value) {
  9027. if (this._filter === value) {
  9028. return;
  9029. }
  9030. this._filter = value;
  9031. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9032. this._shadowMap.anisotropicFilteringLevel = 16;
  9033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9034. }
  9035. else {
  9036. this._shadowMap.anisotropicFilteringLevel = 1;
  9037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9038. }
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9044. get: function () {
  9045. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9046. },
  9047. set: function (value) {
  9048. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9049. },
  9050. enumerable: true,
  9051. configurable: true
  9052. });
  9053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9054. get: function () {
  9055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9056. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9057. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9058. },
  9059. set: function (value) {
  9060. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9066. get: function () {
  9067. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9068. },
  9069. set: function (value) {
  9070. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9076. var defines = [];
  9077. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9078. defines.push("#define VSM");
  9079. }
  9080. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9081. var mesh = subMesh.getMesh();
  9082. var material = subMesh.getMaterial();
  9083. // Alpha test
  9084. if (material && material.needAlphaTesting()) {
  9085. defines.push("#define ALPHATEST");
  9086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9087. attribs.push(BABYLON.VertexBuffer.UVKind);
  9088. defines.push("#define UV1");
  9089. }
  9090. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9092. defines.push("#define UV2");
  9093. }
  9094. }
  9095. // Bones
  9096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9097. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9098. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9099. if (mesh.numBoneInfluencers > 4) {
  9100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9102. }
  9103. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9104. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9105. }
  9106. else {
  9107. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9108. }
  9109. // Instances
  9110. if (useInstances) {
  9111. defines.push("#define INSTANCES");
  9112. attribs.push("world0");
  9113. attribs.push("world1");
  9114. attribs.push("world2");
  9115. attribs.push("world3");
  9116. }
  9117. // Get correct effect
  9118. var join = defines.join("\n");
  9119. if (this._cachedDefines !== join) {
  9120. this._cachedDefines = join;
  9121. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9122. }
  9123. return this._effect.isReady();
  9124. };
  9125. ShadowGenerator.prototype.getShadowMap = function () {
  9126. return this._shadowMap;
  9127. };
  9128. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9129. if (this._shadowMap2) {
  9130. return this._shadowMap2;
  9131. }
  9132. return this._shadowMap;
  9133. };
  9134. ShadowGenerator.prototype.getLight = function () {
  9135. return this._light;
  9136. };
  9137. // Methods
  9138. ShadowGenerator.prototype.getTransformMatrix = function () {
  9139. var scene = this._scene;
  9140. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9141. return this._transformMatrix;
  9142. }
  9143. this._currentRenderID = scene.getRenderId();
  9144. this._currentFaceIndexCache = this._currentFaceIndex;
  9145. var lightPosition = this._light.position;
  9146. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9147. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9148. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9149. }
  9150. if (this._light.computeTransformedPosition()) {
  9151. lightPosition = this._light.transformedPosition;
  9152. }
  9153. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9154. this._cachedPosition = lightPosition.clone();
  9155. this._cachedDirection = this._lightDirection.clone();
  9156. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9157. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9158. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9159. }
  9160. return this._transformMatrix;
  9161. };
  9162. ShadowGenerator.prototype.getDarkness = function () {
  9163. return this._darkness;
  9164. };
  9165. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9166. if (darkness >= 1.0)
  9167. this._darkness = 1.0;
  9168. else if (darkness <= 0.0)
  9169. this._darkness = 0.0;
  9170. else
  9171. this._darkness = darkness;
  9172. };
  9173. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9174. this._transparencyShadow = hasShadow;
  9175. };
  9176. ShadowGenerator.prototype._packHalf = function (depth) {
  9177. var scale = depth * 255.0;
  9178. var fract = scale - Math.floor(scale);
  9179. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9180. };
  9181. ShadowGenerator.prototype.dispose = function () {
  9182. this._shadowMap.dispose();
  9183. if (this._shadowMap2) {
  9184. this._shadowMap2.dispose();
  9185. }
  9186. if (this._downSamplePostprocess) {
  9187. this._downSamplePostprocess.dispose();
  9188. }
  9189. if (this._boxBlurPostprocess) {
  9190. this._boxBlurPostprocess.dispose();
  9191. }
  9192. };
  9193. ShadowGenerator.prototype.serialize = function () {
  9194. var serializationObject = {};
  9195. serializationObject.lightId = this._light.id;
  9196. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9197. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9198. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9199. serializationObject.renderList = [];
  9200. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9201. var mesh = this.getShadowMap().renderList[meshIndex];
  9202. serializationObject.renderList.push(mesh.id);
  9203. }
  9204. return serializationObject;
  9205. };
  9206. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9207. //casting to point light, as light is missing the position attr and typescript complains.
  9208. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9209. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9210. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9211. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9212. shadowGenerator.getShadowMap().renderList.push(mesh);
  9213. }
  9214. if (parsedShadowGenerator.usePoissonSampling) {
  9215. shadowGenerator.usePoissonSampling = true;
  9216. }
  9217. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9218. shadowGenerator.useVarianceShadowMap = true;
  9219. }
  9220. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9221. shadowGenerator.useBlurVarianceShadowMap = true;
  9222. if (parsedShadowGenerator.blurScale) {
  9223. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9224. }
  9225. if (parsedShadowGenerator.blurBoxOffset) {
  9226. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9227. }
  9228. }
  9229. if (parsedShadowGenerator.bias !== undefined) {
  9230. shadowGenerator.bias = parsedShadowGenerator.bias;
  9231. }
  9232. return shadowGenerator;
  9233. };
  9234. ShadowGenerator._FILTER_NONE = 0;
  9235. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9236. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9237. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9238. return ShadowGenerator;
  9239. })();
  9240. BABYLON.ShadowGenerator = ShadowGenerator;
  9241. })(BABYLON || (BABYLON = {}));
  9242. var BABYLON;
  9243. (function (BABYLON) {
  9244. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9245. if (boxMin.x > sphereCenter.x + sphereRadius)
  9246. return false;
  9247. if (sphereCenter.x - sphereRadius > boxMax.x)
  9248. return false;
  9249. if (boxMin.y > sphereCenter.y + sphereRadius)
  9250. return false;
  9251. if (sphereCenter.y - sphereRadius > boxMax.y)
  9252. return false;
  9253. if (boxMin.z > sphereCenter.z + sphereRadius)
  9254. return false;
  9255. if (sphereCenter.z - sphereRadius > boxMax.z)
  9256. return false;
  9257. return true;
  9258. };
  9259. var getLowestRoot = function (a, b, c, maxR) {
  9260. var determinant = b * b - 4.0 * a * c;
  9261. var result = { root: 0, found: false };
  9262. if (determinant < 0)
  9263. return result;
  9264. var sqrtD = Math.sqrt(determinant);
  9265. var r1 = (-b - sqrtD) / (2.0 * a);
  9266. var r2 = (-b + sqrtD) / (2.0 * a);
  9267. if (r1 > r2) {
  9268. var temp = r2;
  9269. r2 = r1;
  9270. r1 = temp;
  9271. }
  9272. if (r1 > 0 && r1 < maxR) {
  9273. result.root = r1;
  9274. result.found = true;
  9275. return result;
  9276. }
  9277. if (r2 > 0 && r2 < maxR) {
  9278. result.root = r2;
  9279. result.found = true;
  9280. return result;
  9281. }
  9282. return result;
  9283. };
  9284. var Collider = (function () {
  9285. function Collider() {
  9286. this.radius = new BABYLON.Vector3(1, 1, 1);
  9287. this.retry = 0;
  9288. this.basePointWorld = BABYLON.Vector3.Zero();
  9289. this.velocityWorld = BABYLON.Vector3.Zero();
  9290. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9291. this._collisionPoint = BABYLON.Vector3.Zero();
  9292. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9293. this._tempVector = BABYLON.Vector3.Zero();
  9294. this._tempVector2 = BABYLON.Vector3.Zero();
  9295. this._tempVector3 = BABYLON.Vector3.Zero();
  9296. this._tempVector4 = BABYLON.Vector3.Zero();
  9297. this._edge = BABYLON.Vector3.Zero();
  9298. this._baseToVertex = BABYLON.Vector3.Zero();
  9299. this._destinationPoint = BABYLON.Vector3.Zero();
  9300. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9301. this._displacementVector = BABYLON.Vector3.Zero();
  9302. }
  9303. // Methods
  9304. Collider.prototype._initialize = function (source, dir, e) {
  9305. this.velocity = dir;
  9306. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9307. this.basePoint = source;
  9308. source.multiplyToRef(this.radius, this.basePointWorld);
  9309. dir.multiplyToRef(this.radius, this.velocityWorld);
  9310. this.velocityWorldLength = this.velocityWorld.length();
  9311. this.epsilon = e;
  9312. this.collisionFound = false;
  9313. };
  9314. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9315. pa.subtractToRef(point, this._tempVector);
  9316. pb.subtractToRef(point, this._tempVector2);
  9317. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9318. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9319. if (d < 0)
  9320. return false;
  9321. pc.subtractToRef(point, this._tempVector3);
  9322. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9323. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9324. if (d < 0)
  9325. return false;
  9326. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9327. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9328. return d >= 0;
  9329. };
  9330. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9331. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9332. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9333. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9334. return false;
  9335. }
  9336. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9337. return false;
  9338. return true;
  9339. };
  9340. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9341. var t0;
  9342. var embeddedInPlane = false;
  9343. //defensive programming, actually not needed.
  9344. if (!trianglePlaneArray) {
  9345. trianglePlaneArray = [];
  9346. }
  9347. if (!trianglePlaneArray[faceIndex]) {
  9348. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9349. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9350. }
  9351. var trianglePlane = trianglePlaneArray[faceIndex];
  9352. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9353. return;
  9354. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9355. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9356. if (normalDotVelocity == 0) {
  9357. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9358. return;
  9359. embeddedInPlane = true;
  9360. t0 = 0;
  9361. }
  9362. else {
  9363. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9364. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9365. if (t0 > t1) {
  9366. var temp = t1;
  9367. t1 = t0;
  9368. t0 = temp;
  9369. }
  9370. if (t0 > 1.0 || t1 < 0.0)
  9371. return;
  9372. if (t0 < 0)
  9373. t0 = 0;
  9374. if (t0 > 1.0)
  9375. t0 = 1.0;
  9376. }
  9377. this._collisionPoint.copyFromFloats(0, 0, 0);
  9378. var found = false;
  9379. var t = 1.0;
  9380. if (!embeddedInPlane) {
  9381. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9382. this.velocity.scaleToRef(t0, this._tempVector);
  9383. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9384. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9385. found = true;
  9386. t = t0;
  9387. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9388. }
  9389. }
  9390. if (!found) {
  9391. var velocitySquaredLength = this.velocity.lengthSquared();
  9392. var a = velocitySquaredLength;
  9393. this.basePoint.subtractToRef(p1, this._tempVector);
  9394. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9395. var c = this._tempVector.lengthSquared() - 1.0;
  9396. var lowestRoot = getLowestRoot(a, b, c, t);
  9397. if (lowestRoot.found) {
  9398. t = lowestRoot.root;
  9399. found = true;
  9400. this._collisionPoint.copyFrom(p1);
  9401. }
  9402. this.basePoint.subtractToRef(p2, this._tempVector);
  9403. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9404. c = this._tempVector.lengthSquared() - 1.0;
  9405. lowestRoot = getLowestRoot(a, b, c, t);
  9406. if (lowestRoot.found) {
  9407. t = lowestRoot.root;
  9408. found = true;
  9409. this._collisionPoint.copyFrom(p2);
  9410. }
  9411. this.basePoint.subtractToRef(p3, this._tempVector);
  9412. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9413. c = this._tempVector.lengthSquared() - 1.0;
  9414. lowestRoot = getLowestRoot(a, b, c, t);
  9415. if (lowestRoot.found) {
  9416. t = lowestRoot.root;
  9417. found = true;
  9418. this._collisionPoint.copyFrom(p3);
  9419. }
  9420. p2.subtractToRef(p1, this._edge);
  9421. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9422. var edgeSquaredLength = this._edge.lengthSquared();
  9423. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9424. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9425. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9426. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9427. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9428. lowestRoot = getLowestRoot(a, b, c, t);
  9429. if (lowestRoot.found) {
  9430. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9431. if (f >= 0.0 && f <= 1.0) {
  9432. t = lowestRoot.root;
  9433. found = true;
  9434. this._edge.scaleInPlace(f);
  9435. p1.addToRef(this._edge, this._collisionPoint);
  9436. }
  9437. }
  9438. p3.subtractToRef(p2, this._edge);
  9439. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9440. edgeSquaredLength = this._edge.lengthSquared();
  9441. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9442. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9443. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9444. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9445. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9446. lowestRoot = getLowestRoot(a, b, c, t);
  9447. if (lowestRoot.found) {
  9448. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9449. if (f >= 0.0 && f <= 1.0) {
  9450. t = lowestRoot.root;
  9451. found = true;
  9452. this._edge.scaleInPlace(f);
  9453. p2.addToRef(this._edge, this._collisionPoint);
  9454. }
  9455. }
  9456. p1.subtractToRef(p3, this._edge);
  9457. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9458. edgeSquaredLength = this._edge.lengthSquared();
  9459. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9460. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9461. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9462. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9463. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9464. lowestRoot = getLowestRoot(a, b, c, t);
  9465. if (lowestRoot.found) {
  9466. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9467. if (f >= 0.0 && f <= 1.0) {
  9468. t = lowestRoot.root;
  9469. found = true;
  9470. this._edge.scaleInPlace(f);
  9471. p3.addToRef(this._edge, this._collisionPoint);
  9472. }
  9473. }
  9474. }
  9475. if (found) {
  9476. var distToCollision = t * this.velocity.length();
  9477. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9478. if (!this.intersectionPoint) {
  9479. this.intersectionPoint = this._collisionPoint.clone();
  9480. }
  9481. else {
  9482. this.intersectionPoint.copyFrom(this._collisionPoint);
  9483. }
  9484. this.nearestDistance = distToCollision;
  9485. this.collisionFound = true;
  9486. }
  9487. }
  9488. };
  9489. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9490. for (var i = indexStart; i < indexEnd; i += 3) {
  9491. var p1 = pts[indices[i] - decal];
  9492. var p2 = pts[indices[i + 1] - decal];
  9493. var p3 = pts[indices[i + 2] - decal];
  9494. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9495. }
  9496. };
  9497. Collider.prototype._getResponse = function (pos, vel) {
  9498. pos.addToRef(vel, this._destinationPoint);
  9499. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9500. this.basePoint.addToRef(vel, pos);
  9501. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9502. this._slidePlaneNormal.normalize();
  9503. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9504. pos.addInPlace(this._displacementVector);
  9505. this.intersectionPoint.addInPlace(this._displacementVector);
  9506. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9507. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9508. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9509. };
  9510. return Collider;
  9511. })();
  9512. BABYLON.Collider = Collider;
  9513. })(BABYLON || (BABYLON = {}));
  9514. var BABYLON;
  9515. (function (BABYLON) {
  9516. //WebWorker code will be inserted to this variable.
  9517. BABYLON.CollisionWorker = "";
  9518. (function (WorkerTaskType) {
  9519. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9520. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9521. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9522. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9523. var WorkerTaskType = BABYLON.WorkerTaskType;
  9524. (function (WorkerReplyType) {
  9525. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9526. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9527. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9528. var WorkerReplyType = BABYLON.WorkerReplyType;
  9529. var CollisionCoordinatorWorker = (function () {
  9530. function CollisionCoordinatorWorker() {
  9531. var _this = this;
  9532. this._scaledPosition = BABYLON.Vector3.Zero();
  9533. this._scaledVelocity = BABYLON.Vector3.Zero();
  9534. this.onMeshUpdated = function (mesh) {
  9535. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9536. };
  9537. this.onGeometryUpdated = function (geometry) {
  9538. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9539. };
  9540. this._afterRender = function () {
  9541. if (!_this._init)
  9542. return;
  9543. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9544. return;
  9545. }
  9546. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9547. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9548. if (_this._runningUpdated > 4) {
  9549. return;
  9550. }
  9551. ++_this._runningUpdated;
  9552. var payload = {
  9553. updatedMeshes: _this._addUpdateMeshesList,
  9554. updatedGeometries: _this._addUpdateGeometriesList,
  9555. removedGeometries: _this._toRemoveGeometryArray,
  9556. removedMeshes: _this._toRemoveMeshesArray
  9557. };
  9558. var message = {
  9559. payload: payload,
  9560. taskType: WorkerTaskType.UPDATE
  9561. };
  9562. var serializable = [];
  9563. for (var id in payload.updatedGeometries) {
  9564. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9565. //prepare transferables
  9566. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9567. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9568. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9569. }
  9570. }
  9571. _this._worker.postMessage(message, serializable);
  9572. _this._addUpdateMeshesList = {};
  9573. _this._addUpdateGeometriesList = {};
  9574. _this._toRemoveGeometryArray = [];
  9575. _this._toRemoveMeshesArray = [];
  9576. };
  9577. this._onMessageFromWorker = function (e) {
  9578. var returnData = e.data;
  9579. if (returnData.error != WorkerReplyType.SUCCESS) {
  9580. //TODO what errors can be returned from the worker?
  9581. BABYLON.Tools.Warn("error returned from worker!");
  9582. return;
  9583. }
  9584. switch (returnData.taskType) {
  9585. case WorkerTaskType.INIT:
  9586. _this._init = true;
  9587. //Update the worked with ALL of the scene's current state
  9588. _this._scene.meshes.forEach(function (mesh) {
  9589. _this.onMeshAdded(mesh);
  9590. });
  9591. _this._scene.getGeometries().forEach(function (geometry) {
  9592. _this.onGeometryAdded(geometry);
  9593. });
  9594. break;
  9595. case WorkerTaskType.UPDATE:
  9596. _this._runningUpdated--;
  9597. break;
  9598. case WorkerTaskType.COLLIDE:
  9599. _this._runningCollisionTask = false;
  9600. var returnPayload = returnData.payload;
  9601. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9602. return;
  9603. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9604. //cleanup
  9605. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9606. break;
  9607. }
  9608. };
  9609. this._collisionsCallbackArray = [];
  9610. this._init = false;
  9611. this._runningUpdated = 0;
  9612. this._runningCollisionTask = false;
  9613. this._addUpdateMeshesList = {};
  9614. this._addUpdateGeometriesList = {};
  9615. this._toRemoveGeometryArray = [];
  9616. this._toRemoveMeshesArray = [];
  9617. }
  9618. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9619. if (!this._init)
  9620. return;
  9621. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9622. return;
  9623. position.divideToRef(collider.radius, this._scaledPosition);
  9624. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9625. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9626. var payload = {
  9627. collider: {
  9628. position: this._scaledPosition.asArray(),
  9629. velocity: this._scaledVelocity.asArray(),
  9630. radius: collider.radius.asArray()
  9631. },
  9632. collisionId: collisionIndex,
  9633. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9634. maximumRetry: maximumRetry
  9635. };
  9636. var message = {
  9637. payload: payload,
  9638. taskType: WorkerTaskType.COLLIDE
  9639. };
  9640. this._worker.postMessage(message);
  9641. };
  9642. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9643. this._scene = scene;
  9644. this._scene.registerAfterRender(this._afterRender);
  9645. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9646. this._worker = new Worker(workerUrl);
  9647. this._worker.onmessage = this._onMessageFromWorker;
  9648. var message = {
  9649. payload: {},
  9650. taskType: WorkerTaskType.INIT
  9651. };
  9652. this._worker.postMessage(message);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.destroy = function () {
  9655. this._scene.unregisterAfterRender(this._afterRender);
  9656. this._worker.terminate();
  9657. };
  9658. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9659. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9660. this.onMeshUpdated(mesh);
  9661. };
  9662. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9663. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9664. };
  9665. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9666. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9667. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9668. this.onGeometryUpdated(geometry);
  9669. };
  9670. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9671. this._toRemoveGeometryArray.push(geometry.id);
  9672. };
  9673. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9674. var submeshes = [];
  9675. if (mesh.subMeshes) {
  9676. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9677. return {
  9678. position: idx,
  9679. verticesStart: sm.verticesStart,
  9680. verticesCount: sm.verticesCount,
  9681. indexStart: sm.indexStart,
  9682. indexCount: sm.indexCount,
  9683. hasMaterial: !!sm.getMaterial(),
  9684. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9685. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9686. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9687. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9688. };
  9689. });
  9690. }
  9691. var geometryId = null;
  9692. if (mesh instanceof BABYLON.Mesh) {
  9693. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9694. }
  9695. else if (mesh instanceof BABYLON.InstancedMesh) {
  9696. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9697. }
  9698. return {
  9699. uniqueId: mesh.uniqueId,
  9700. id: mesh.id,
  9701. name: mesh.name,
  9702. geometryId: geometryId,
  9703. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9704. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9705. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9706. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9707. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9708. subMeshes: submeshes,
  9709. checkCollisions: mesh.checkCollisions
  9710. };
  9711. };
  9712. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9713. return {
  9714. id: geometry.id,
  9715. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9716. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9717. indices: new Int32Array(geometry.getIndices() || []),
  9718. };
  9719. };
  9720. return CollisionCoordinatorWorker;
  9721. })();
  9722. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9723. var CollisionCoordinatorLegacy = (function () {
  9724. function CollisionCoordinatorLegacy() {
  9725. this._scaledPosition = BABYLON.Vector3.Zero();
  9726. this._scaledVelocity = BABYLON.Vector3.Zero();
  9727. this._finalPosition = BABYLON.Vector3.Zero();
  9728. }
  9729. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9730. position.divideToRef(collider.radius, this._scaledPosition);
  9731. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9732. collider.collidedMesh = null;
  9733. collider.retry = 0;
  9734. collider.initialVelocity = this._scaledVelocity;
  9735. collider.initialPosition = this._scaledPosition;
  9736. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9737. this._finalPosition.multiplyInPlace(collider.radius);
  9738. //run the callback
  9739. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9740. };
  9741. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9742. this._scene = scene;
  9743. };
  9744. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9745. //Legacy need no destruction method.
  9746. };
  9747. //No update in legacy mode
  9748. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9749. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9750. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9751. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9752. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9753. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9754. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9755. if (excludedMesh === void 0) { excludedMesh = null; }
  9756. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9757. if (collider.retry >= maximumRetry) {
  9758. finalPosition.copyFrom(position);
  9759. return;
  9760. }
  9761. collider._initialize(position, velocity, closeDistance);
  9762. // Check all meshes
  9763. for (var index = 0; index < this._scene.meshes.length; index++) {
  9764. var mesh = this._scene.meshes[index];
  9765. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9766. mesh._checkCollision(collider);
  9767. }
  9768. }
  9769. if (!collider.collisionFound) {
  9770. position.addToRef(velocity, finalPosition);
  9771. return;
  9772. }
  9773. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9774. collider._getResponse(position, velocity);
  9775. }
  9776. if (velocity.length() <= closeDistance) {
  9777. finalPosition.copyFrom(position);
  9778. return;
  9779. }
  9780. collider.retry++;
  9781. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9782. };
  9783. return CollisionCoordinatorLegacy;
  9784. })();
  9785. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9786. })(BABYLON || (BABYLON = {}));
  9787. var BABYLON;
  9788. (function (BABYLON) {
  9789. var VRCameraMetrics = (function () {
  9790. function VRCameraMetrics() {
  9791. this.compensateDistortion = true;
  9792. }
  9793. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9794. get: function () {
  9795. return this.hResolution / (2 * this.vResolution);
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9801. get: function () {
  9802. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9803. },
  9804. enumerable: true,
  9805. configurable: true
  9806. });
  9807. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9808. get: function () {
  9809. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9810. var h = (4 * meters) / this.hScreenSize;
  9811. return BABYLON.Matrix.Translation(h, 0, 0);
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9817. get: function () {
  9818. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9819. var h = (4 * meters) / this.hScreenSize;
  9820. return BABYLON.Matrix.Translation(-h, 0, 0);
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9826. get: function () {
  9827. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9833. get: function () {
  9834. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. VRCameraMetrics.GetDefault = function () {
  9840. var result = new VRCameraMetrics();
  9841. result.hResolution = 1280;
  9842. result.vResolution = 800;
  9843. result.hScreenSize = 0.149759993;
  9844. result.vScreenSize = 0.0935999975;
  9845. result.vScreenCenter = 0.0467999987,
  9846. result.eyeToScreenDistance = 0.0410000011;
  9847. result.lensSeparationDistance = 0.0635000020;
  9848. result.interpupillaryDistance = 0.0640000030;
  9849. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9850. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9851. result.postProcessScaleFactor = 1.714605507808412;
  9852. result.lensCenterOffset = 0.151976421;
  9853. return result;
  9854. };
  9855. return VRCameraMetrics;
  9856. })();
  9857. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9858. var Camera = (function (_super) {
  9859. __extends(Camera, _super);
  9860. function Camera(name, position, scene) {
  9861. _super.call(this, name, scene);
  9862. this.position = position;
  9863. // Members
  9864. this.upVector = BABYLON.Vector3.Up();
  9865. this.orthoLeft = null;
  9866. this.orthoRight = null;
  9867. this.orthoBottom = null;
  9868. this.orthoTop = null;
  9869. this.fov = 0.8;
  9870. this.minZ = 1.0;
  9871. this.maxZ = 10000.0;
  9872. this.inertia = 0.9;
  9873. this.mode = Camera.PERSPECTIVE_CAMERA;
  9874. this.isIntermediate = false;
  9875. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9876. this.layerMask = 0x0FFFFFFF;
  9877. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9878. // Camera rig members
  9879. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9880. this._rigCameras = new Array();
  9881. // Cache
  9882. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9883. this._projectionMatrix = new BABYLON.Matrix();
  9884. this._postProcesses = new Array();
  9885. this._postProcessesTakenIndices = [];
  9886. this._activeMeshes = new BABYLON.SmartArray(256);
  9887. this._globalPosition = BABYLON.Vector3.Zero();
  9888. scene.addCamera(this);
  9889. if (!scene.activeCamera) {
  9890. scene.activeCamera = this;
  9891. }
  9892. }
  9893. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9894. get: function () {
  9895. return Camera._PERSPECTIVE_CAMERA;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9901. get: function () {
  9902. return Camera._ORTHOGRAPHIC_CAMERA;
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9908. get: function () {
  9909. return Camera._FOVMODE_VERTICAL_FIXED;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9915. get: function () {
  9916. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9922. get: function () {
  9923. return Camera._RIG_MODE_NONE;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9929. get: function () {
  9930. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9936. get: function () {
  9937. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9943. get: function () {
  9944. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9950. get: function () {
  9951. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9957. get: function () {
  9958. return Camera._RIG_MODE_VR;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Object.defineProperty(Camera.prototype, "globalPosition", {
  9964. get: function () {
  9965. return this._globalPosition;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Camera.prototype.getActiveMeshes = function () {
  9971. return this._activeMeshes;
  9972. };
  9973. Camera.prototype.isActiveMesh = function (mesh) {
  9974. return (this._activeMeshes.indexOf(mesh) !== -1);
  9975. };
  9976. //Cache
  9977. Camera.prototype._initCache = function () {
  9978. _super.prototype._initCache.call(this);
  9979. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9980. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9981. this._cache.mode = undefined;
  9982. this._cache.minZ = undefined;
  9983. this._cache.maxZ = undefined;
  9984. this._cache.fov = undefined;
  9985. this._cache.aspectRatio = undefined;
  9986. this._cache.orthoLeft = undefined;
  9987. this._cache.orthoRight = undefined;
  9988. this._cache.orthoBottom = undefined;
  9989. this._cache.orthoTop = undefined;
  9990. this._cache.renderWidth = undefined;
  9991. this._cache.renderHeight = undefined;
  9992. };
  9993. Camera.prototype._updateCache = function (ignoreParentClass) {
  9994. if (!ignoreParentClass) {
  9995. _super.prototype._updateCache.call(this);
  9996. }
  9997. var engine = this.getEngine();
  9998. this._cache.position.copyFrom(this.position);
  9999. this._cache.upVector.copyFrom(this.upVector);
  10000. this._cache.mode = this.mode;
  10001. this._cache.minZ = this.minZ;
  10002. this._cache.maxZ = this.maxZ;
  10003. this._cache.fov = this.fov;
  10004. this._cache.aspectRatio = engine.getAspectRatio(this);
  10005. this._cache.orthoLeft = this.orthoLeft;
  10006. this._cache.orthoRight = this.orthoRight;
  10007. this._cache.orthoBottom = this.orthoBottom;
  10008. this._cache.orthoTop = this.orthoTop;
  10009. this._cache.renderWidth = engine.getRenderWidth();
  10010. this._cache.renderHeight = engine.getRenderHeight();
  10011. };
  10012. Camera.prototype._updateFromScene = function () {
  10013. this.updateCache();
  10014. this._update();
  10015. };
  10016. // Synchronized
  10017. Camera.prototype._isSynchronized = function () {
  10018. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10019. };
  10020. Camera.prototype._isSynchronizedViewMatrix = function () {
  10021. if (!_super.prototype._isSynchronized.call(this))
  10022. return false;
  10023. return this._cache.position.equals(this.position)
  10024. && this._cache.upVector.equals(this.upVector)
  10025. && this.isSynchronizedWithParent();
  10026. };
  10027. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10028. var check = this._cache.mode === this.mode
  10029. && this._cache.minZ === this.minZ
  10030. && this._cache.maxZ === this.maxZ;
  10031. if (!check) {
  10032. return false;
  10033. }
  10034. var engine = this.getEngine();
  10035. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10036. check = this._cache.fov === this.fov
  10037. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10038. }
  10039. else {
  10040. check = this._cache.orthoLeft === this.orthoLeft
  10041. && this._cache.orthoRight === this.orthoRight
  10042. && this._cache.orthoBottom === this.orthoBottom
  10043. && this._cache.orthoTop === this.orthoTop
  10044. && this._cache.renderWidth === engine.getRenderWidth()
  10045. && this._cache.renderHeight === engine.getRenderHeight();
  10046. }
  10047. return check;
  10048. };
  10049. // Controls
  10050. Camera.prototype.attachControl = function (element) {
  10051. };
  10052. Camera.prototype.detachControl = function (element) {
  10053. };
  10054. Camera.prototype._update = function () {
  10055. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10056. this._updateRigCameras();
  10057. }
  10058. this._checkInputs();
  10059. };
  10060. Camera.prototype._checkInputs = function () {
  10061. };
  10062. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10063. if (insertAt === void 0) { insertAt = null; }
  10064. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10065. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10066. return 0;
  10067. }
  10068. if (insertAt == null || insertAt < 0) {
  10069. this._postProcesses.push(postProcess);
  10070. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10071. return this._postProcesses.length - 1;
  10072. }
  10073. var add = 0;
  10074. var i;
  10075. var start;
  10076. if (this._postProcesses[insertAt]) {
  10077. start = this._postProcesses.length - 1;
  10078. for (i = start; i >= insertAt + 1; --i) {
  10079. this._postProcesses[i + 1] = this._postProcesses[i];
  10080. }
  10081. add = 1;
  10082. }
  10083. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10084. if (this._postProcessesTakenIndices[i] < insertAt) {
  10085. continue;
  10086. }
  10087. start = this._postProcessesTakenIndices.length - 1;
  10088. for (var j = start; j >= i; --j) {
  10089. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10090. }
  10091. this._postProcessesTakenIndices[i] = insertAt;
  10092. break;
  10093. }
  10094. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10095. this._postProcessesTakenIndices.push(insertAt);
  10096. }
  10097. var result = insertAt + add;
  10098. this._postProcesses[result] = postProcess;
  10099. return result;
  10100. };
  10101. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10102. if (atIndices === void 0) { atIndices = null; }
  10103. var result = [];
  10104. var i;
  10105. var index;
  10106. if (!atIndices) {
  10107. var length = this._postProcesses.length;
  10108. for (i = 0; i < length; i++) {
  10109. if (this._postProcesses[i] !== postProcess) {
  10110. continue;
  10111. }
  10112. delete this._postProcesses[i];
  10113. index = this._postProcessesTakenIndices.indexOf(i);
  10114. this._postProcessesTakenIndices.splice(index, 1);
  10115. }
  10116. }
  10117. else {
  10118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10119. for (i = 0; i < atIndices.length; i++) {
  10120. var foundPostProcess = this._postProcesses[atIndices[i]];
  10121. if (foundPostProcess !== postProcess) {
  10122. result.push(i);
  10123. continue;
  10124. }
  10125. delete this._postProcesses[atIndices[i]];
  10126. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10127. this._postProcessesTakenIndices.splice(index, 1);
  10128. }
  10129. }
  10130. return result;
  10131. };
  10132. Camera.prototype.getWorldMatrix = function () {
  10133. if (!this._worldMatrix) {
  10134. this._worldMatrix = BABYLON.Matrix.Identity();
  10135. }
  10136. var viewMatrix = this.getViewMatrix();
  10137. viewMatrix.invertToRef(this._worldMatrix);
  10138. return this._worldMatrix;
  10139. };
  10140. Camera.prototype._getViewMatrix = function () {
  10141. return BABYLON.Matrix.Identity();
  10142. };
  10143. Camera.prototype.getViewMatrix = function (force) {
  10144. this._computedViewMatrix = this._computeViewMatrix(force);
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. if (!this.parent || !this.parent.getWorldMatrix) {
  10149. this._globalPosition.copyFrom(this.position);
  10150. }
  10151. else {
  10152. if (!this._worldMatrix) {
  10153. this._worldMatrix = BABYLON.Matrix.Identity();
  10154. }
  10155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10158. this._computedViewMatrix.invert();
  10159. this._markSyncedWithParent();
  10160. }
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. return this._computedViewMatrix;
  10163. };
  10164. Camera.prototype._computeViewMatrix = function (force) {
  10165. if (!force && this._isSynchronizedViewMatrix()) {
  10166. return this._computedViewMatrix;
  10167. }
  10168. this._computedViewMatrix = this._getViewMatrix();
  10169. this._currentRenderId = this.getScene().getRenderId();
  10170. return this._computedViewMatrix;
  10171. };
  10172. Camera.prototype.getProjectionMatrix = function (force) {
  10173. if (!force && this._isSynchronizedProjectionMatrix()) {
  10174. return this._projectionMatrix;
  10175. }
  10176. var engine = this.getEngine();
  10177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10178. if (this.minZ <= 0) {
  10179. this.minZ = 0.1;
  10180. }
  10181. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10182. return this._projectionMatrix;
  10183. }
  10184. var halfWidth = engine.getRenderWidth() / 2.0;
  10185. var halfHeight = engine.getRenderHeight() / 2.0;
  10186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10187. return this._projectionMatrix;
  10188. };
  10189. Camera.prototype.dispose = function () {
  10190. // Animations
  10191. this.getScene().stopAnimation(this);
  10192. // Remove from scene
  10193. this.getScene().removeCamera(this);
  10194. while (this._rigCameras.length > 0) {
  10195. this._rigCameras.pop().dispose();
  10196. }
  10197. // Postprocesses
  10198. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10199. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10200. }
  10201. };
  10202. // ---- Camera rigs section ----
  10203. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10204. while (this._rigCameras.length > 0) {
  10205. this._rigCameras.pop().dispose();
  10206. }
  10207. this.cameraRigMode = mode;
  10208. this._cameraRigParams = {};
  10209. switch (this.cameraRigMode) {
  10210. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10212. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10213. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10214. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10215. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10216. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10217. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10218. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10219. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10220. break;
  10221. }
  10222. var postProcesses = new Array();
  10223. switch (this.cameraRigMode) {
  10224. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10225. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10226. this._rigCameras[0].isIntermediate = true;
  10227. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10228. postProcesses[1].onApply = function (effect) {
  10229. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10230. };
  10231. break;
  10232. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10233. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10234. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10235. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10236. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10237. var secondCamIndex = 1 - firstCamIndex;
  10238. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10239. this._rigCameras[firstCamIndex].isIntermediate = true;
  10240. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10241. break;
  10242. case Camera.RIG_MODE_VR:
  10243. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10244. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10245. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10246. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10247. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10248. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10249. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10250. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10251. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10252. if (metrics.compensateDistortion) {
  10253. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10254. }
  10255. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10256. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10257. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10258. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10259. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10260. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10261. if (metrics.compensateDistortion) {
  10262. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10263. }
  10264. break;
  10265. }
  10266. this._update();
  10267. };
  10268. Camera.prototype._getVRProjectionMatrix = function () {
  10269. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10270. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10271. return this._projectionMatrix;
  10272. };
  10273. Camera.prototype.setCameraRigParameter = function (name, value) {
  10274. this._cameraRigParams[name] = value;
  10275. //provisionnally:
  10276. if (name === "interaxialDistance") {
  10277. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10278. }
  10279. };
  10280. /**
  10281. * May needs to be overridden by children so sub has required properties to be copied
  10282. */
  10283. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10284. return null;
  10285. };
  10286. /**
  10287. * May needs to be overridden by children
  10288. */
  10289. Camera.prototype._updateRigCameras = function () {
  10290. for (var i = 0; i < this._rigCameras.length; i++) {
  10291. this._rigCameras[i].minZ = this.minZ;
  10292. this._rigCameras[i].maxZ = this.maxZ;
  10293. this._rigCameras[i].fov = this.fov;
  10294. }
  10295. // only update viewport when ANAGLYPH
  10296. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10297. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10298. }
  10299. };
  10300. Camera.prototype.serialize = function () {
  10301. var serializationObject = {};
  10302. serializationObject.name = this.name;
  10303. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10304. serializationObject.id = this.id;
  10305. serializationObject.position = this.position.asArray();
  10306. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10307. // Parent
  10308. if (this.parent) {
  10309. serializationObject.parentId = this.parent.id;
  10310. }
  10311. serializationObject.fov = this.fov;
  10312. serializationObject.minZ = this.minZ;
  10313. serializationObject.maxZ = this.maxZ;
  10314. serializationObject.inertia = this.inertia;
  10315. // Animations
  10316. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10317. // Layer mask
  10318. serializationObject.layerMask = this.layerMask;
  10319. return serializationObject;
  10320. };
  10321. Camera.Parse = function (parsedCamera, scene) {
  10322. var camera;
  10323. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10324. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10325. var interaxial_distance;
  10326. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10327. var alpha = parsedCamera.alpha;
  10328. var beta = parsedCamera.beta;
  10329. var radius = parsedCamera.radius;
  10330. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10331. interaxial_distance = parsedCamera.interaxial_distance;
  10332. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10333. }
  10334. else {
  10335. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10336. }
  10337. }
  10338. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10339. interaxial_distance = parsedCamera.interaxial_distance;
  10340. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10341. }
  10342. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10343. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10344. }
  10345. else if (parsedCamera.type === "FollowCamera") {
  10346. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10347. camera.heightOffset = parsedCamera.heightOffset;
  10348. camera.radius = parsedCamera.radius;
  10349. camera.rotationOffset = parsedCamera.rotationOffset;
  10350. if (lockedTargetMesh)
  10351. camera.target = lockedTargetMesh;
  10352. }
  10353. else if (parsedCamera.type === "GamepadCamera") {
  10354. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10355. }
  10356. else if (parsedCamera.type === "TouchCamera") {
  10357. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10358. }
  10359. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10360. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10361. }
  10362. else if (parsedCamera.type === "WebVRFreeCamera") {
  10363. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10364. }
  10365. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10366. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10367. }
  10368. else {
  10369. // Free Camera is the default value
  10370. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10371. }
  10372. // apply 3d rig, when found
  10373. if (parsedCamera.cameraRigMode) {
  10374. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10375. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10376. }
  10377. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10378. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10379. camera.lockedTarget = lockedTargetMesh;
  10380. }
  10381. camera.id = parsedCamera.id;
  10382. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10383. // Parent
  10384. if (parsedCamera.parentId) {
  10385. camera._waitingParentId = parsedCamera.parentId;
  10386. }
  10387. // Target
  10388. if (parsedCamera.target) {
  10389. if (camera.setTarget) {
  10390. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10391. }
  10392. else {
  10393. //For ArcRotate
  10394. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10395. }
  10396. }
  10397. else {
  10398. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10399. }
  10400. camera.fov = parsedCamera.fov;
  10401. camera.minZ = parsedCamera.minZ;
  10402. camera.maxZ = parsedCamera.maxZ;
  10403. camera.speed = parsedCamera.speed;
  10404. camera.inertia = parsedCamera.inertia;
  10405. camera.checkCollisions = parsedCamera.checkCollisions;
  10406. camera.applyGravity = parsedCamera.applyGravity;
  10407. if (parsedCamera.ellipsoid) {
  10408. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10409. }
  10410. // Animations
  10411. if (parsedCamera.animations) {
  10412. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10413. var parsedAnimation = parsedCamera.animations[animationIndex];
  10414. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10415. }
  10416. }
  10417. if (parsedCamera.autoAnimate) {
  10418. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10419. }
  10420. // Layer Mask
  10421. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10422. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10423. }
  10424. else {
  10425. camera.layerMask = 0x0FFFFFFF;
  10426. }
  10427. return camera;
  10428. };
  10429. // Statics
  10430. Camera._PERSPECTIVE_CAMERA = 0;
  10431. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10432. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10433. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10434. Camera._RIG_MODE_NONE = 0;
  10435. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10436. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10437. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10438. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10439. Camera._RIG_MODE_VR = 20;
  10440. return Camera;
  10441. })(BABYLON.Node);
  10442. BABYLON.Camera = Camera;
  10443. })(BABYLON || (BABYLON = {}));
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. var TargetCamera = (function (_super) {
  10447. __extends(TargetCamera, _super);
  10448. function TargetCamera(name, position, scene) {
  10449. _super.call(this, name, position, scene);
  10450. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10451. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10452. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10453. this.speed = 2.0;
  10454. this.noRotationConstraint = false;
  10455. this.lockedTarget = null;
  10456. this._currentTarget = BABYLON.Vector3.Zero();
  10457. this._viewMatrix = BABYLON.Matrix.Zero();
  10458. this._camMatrix = BABYLON.Matrix.Zero();
  10459. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10460. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10461. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10462. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10463. this._lookAtTemp = BABYLON.Matrix.Zero();
  10464. this._tempMatrix = BABYLON.Matrix.Zero();
  10465. }
  10466. TargetCamera.prototype.getFrontPosition = function (distance) {
  10467. var direction = this.getTarget().subtract(this.position);
  10468. direction.normalize();
  10469. direction.scaleInPlace(distance);
  10470. return this.globalPosition.add(direction);
  10471. };
  10472. TargetCamera.prototype._getLockedTargetPosition = function () {
  10473. if (!this.lockedTarget) {
  10474. return null;
  10475. }
  10476. return this.lockedTarget.position || this.lockedTarget;
  10477. };
  10478. // Cache
  10479. TargetCamera.prototype._initCache = function () {
  10480. _super.prototype._initCache.call(this);
  10481. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10482. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10483. };
  10484. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10485. if (!ignoreParentClass) {
  10486. _super.prototype._updateCache.call(this);
  10487. }
  10488. var lockedTargetPosition = this._getLockedTargetPosition();
  10489. if (!lockedTargetPosition) {
  10490. this._cache.lockedTarget = null;
  10491. }
  10492. else {
  10493. if (!this._cache.lockedTarget) {
  10494. this._cache.lockedTarget = lockedTargetPosition.clone();
  10495. }
  10496. else {
  10497. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10498. }
  10499. }
  10500. this._cache.rotation.copyFrom(this.rotation);
  10501. };
  10502. // Synchronized
  10503. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10504. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10505. return false;
  10506. }
  10507. var lockedTargetPosition = this._getLockedTargetPosition();
  10508. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10509. && this._cache.rotation.equals(this.rotation);
  10510. };
  10511. // Methods
  10512. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10513. var engine = this.getEngine();
  10514. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10515. };
  10516. // Target
  10517. TargetCamera.prototype.setTarget = function (target) {
  10518. this.upVector.normalize();
  10519. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10520. this._camMatrix.invert();
  10521. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10522. var vDir = target.subtract(this.position);
  10523. if (vDir.x >= 0.0) {
  10524. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10525. }
  10526. else {
  10527. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10528. }
  10529. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10530. if (isNaN(this.rotation.x)) {
  10531. this.rotation.x = 0;
  10532. }
  10533. if (isNaN(this.rotation.y)) {
  10534. this.rotation.y = 0;
  10535. }
  10536. if (isNaN(this.rotation.z)) {
  10537. this.rotation.z = 0;
  10538. }
  10539. };
  10540. TargetCamera.prototype.getTarget = function () {
  10541. return this._currentTarget;
  10542. };
  10543. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10544. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10545. };
  10546. TargetCamera.prototype._updatePosition = function () {
  10547. this.position.addInPlace(this.cameraDirection);
  10548. };
  10549. TargetCamera.prototype._checkInputs = function () {
  10550. var needToMove = this._decideIfNeedsToMove();
  10551. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10552. // Move
  10553. if (needToMove) {
  10554. this._updatePosition();
  10555. }
  10556. // Rotate
  10557. if (needToRotate) {
  10558. this.rotation.x += this.cameraRotation.x;
  10559. this.rotation.y += this.cameraRotation.y;
  10560. if (!this.noRotationConstraint) {
  10561. var limit = (Math.PI / 2) * 0.95;
  10562. if (this.rotation.x > limit)
  10563. this.rotation.x = limit;
  10564. if (this.rotation.x < -limit)
  10565. this.rotation.x = -limit;
  10566. }
  10567. }
  10568. // Inertia
  10569. if (needToMove) {
  10570. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10571. this.cameraDirection.x = 0;
  10572. }
  10573. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10574. this.cameraDirection.y = 0;
  10575. }
  10576. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10577. this.cameraDirection.z = 0;
  10578. }
  10579. this.cameraDirection.scaleInPlace(this.inertia);
  10580. }
  10581. if (needToRotate) {
  10582. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10583. this.cameraRotation.x = 0;
  10584. }
  10585. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10586. this.cameraRotation.y = 0;
  10587. }
  10588. this.cameraRotation.scaleInPlace(this.inertia);
  10589. }
  10590. _super.prototype._checkInputs.call(this);
  10591. };
  10592. TargetCamera.prototype._getViewMatrix = function () {
  10593. if (!this.lockedTarget) {
  10594. // Compute
  10595. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10596. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10597. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10598. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10599. this._lookAtTemp.invert();
  10600. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10601. }
  10602. else {
  10603. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10604. }
  10605. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10606. // Computing target and final matrix
  10607. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10608. }
  10609. else {
  10610. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10611. }
  10612. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10613. return this._viewMatrix;
  10614. };
  10615. TargetCamera.prototype._getVRViewMatrix = function () {
  10616. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10617. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10618. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10619. // Computing target and final matrix
  10620. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10621. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10622. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10623. return this._viewMatrix;
  10624. };
  10625. /**
  10626. * @override
  10627. * Override Camera.createRigCamera
  10628. */
  10629. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10630. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10631. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10632. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10633. rigCamera._cameraRigParams = {};
  10634. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10635. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10636. }
  10637. return rigCamera;
  10638. }
  10639. return null;
  10640. };
  10641. /**
  10642. * @override
  10643. * Override Camera._updateRigCameras
  10644. */
  10645. TargetCamera.prototype._updateRigCameras = function () {
  10646. switch (this.cameraRigMode) {
  10647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10651. case BABYLON.Camera.RIG_MODE_VR:
  10652. var camLeft = this._rigCameras[0];
  10653. var camRight = this._rigCameras[1];
  10654. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10655. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10656. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10657. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10658. camLeft.position.copyFrom(this.position);
  10659. camRight.position.copyFrom(this.position);
  10660. }
  10661. else {
  10662. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10663. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10664. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10665. camLeft.setTarget(this.getTarget());
  10666. camRight.setTarget(this.getTarget());
  10667. }
  10668. break;
  10669. }
  10670. _super.prototype._updateRigCameras.call(this);
  10671. };
  10672. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10673. if (!this._rigCamTransformMatrix) {
  10674. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10675. }
  10676. var target = this.getTarget();
  10677. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10678. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10679. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10680. };
  10681. TargetCamera.prototype.serialize = function () {
  10682. var serializationObject = _super.prototype.serialize.call(this);
  10683. serializationObject.speed = this.speed;
  10684. if (this.rotation) {
  10685. serializationObject.rotation = this.rotation.asArray();
  10686. }
  10687. if (this.lockedTarget && this.lockedTarget.id) {
  10688. serializationObject.lockedTargetId = this.lockedTarget.id;
  10689. }
  10690. return serializationObject;
  10691. };
  10692. return TargetCamera;
  10693. })(BABYLON.Camera);
  10694. BABYLON.TargetCamera = TargetCamera;
  10695. })(BABYLON || (BABYLON = {}));
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. var FreeCamera = (function (_super) {
  10699. __extends(FreeCamera, _super);
  10700. function FreeCamera(name, position, scene) {
  10701. var _this = this;
  10702. _super.call(this, name, position, scene);
  10703. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10704. this.keysUp = [38];
  10705. this.keysDown = [40];
  10706. this.keysLeft = [37];
  10707. this.keysRight = [39];
  10708. this.checkCollisions = false;
  10709. this.applyGravity = false;
  10710. this.angularSensibility = 2000.0;
  10711. this._keys = [];
  10712. this._collider = new BABYLON.Collider();
  10713. this._needMoveForGravity = false;
  10714. this._oldPosition = BABYLON.Vector3.Zero();
  10715. this._diffPosition = BABYLON.Vector3.Zero();
  10716. this._newPosition = BABYLON.Vector3.Zero();
  10717. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10718. if (collidedMesh === void 0) { collidedMesh = null; }
  10719. //TODO move this to the collision coordinator!
  10720. if (_this.getScene().workerCollisions)
  10721. newPosition.multiplyInPlace(_this._collider.radius);
  10722. var updatePosition = function (newPos) {
  10723. _this._newPosition.copyFrom(newPos);
  10724. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10725. var oldPosition = _this.position.clone();
  10726. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10727. _this.position.addInPlace(_this._diffPosition);
  10728. if (_this.onCollide && collidedMesh) {
  10729. _this.onCollide(collidedMesh);
  10730. }
  10731. }
  10732. };
  10733. updatePosition(newPosition);
  10734. };
  10735. }
  10736. // Controls
  10737. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10738. var _this = this;
  10739. var previousPosition;
  10740. var engine = this.getEngine();
  10741. if (this._attachedElement) {
  10742. return;
  10743. }
  10744. this._attachedElement = element;
  10745. if (this._onMouseDown === undefined) {
  10746. this._onMouseDown = function (evt) {
  10747. previousPosition = {
  10748. x: evt.clientX,
  10749. y: evt.clientY
  10750. };
  10751. if (!noPreventDefault) {
  10752. evt.preventDefault();
  10753. }
  10754. };
  10755. this._onMouseUp = function (evt) {
  10756. previousPosition = null;
  10757. if (!noPreventDefault) {
  10758. evt.preventDefault();
  10759. }
  10760. };
  10761. this._onMouseOut = function (evt) {
  10762. previousPosition = null;
  10763. _this._keys = [];
  10764. if (!noPreventDefault) {
  10765. evt.preventDefault();
  10766. }
  10767. };
  10768. this._onMouseMove = function (evt) {
  10769. if (!previousPosition && !engine.isPointerLock) {
  10770. return;
  10771. }
  10772. var offsetX;
  10773. var offsetY;
  10774. if (!engine.isPointerLock) {
  10775. offsetX = evt.clientX - previousPosition.x;
  10776. offsetY = evt.clientY - previousPosition.y;
  10777. }
  10778. else {
  10779. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10780. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10781. }
  10782. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10783. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10784. previousPosition = {
  10785. x: evt.clientX,
  10786. y: evt.clientY
  10787. };
  10788. if (!noPreventDefault) {
  10789. evt.preventDefault();
  10790. }
  10791. };
  10792. this._onKeyDown = function (evt) {
  10793. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10794. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10795. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10796. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10797. var index = _this._keys.indexOf(evt.keyCode);
  10798. if (index === -1) {
  10799. _this._keys.push(evt.keyCode);
  10800. }
  10801. if (!noPreventDefault) {
  10802. evt.preventDefault();
  10803. }
  10804. }
  10805. };
  10806. this._onKeyUp = function (evt) {
  10807. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10808. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10809. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10810. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10811. var index = _this._keys.indexOf(evt.keyCode);
  10812. if (index >= 0) {
  10813. _this._keys.splice(index, 1);
  10814. }
  10815. if (!noPreventDefault) {
  10816. evt.preventDefault();
  10817. }
  10818. }
  10819. };
  10820. this._onLostFocus = function () {
  10821. _this._keys = [];
  10822. };
  10823. this._reset = function () {
  10824. _this._keys = [];
  10825. previousPosition = null;
  10826. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10827. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10828. };
  10829. }
  10830. element.addEventListener("mousedown", this._onMouseDown, false);
  10831. element.addEventListener("mouseup", this._onMouseUp, false);
  10832. element.addEventListener("mouseout", this._onMouseOut, false);
  10833. element.addEventListener("mousemove", this._onMouseMove, false);
  10834. BABYLON.Tools.RegisterTopRootEvents([
  10835. { name: "keydown", handler: this._onKeyDown },
  10836. { name: "keyup", handler: this._onKeyUp },
  10837. { name: "blur", handler: this._onLostFocus }
  10838. ]);
  10839. };
  10840. FreeCamera.prototype.detachControl = function (element) {
  10841. if (this._attachedElement !== element) {
  10842. return;
  10843. }
  10844. element.removeEventListener("mousedown", this._onMouseDown);
  10845. element.removeEventListener("mouseup", this._onMouseUp);
  10846. element.removeEventListener("mouseout", this._onMouseOut);
  10847. element.removeEventListener("mousemove", this._onMouseMove);
  10848. BABYLON.Tools.UnregisterTopRootEvents([
  10849. { name: "keydown", handler: this._onKeyDown },
  10850. { name: "keyup", handler: this._onKeyUp },
  10851. { name: "blur", handler: this._onLostFocus }
  10852. ]);
  10853. this._attachedElement = null;
  10854. if (this._reset) {
  10855. this._reset();
  10856. }
  10857. };
  10858. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10859. var globalPosition;
  10860. if (this.parent) {
  10861. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10862. }
  10863. else {
  10864. globalPosition = this.position;
  10865. }
  10866. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10867. this._collider.radius = this.ellipsoid;
  10868. //no need for clone, as long as gravity is not on.
  10869. var actualVelocity = velocity;
  10870. //add gravity to the velocity to prevent the dual-collision checking
  10871. if (this.applyGravity) {
  10872. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10873. actualVelocity = velocity.add(this.getScene().gravity);
  10874. }
  10875. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10876. };
  10877. FreeCamera.prototype._checkInputs = function () {
  10878. if (!this._localDirection) {
  10879. this._localDirection = BABYLON.Vector3.Zero();
  10880. this._transformedDirection = BABYLON.Vector3.Zero();
  10881. }
  10882. // Keyboard
  10883. for (var index = 0; index < this._keys.length; index++) {
  10884. var keyCode = this._keys[index];
  10885. var speed = this._computeLocalCameraSpeed();
  10886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10887. this._localDirection.copyFromFloats(-speed, 0, 0);
  10888. }
  10889. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10890. this._localDirection.copyFromFloats(0, 0, speed);
  10891. }
  10892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10893. this._localDirection.copyFromFloats(speed, 0, 0);
  10894. }
  10895. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10896. this._localDirection.copyFromFloats(0, 0, -speed);
  10897. }
  10898. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10899. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10900. this.cameraDirection.addInPlace(this._transformedDirection);
  10901. }
  10902. _super.prototype._checkInputs.call(this);
  10903. };
  10904. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10905. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10906. };
  10907. FreeCamera.prototype._updatePosition = function () {
  10908. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10909. this._collideWithWorld(this.cameraDirection);
  10910. }
  10911. else {
  10912. this.position.addInPlace(this.cameraDirection);
  10913. }
  10914. };
  10915. FreeCamera.prototype.serialize = function () {
  10916. var serializationObject = _super.prototype.serialize.call(this);
  10917. serializationObject.checkCollisions = this.checkCollisions;
  10918. serializationObject.applyGravity = this.applyGravity;
  10919. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10920. return serializationObject;
  10921. };
  10922. return FreeCamera;
  10923. })(BABYLON.TargetCamera);
  10924. BABYLON.FreeCamera = FreeCamera;
  10925. })(BABYLON || (BABYLON = {}));
  10926. var BABYLON;
  10927. (function (BABYLON) {
  10928. var FollowCamera = (function (_super) {
  10929. __extends(FollowCamera, _super);
  10930. function FollowCamera(name, position, scene) {
  10931. _super.call(this, name, position, scene);
  10932. this.radius = 12;
  10933. this.rotationOffset = 0;
  10934. this.heightOffset = 4;
  10935. this.cameraAcceleration = 0.05;
  10936. this.maxCameraSpeed = 20;
  10937. }
  10938. FollowCamera.prototype.getRadians = function (degrees) {
  10939. return degrees * Math.PI / 180;
  10940. };
  10941. FollowCamera.prototype.follow = function (cameraTarget) {
  10942. if (!cameraTarget)
  10943. return;
  10944. var yRotation;
  10945. if (cameraTarget.rotationQuaternion) {
  10946. var rotMatrix = new BABYLON.Matrix();
  10947. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10948. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10949. }
  10950. else {
  10951. yRotation = cameraTarget.rotation.y;
  10952. }
  10953. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10954. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10955. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10956. var dx = targetX - this.position.x;
  10957. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10958. var dz = (targetZ) - this.position.z;
  10959. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10960. var vy = dy * this.cameraAcceleration;
  10961. var vz = dz * this.cameraAcceleration * 2;
  10962. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10963. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10964. }
  10965. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10966. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10967. }
  10968. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10969. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10970. }
  10971. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10972. this.setTarget(cameraTarget.position);
  10973. };
  10974. FollowCamera.prototype._checkInputs = function () {
  10975. _super.prototype._checkInputs.call(this);
  10976. this.follow(this.target);
  10977. };
  10978. FollowCamera.prototype.serialize = function () {
  10979. var serializationObject = _super.prototype.serialize.call(this);
  10980. serializationObject.radius = this.radius;
  10981. serializationObject.heightOffset = this.heightOffset;
  10982. serializationObject.rotationOffset = this.rotationOffset;
  10983. return serializationObject;
  10984. };
  10985. return FollowCamera;
  10986. })(BABYLON.TargetCamera);
  10987. BABYLON.FollowCamera = FollowCamera;
  10988. var ArcFollowCamera = (function (_super) {
  10989. __extends(ArcFollowCamera, _super);
  10990. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10991. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10992. this.alpha = alpha;
  10993. this.beta = beta;
  10994. this.radius = radius;
  10995. this.target = target;
  10996. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10997. this.follow();
  10998. }
  10999. ArcFollowCamera.prototype.follow = function () {
  11000. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11001. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11002. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11003. this.position = this.target.position.add(this._cartesianCoordinates);
  11004. this.setTarget(this.target.position);
  11005. };
  11006. ArcFollowCamera.prototype._checkInputs = function () {
  11007. _super.prototype._checkInputs.call(this);
  11008. this.follow();
  11009. };
  11010. ArcFollowCamera.prototype.serialize = function () {
  11011. var serializationObject = _super.prototype.serialize.call(this);
  11012. serializationObject.radius = this.radius;
  11013. return serializationObject;
  11014. };
  11015. return ArcFollowCamera;
  11016. })(BABYLON.TargetCamera);
  11017. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11018. })(BABYLON || (BABYLON = {}));
  11019. var BABYLON;
  11020. (function (BABYLON) {
  11021. // We're mainly based on the logic defined into the FreeCamera code
  11022. var TouchCamera = (function (_super) {
  11023. __extends(TouchCamera, _super);
  11024. function TouchCamera(name, position, scene) {
  11025. _super.call(this, name, position, scene);
  11026. this._offsetX = null;
  11027. this._offsetY = null;
  11028. this._pointerCount = 0;
  11029. this._pointerPressed = [];
  11030. this.angularSensibility = 200000.0;
  11031. this.moveSensibility = 500.0;
  11032. }
  11033. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11034. var _this = this;
  11035. var previousPosition;
  11036. if (this._attachedCanvas) {
  11037. return;
  11038. }
  11039. this._attachedCanvas = canvas;
  11040. if (this._onPointerDown === undefined) {
  11041. this._onPointerDown = function (evt) {
  11042. if (!noPreventDefault) {
  11043. evt.preventDefault();
  11044. }
  11045. _this._pointerPressed.push(evt.pointerId);
  11046. if (_this._pointerPressed.length !== 1) {
  11047. return;
  11048. }
  11049. previousPosition = {
  11050. x: evt.clientX,
  11051. y: evt.clientY
  11052. };
  11053. };
  11054. this._onPointerUp = function (evt) {
  11055. if (!noPreventDefault) {
  11056. evt.preventDefault();
  11057. }
  11058. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11059. if (index === -1) {
  11060. return;
  11061. }
  11062. _this._pointerPressed.splice(index, 1);
  11063. if (index != 0) {
  11064. return;
  11065. }
  11066. previousPosition = null;
  11067. _this._offsetX = null;
  11068. _this._offsetY = null;
  11069. };
  11070. this._onPointerMove = function (evt) {
  11071. if (!noPreventDefault) {
  11072. evt.preventDefault();
  11073. }
  11074. if (!previousPosition) {
  11075. return;
  11076. }
  11077. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11078. if (index != 0) {
  11079. return;
  11080. }
  11081. _this._offsetX = evt.clientX - previousPosition.x;
  11082. _this._offsetY = -(evt.clientY - previousPosition.y);
  11083. };
  11084. this._onLostFocus = function () {
  11085. _this._offsetX = null;
  11086. _this._offsetY = null;
  11087. };
  11088. }
  11089. canvas.addEventListener("pointerdown", this._onPointerDown);
  11090. canvas.addEventListener("pointerup", this._onPointerUp);
  11091. canvas.addEventListener("pointerout", this._onPointerUp);
  11092. canvas.addEventListener("pointermove", this._onPointerMove);
  11093. BABYLON.Tools.RegisterTopRootEvents([
  11094. { name: "blur", handler: this._onLostFocus }
  11095. ]);
  11096. };
  11097. TouchCamera.prototype.detachControl = function (canvas) {
  11098. if (this._attachedCanvas !== canvas) {
  11099. return;
  11100. }
  11101. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11102. canvas.removeEventListener("pointerup", this._onPointerUp);
  11103. canvas.removeEventListener("pointerout", this._onPointerUp);
  11104. canvas.removeEventListener("pointermove", this._onPointerMove);
  11105. BABYLON.Tools.UnregisterTopRootEvents([
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. this._attachedCanvas = null;
  11109. };
  11110. TouchCamera.prototype._checkInputs = function () {
  11111. if (this._offsetX) {
  11112. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11113. if (this._pointerPressed.length > 1) {
  11114. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11115. }
  11116. else {
  11117. var speed = this._computeLocalCameraSpeed();
  11118. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11119. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11120. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11121. }
  11122. }
  11123. _super.prototype._checkInputs.call(this);
  11124. };
  11125. return TouchCamera;
  11126. })(BABYLON.FreeCamera);
  11127. BABYLON.TouchCamera = TouchCamera;
  11128. })(BABYLON || (BABYLON = {}));
  11129. var BABYLON;
  11130. (function (BABYLON) {
  11131. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11132. var ArcRotateCamera = (function (_super) {
  11133. __extends(ArcRotateCamera, _super);
  11134. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11135. var _this = this;
  11136. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11137. this.alpha = alpha;
  11138. this.beta = beta;
  11139. this.radius = radius;
  11140. this.target = target;
  11141. this.inertialAlphaOffset = 0;
  11142. this.inertialBetaOffset = 0;
  11143. this.inertialRadiusOffset = 0;
  11144. this.lowerAlphaLimit = null;
  11145. this.upperAlphaLimit = null;
  11146. this.lowerBetaLimit = 0.01;
  11147. this.upperBetaLimit = Math.PI;
  11148. this.lowerRadiusLimit = null;
  11149. this.upperRadiusLimit = null;
  11150. this.angularSensibilityX = 1000.0;
  11151. this.angularSensibilityY = 1000.0;
  11152. this.wheelPrecision = 3.0;
  11153. this.pinchPrecision = 2.0;
  11154. this.panningSensibility = 50.0;
  11155. this.inertialPanningX = 0;
  11156. this.inertialPanningY = 0;
  11157. this.keysUp = [38];
  11158. this.keysDown = [40];
  11159. this.keysLeft = [37];
  11160. this.keysRight = [39];
  11161. this.zoomOnFactor = 1;
  11162. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11163. this.pinchInwards = true;
  11164. this.allowUpsideDown = true;
  11165. this._keys = [];
  11166. this._viewMatrix = new BABYLON.Matrix();
  11167. this._isRightClick = false;
  11168. this._isCtrlPushed = false;
  11169. this.checkCollisions = false;
  11170. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11171. this._collider = new BABYLON.Collider();
  11172. this._previousPosition = BABYLON.Vector3.Zero();
  11173. this._collisionVelocity = BABYLON.Vector3.Zero();
  11174. this._newPosition = BABYLON.Vector3.Zero();
  11175. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11176. if (collidedMesh === void 0) { collidedMesh = null; }
  11177. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11178. newPosition.multiplyInPlace(_this._collider.radius);
  11179. }
  11180. if (!collidedMesh) {
  11181. _this._previousPosition.copyFrom(_this.position);
  11182. }
  11183. else {
  11184. _this.setPosition(_this.position);
  11185. if (_this.onCollide) {
  11186. _this.onCollide(collidedMesh);
  11187. }
  11188. }
  11189. // Recompute because of constraints
  11190. var cosa = Math.cos(_this.alpha);
  11191. var sina = Math.sin(_this.alpha);
  11192. var cosb = Math.cos(_this.beta);
  11193. var sinb = Math.sin(_this.beta);
  11194. var target = _this._getTargetPosition();
  11195. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11196. _this.position.copyFrom(_this._newPosition);
  11197. var up = _this.upVector;
  11198. if (_this.allowUpsideDown && _this.beta < 0) {
  11199. up = up.clone();
  11200. up = up.negate();
  11201. }
  11202. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11203. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11204. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11205. _this._collisionTriggered = false;
  11206. };
  11207. if (!this.target) {
  11208. this.target = BABYLON.Vector3.Zero();
  11209. }
  11210. this.getViewMatrix();
  11211. }
  11212. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11213. //deprecated angularSensibility support
  11214. get: function () {
  11215. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11216. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11217. },
  11218. //deprecated angularSensibility support
  11219. set: function (value) {
  11220. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11221. this.angularSensibilityX = value;
  11222. this.angularSensibilityY = value;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. ArcRotateCamera.prototype._getTargetPosition = function () {
  11228. return this.target.position || this.target;
  11229. };
  11230. // Cache
  11231. ArcRotateCamera.prototype._initCache = function () {
  11232. _super.prototype._initCache.call(this);
  11233. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11234. this._cache.alpha = undefined;
  11235. this._cache.beta = undefined;
  11236. this._cache.radius = undefined;
  11237. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11238. };
  11239. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11240. if (!ignoreParentClass) {
  11241. _super.prototype._updateCache.call(this);
  11242. }
  11243. this._cache.target.copyFrom(this._getTargetPosition());
  11244. this._cache.alpha = this.alpha;
  11245. this._cache.beta = this.beta;
  11246. this._cache.radius = this.radius;
  11247. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11248. };
  11249. // Synchronized
  11250. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11251. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11252. return false;
  11253. return this._cache.target.equals(this._getTargetPosition())
  11254. && this._cache.alpha === this.alpha
  11255. && this._cache.beta === this.beta
  11256. && this._cache.radius === this.radius
  11257. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11258. };
  11259. // Methods
  11260. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11261. var _this = this;
  11262. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11263. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11264. var previousPinchDistance = 0;
  11265. var pointers = new BABYLON.SmartCollection();
  11266. if (this._attachedElement) {
  11267. return;
  11268. }
  11269. this._attachedElement = element;
  11270. var engine = this.getEngine();
  11271. if (this._onPointerDown === undefined) {
  11272. this._onPointerDown = function (evt) {
  11273. // Manage panning with right click
  11274. _this._isRightClick = evt.button === 2;
  11275. // manage pointers
  11276. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11277. cacheSoloPointer = pointers.item(evt.pointerId);
  11278. if (!noPreventDefault) {
  11279. evt.preventDefault();
  11280. }
  11281. };
  11282. this._onPointerUp = function (evt) {
  11283. cacheSoloPointer = null;
  11284. previousPinchDistance = 0;
  11285. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11286. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11287. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11288. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11289. pointers.empty();
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onContextMenu = function (evt) {
  11295. evt.preventDefault();
  11296. };
  11297. this._onPointerMove = function (evt) {
  11298. if (!noPreventDefault) {
  11299. evt.preventDefault();
  11300. }
  11301. switch (pointers.count) {
  11302. case 1:
  11303. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11304. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11305. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11306. }
  11307. else {
  11308. var offsetX = evt.clientX - cacheSoloPointer.x;
  11309. var offsetY = evt.clientY - cacheSoloPointer.y;
  11310. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11311. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11312. }
  11313. cacheSoloPointer.x = evt.clientX;
  11314. cacheSoloPointer.y = evt.clientY;
  11315. break;
  11316. case 2:
  11317. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11318. pointers.item(evt.pointerId).x = evt.clientX;
  11319. pointers.item(evt.pointerId).y = evt.clientY;
  11320. var direction = _this.pinchInwards ? 1 : -1;
  11321. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11322. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11323. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11324. if (previousPinchDistance === 0) {
  11325. previousPinchDistance = pinchSquaredDistance;
  11326. return;
  11327. }
  11328. if (pinchSquaredDistance !== previousPinchDistance) {
  11329. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11330. previousPinchDistance = pinchSquaredDistance;
  11331. }
  11332. break;
  11333. default:
  11334. if (pointers.item(evt.pointerId)) {
  11335. pointers.item(evt.pointerId).x = evt.clientX;
  11336. pointers.item(evt.pointerId).y = evt.clientY;
  11337. }
  11338. }
  11339. };
  11340. this._onMouseMove = function (evt) {
  11341. if (!engine.isPointerLock) {
  11342. return;
  11343. }
  11344. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11345. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11346. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11347. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11348. if (!noPreventDefault) {
  11349. evt.preventDefault();
  11350. }
  11351. };
  11352. this._wheel = function (event) {
  11353. var delta = 0;
  11354. if (event.wheelDelta) {
  11355. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11356. }
  11357. else if (event.detail) {
  11358. delta = -event.detail / _this.wheelPrecision;
  11359. }
  11360. if (delta)
  11361. _this.inertialRadiusOffset += delta;
  11362. if (event.preventDefault) {
  11363. if (!noPreventDefault) {
  11364. event.preventDefault();
  11365. }
  11366. }
  11367. };
  11368. this._onKeyDown = function (evt) {
  11369. _this._isCtrlPushed = evt.ctrlKey;
  11370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11373. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11374. var index = _this._keys.indexOf(evt.keyCode);
  11375. if (index === -1) {
  11376. _this._keys.push(evt.keyCode);
  11377. }
  11378. if (evt.preventDefault) {
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. }
  11383. }
  11384. };
  11385. this._onKeyUp = function (evt) {
  11386. _this._isCtrlPushed = evt.ctrlKey;
  11387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11390. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11391. var index = _this._keys.indexOf(evt.keyCode);
  11392. if (index >= 0) {
  11393. _this._keys.splice(index, 1);
  11394. }
  11395. if (evt.preventDefault) {
  11396. if (!noPreventDefault) {
  11397. evt.preventDefault();
  11398. }
  11399. }
  11400. }
  11401. };
  11402. this._onLostFocus = function () {
  11403. _this._keys = [];
  11404. pointers.empty();
  11405. previousPinchDistance = 0;
  11406. cacheSoloPointer = null;
  11407. };
  11408. this._onGestureStart = function (e) {
  11409. if (window.MSGesture === undefined) {
  11410. return;
  11411. }
  11412. if (!_this._MSGestureHandler) {
  11413. _this._MSGestureHandler = new MSGesture();
  11414. _this._MSGestureHandler.target = element;
  11415. }
  11416. _this._MSGestureHandler.addPointer(e.pointerId);
  11417. };
  11418. this._onGesture = function (e) {
  11419. _this.radius *= e.scale;
  11420. if (e.preventDefault) {
  11421. if (!noPreventDefault) {
  11422. e.stopPropagation();
  11423. e.preventDefault();
  11424. }
  11425. }
  11426. };
  11427. this._reset = function () {
  11428. _this._keys = [];
  11429. _this.inertialAlphaOffset = 0;
  11430. _this.inertialBetaOffset = 0;
  11431. _this.inertialRadiusOffset = 0;
  11432. pointers.empty();
  11433. previousPinchDistance = 0;
  11434. cacheSoloPointer = null;
  11435. };
  11436. }
  11437. if (!useCtrlForPanning) {
  11438. element.addEventListener("contextmenu", this._onContextMenu, false);
  11439. }
  11440. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11441. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11442. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11443. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11444. element.addEventListener("mousemove", this._onMouseMove, false);
  11445. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11446. element.addEventListener("MSGestureChange", this._onGesture, false);
  11447. element.addEventListener('mousewheel', this._wheel, false);
  11448. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11449. BABYLON.Tools.RegisterTopRootEvents([
  11450. { name: "keydown", handler: this._onKeyDown },
  11451. { name: "keyup", handler: this._onKeyUp },
  11452. { name: "blur", handler: this._onLostFocus }
  11453. ]);
  11454. };
  11455. ArcRotateCamera.prototype.detachControl = function (element) {
  11456. if (this._attachedElement !== element) {
  11457. return;
  11458. }
  11459. element.removeEventListener("contextmenu", this._onContextMenu);
  11460. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11461. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11462. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11463. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11464. element.removeEventListener("mousemove", this._onMouseMove);
  11465. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11466. element.removeEventListener("MSGestureChange", this._onGesture);
  11467. element.removeEventListener('mousewheel', this._wheel);
  11468. element.removeEventListener('DOMMouseScroll', this._wheel);
  11469. BABYLON.Tools.UnregisterTopRootEvents([
  11470. { name: "keydown", handler: this._onKeyDown },
  11471. { name: "keyup", handler: this._onKeyUp },
  11472. { name: "blur", handler: this._onLostFocus }
  11473. ]);
  11474. this._MSGestureHandler = null;
  11475. this._attachedElement = null;
  11476. if (this._reset) {
  11477. this._reset();
  11478. }
  11479. };
  11480. ArcRotateCamera.prototype._checkInputs = function () {
  11481. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11482. if (this._collisionTriggered) {
  11483. return;
  11484. }
  11485. // Keyboard
  11486. for (var index = 0; index < this._keys.length; index++) {
  11487. var keyCode = this._keys[index];
  11488. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11489. this.inertialAlphaOffset -= 0.01;
  11490. }
  11491. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11492. this.inertialBetaOffset -= 0.01;
  11493. }
  11494. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11495. this.inertialAlphaOffset += 0.01;
  11496. }
  11497. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11498. this.inertialBetaOffset += 0.01;
  11499. }
  11500. }
  11501. // Inertia
  11502. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11503. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11504. this.beta += this.inertialBetaOffset;
  11505. this.radius -= this.inertialRadiusOffset;
  11506. this.inertialAlphaOffset *= this.inertia;
  11507. this.inertialBetaOffset *= this.inertia;
  11508. this.inertialRadiusOffset *= this.inertia;
  11509. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11510. this.inertialAlphaOffset = 0;
  11511. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11512. this.inertialBetaOffset = 0;
  11513. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11514. this.inertialRadiusOffset = 0;
  11515. }
  11516. // Panning inertia
  11517. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11518. if (!this._localDirection) {
  11519. this._localDirection = BABYLON.Vector3.Zero();
  11520. this._transformedDirection = BABYLON.Vector3.Zero();
  11521. }
  11522. this.inertialPanningX *= this.inertia;
  11523. this.inertialPanningY *= this.inertia;
  11524. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11525. this.inertialPanningX = 0;
  11526. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11527. this.inertialPanningY = 0;
  11528. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11529. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11530. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11531. this.target.addInPlace(this._transformedDirection);
  11532. }
  11533. // Limits
  11534. this._checkLimits();
  11535. _super.prototype._checkInputs.call(this);
  11536. };
  11537. ArcRotateCamera.prototype._checkLimits = function () {
  11538. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11539. if (this.allowUpsideDown && this.beta > Math.PI) {
  11540. this.beta = this.beta - (2 * Math.PI);
  11541. }
  11542. }
  11543. else {
  11544. if (this.beta < this.lowerBetaLimit) {
  11545. this.beta = this.lowerBetaLimit;
  11546. }
  11547. }
  11548. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11549. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11550. this.beta = this.beta + (2 * Math.PI);
  11551. }
  11552. }
  11553. else {
  11554. if (this.beta > this.upperBetaLimit) {
  11555. this.beta = this.upperBetaLimit;
  11556. }
  11557. }
  11558. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11559. this.alpha = this.lowerAlphaLimit;
  11560. }
  11561. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11562. this.alpha = this.upperAlphaLimit;
  11563. }
  11564. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11565. this.radius = this.lowerRadiusLimit;
  11566. }
  11567. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11568. this.radius = this.upperRadiusLimit;
  11569. }
  11570. };
  11571. ArcRotateCamera.prototype.setPosition = function (position) {
  11572. if (this.position.equals(position)) {
  11573. return;
  11574. }
  11575. var radiusv3 = position.subtract(this._getTargetPosition());
  11576. this.radius = radiusv3.length();
  11577. // Alpha
  11578. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11579. if (radiusv3.z < 0) {
  11580. this.alpha = 2 * Math.PI - this.alpha;
  11581. }
  11582. // Beta
  11583. this.beta = Math.acos(radiusv3.y / this.radius);
  11584. this._checkLimits();
  11585. };
  11586. ArcRotateCamera.prototype.setTarget = function (target) {
  11587. this.target = target;
  11588. };
  11589. ArcRotateCamera.prototype._getViewMatrix = function () {
  11590. // Compute
  11591. var cosa = Math.cos(this.alpha);
  11592. var sina = Math.sin(this.alpha);
  11593. var cosb = Math.cos(this.beta);
  11594. var sinb = Math.sin(this.beta);
  11595. var target = this._getTargetPosition();
  11596. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11597. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11598. this._collider.radius = this.collisionRadius;
  11599. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11600. this._collisionTriggered = true;
  11601. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11602. }
  11603. else {
  11604. this.position.copyFrom(this._newPosition);
  11605. var up = this.upVector;
  11606. if (this.allowUpsideDown && this.beta < 0) {
  11607. up = up.clone();
  11608. up = up.negate();
  11609. }
  11610. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11611. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11612. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11613. }
  11614. return this._viewMatrix;
  11615. };
  11616. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11617. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11618. meshes = meshes || this.getScene().meshes;
  11619. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11620. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11621. this.radius = distance * this.zoomOnFactor;
  11622. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11623. };
  11624. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11625. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11626. var meshesOrMinMaxVector;
  11627. var distance;
  11628. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11629. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11630. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11631. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11632. }
  11633. else {
  11634. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11635. distance = meshesOrMinMaxVectorAndDistance.distance;
  11636. }
  11637. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11638. if (!doNotUpdateMaxZ) {
  11639. this.maxZ = distance * 2;
  11640. }
  11641. };
  11642. /**
  11643. * @override
  11644. * Override Camera.createRigCamera
  11645. */
  11646. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11647. switch (this.cameraRigMode) {
  11648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11652. case BABYLON.Camera.RIG_MODE_VR:
  11653. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11654. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11655. }
  11656. return null;
  11657. };
  11658. /**
  11659. * @override
  11660. * Override Camera._updateRigCameras
  11661. */
  11662. ArcRotateCamera.prototype._updateRigCameras = function () {
  11663. switch (this.cameraRigMode) {
  11664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11668. case BABYLON.Camera.RIG_MODE_VR:
  11669. var camLeft = this._rigCameras[0];
  11670. var camRight = this._rigCameras[1];
  11671. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11672. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11673. camLeft.beta = camRight.beta = this.beta;
  11674. camLeft.radius = camRight.radius = this.radius;
  11675. break;
  11676. }
  11677. _super.prototype._updateRigCameras.call(this);
  11678. };
  11679. ArcRotateCamera.prototype.serialize = function () {
  11680. var serializationObject = _super.prototype.serialize.call(this);
  11681. if (this.target instanceof BABYLON.Vector3) {
  11682. serializationObject.target = this.target.asArray();
  11683. }
  11684. if (this.target && this.target.id) {
  11685. serializationObject.lockedTargetId = this.target.id;
  11686. }
  11687. serializationObject.checkCollisions = this.checkCollisions;
  11688. serializationObject.alpha = this.alpha;
  11689. serializationObject.beta = this.beta;
  11690. serializationObject.radius = this.radius;
  11691. return serializationObject;
  11692. };
  11693. return ArcRotateCamera;
  11694. })(BABYLON.TargetCamera);
  11695. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11696. })(BABYLON || (BABYLON = {}));
  11697. var BABYLON;
  11698. (function (BABYLON) {
  11699. var RenderingManager = (function () {
  11700. function RenderingManager(scene) {
  11701. this._renderingGroups = new Array();
  11702. this._scene = scene;
  11703. }
  11704. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11705. if (this._scene._activeParticleSystems.length === 0) {
  11706. return;
  11707. }
  11708. // Particles
  11709. var activeCamera = this._scene.activeCamera;
  11710. var beforeParticlesDate = BABYLON.Tools.Now;
  11711. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11712. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11713. if (particleSystem.renderingGroupId !== index) {
  11714. continue;
  11715. }
  11716. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11717. continue;
  11718. }
  11719. this._clearDepthBuffer();
  11720. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11721. this._scene._activeParticles += particleSystem.render();
  11722. }
  11723. }
  11724. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11725. };
  11726. RenderingManager.prototype._renderSprites = function (index) {
  11727. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11728. return;
  11729. }
  11730. // Sprites
  11731. var activeCamera = this._scene.activeCamera;
  11732. var beforeSpritessDate = BABYLON.Tools.Now;
  11733. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11734. var spriteManager = this._scene.spriteManagers[id];
  11735. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11736. this._clearDepthBuffer();
  11737. spriteManager.render();
  11738. }
  11739. }
  11740. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11741. };
  11742. RenderingManager.prototype._clearDepthBuffer = function () {
  11743. if (this._depthBufferAlreadyCleaned) {
  11744. return;
  11745. }
  11746. this._scene.getEngine().clear(0, false, true);
  11747. this._depthBufferAlreadyCleaned = true;
  11748. };
  11749. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11750. if (this._currentRenderSprites) {
  11751. this._renderSprites(this._currentIndex);
  11752. }
  11753. if (this._currentRenderParticles) {
  11754. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11755. }
  11756. };
  11757. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11758. this._currentActiveMeshes = activeMeshes;
  11759. this._currentRenderParticles = renderParticles;
  11760. this._currentRenderSprites = renderSprites;
  11761. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11762. this._depthBufferAlreadyCleaned = false;
  11763. var renderingGroup = this._renderingGroups[index];
  11764. var needToStepBack = false;
  11765. this._currentIndex = index;
  11766. if (renderingGroup) {
  11767. this._clearDepthBuffer();
  11768. if (!renderingGroup.onBeforeTransparentRendering) {
  11769. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11770. }
  11771. if (!renderingGroup.render(customRenderFunction)) {
  11772. this._renderingGroups.splice(index, 1);
  11773. needToStepBack = true;
  11774. this._renderSpritesAndParticles();
  11775. }
  11776. }
  11777. else {
  11778. this._renderSpritesAndParticles();
  11779. }
  11780. if (needToStepBack) {
  11781. index--;
  11782. }
  11783. }
  11784. };
  11785. RenderingManager.prototype.reset = function () {
  11786. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11787. if (renderingGroup) {
  11788. renderingGroup.prepare();
  11789. }
  11790. });
  11791. };
  11792. RenderingManager.prototype.dispatch = function (subMesh) {
  11793. var mesh = subMesh.getMesh();
  11794. var renderingGroupId = mesh.renderingGroupId || 0;
  11795. if (!this._renderingGroups[renderingGroupId]) {
  11796. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11797. }
  11798. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11799. };
  11800. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11801. return RenderingManager;
  11802. })();
  11803. BABYLON.RenderingManager = RenderingManager;
  11804. })(BABYLON || (BABYLON = {}));
  11805. var BABYLON;
  11806. (function (BABYLON) {
  11807. var RenderingGroup = (function () {
  11808. function RenderingGroup(index, scene) {
  11809. this.index = index;
  11810. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11811. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11812. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11813. this._scene = scene;
  11814. }
  11815. RenderingGroup.prototype.render = function (customRenderFunction) {
  11816. if (customRenderFunction) {
  11817. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11818. return true;
  11819. }
  11820. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11821. if (this.onBeforeTransparentRendering) {
  11822. this.onBeforeTransparentRendering();
  11823. }
  11824. return false;
  11825. }
  11826. var engine = this._scene.getEngine();
  11827. // Opaque
  11828. var subIndex;
  11829. var submesh;
  11830. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11831. submesh = this._opaqueSubMeshes.data[subIndex];
  11832. submesh.render(false);
  11833. }
  11834. // Alpha test
  11835. engine.setAlphaTesting(true);
  11836. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11837. submesh = this._alphaTestSubMeshes.data[subIndex];
  11838. submesh.render(false);
  11839. }
  11840. engine.setAlphaTesting(false);
  11841. if (this.onBeforeTransparentRendering) {
  11842. this.onBeforeTransparentRendering();
  11843. }
  11844. // Transparent
  11845. if (this._transparentSubMeshes.length) {
  11846. // Sorting
  11847. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11848. submesh = this._transparentSubMeshes.data[subIndex];
  11849. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11850. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11851. }
  11852. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11853. sortedArray.sort(function (a, b) {
  11854. // Alpha index first
  11855. if (a._alphaIndex > b._alphaIndex) {
  11856. return 1;
  11857. }
  11858. if (a._alphaIndex < b._alphaIndex) {
  11859. return -1;
  11860. }
  11861. // Then distance to camera
  11862. if (a._distanceToCamera < b._distanceToCamera) {
  11863. return 1;
  11864. }
  11865. if (a._distanceToCamera > b._distanceToCamera) {
  11866. return -1;
  11867. }
  11868. return 0;
  11869. });
  11870. // Rendering
  11871. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11872. submesh = sortedArray[subIndex];
  11873. submesh.render(true);
  11874. }
  11875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11876. }
  11877. return true;
  11878. };
  11879. RenderingGroup.prototype.prepare = function () {
  11880. this._opaqueSubMeshes.reset();
  11881. this._transparentSubMeshes.reset();
  11882. this._alphaTestSubMeshes.reset();
  11883. };
  11884. RenderingGroup.prototype.dispatch = function (subMesh) {
  11885. var material = subMesh.getMaterial();
  11886. var mesh = subMesh.getMesh();
  11887. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11888. this._transparentSubMeshes.push(subMesh);
  11889. }
  11890. else if (material.needAlphaTesting()) {
  11891. this._alphaTestSubMeshes.push(subMesh);
  11892. }
  11893. else {
  11894. this._opaqueSubMeshes.push(subMesh); // Opaque
  11895. }
  11896. };
  11897. return RenderingGroup;
  11898. })();
  11899. BABYLON.RenderingGroup = RenderingGroup;
  11900. })(BABYLON || (BABYLON = {}));
  11901. var BABYLON;
  11902. (function (BABYLON) {
  11903. /**
  11904. * Represents a scene to be rendered by the engine.
  11905. * @see http://doc.babylonjs.com/page.php?p=21911
  11906. */
  11907. var Scene = (function () {
  11908. /**
  11909. * @constructor
  11910. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11911. */
  11912. function Scene(engine) {
  11913. // Members
  11914. this.autoClear = true;
  11915. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11916. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11917. this.forceWireframe = false;
  11918. this.forcePointsCloud = false;
  11919. this.forceShowBoundingBoxes = false;
  11920. this.animationsEnabled = true;
  11921. this.constantlyUpdateMeshUnderPointer = false;
  11922. 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
  11923. // Fog
  11924. /**
  11925. * is fog enabled on this scene.
  11926. * @type {boolean}
  11927. */
  11928. this.fogEnabled = true;
  11929. this.fogMode = Scene.FOGMODE_NONE;
  11930. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11931. this.fogDensity = 0.1;
  11932. this.fogStart = 0;
  11933. this.fogEnd = 1000.0;
  11934. // Lights
  11935. /**
  11936. * is shadow enabled on this scene.
  11937. * @type {boolean}
  11938. */
  11939. this.shadowsEnabled = true;
  11940. /**
  11941. * is light enabled on this scene.
  11942. * @type {boolean}
  11943. */
  11944. this.lightsEnabled = true;
  11945. /**
  11946. * All of the lights added to this scene.
  11947. * @see BABYLON.Light
  11948. * @type {BABYLON.Light[]}
  11949. */
  11950. this.lights = new Array();
  11951. // Cameras
  11952. /**
  11953. * All of the cameras added to this scene.
  11954. * @see BABYLON.Camera
  11955. * @type {BABYLON.Camera[]}
  11956. */
  11957. this.cameras = new Array();
  11958. this.activeCameras = new Array();
  11959. // Meshes
  11960. /**
  11961. * All of the (abstract) meshes added to this scene.
  11962. * @see BABYLON.AbstractMesh
  11963. * @type {BABYLON.AbstractMesh[]}
  11964. */
  11965. this.meshes = new Array();
  11966. // Geometries
  11967. this._geometries = new Array();
  11968. this.materials = new Array();
  11969. this.multiMaterials = new Array();
  11970. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11971. // Textures
  11972. this.texturesEnabled = true;
  11973. this.textures = new Array();
  11974. // Particles
  11975. this.particlesEnabled = true;
  11976. this.particleSystems = new Array();
  11977. // Sprites
  11978. this.spritesEnabled = true;
  11979. this.spriteManagers = new Array();
  11980. // Layers
  11981. this.layers = new Array();
  11982. // Skeletons
  11983. this.skeletonsEnabled = true;
  11984. this.skeletons = new Array();
  11985. // Lens flares
  11986. this.lensFlaresEnabled = true;
  11987. this.lensFlareSystems = new Array();
  11988. // Collisions
  11989. this.collisionsEnabled = true;
  11990. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11991. // Postprocesses
  11992. this.postProcessesEnabled = true;
  11993. // Customs render targets
  11994. this.renderTargetsEnabled = true;
  11995. this.dumpNextRenderTargets = false;
  11996. this.customRenderTargets = new Array();
  11997. // Imported meshes
  11998. this.importedMeshesFiles = new Array();
  11999. // Probes
  12000. this.probesEnabled = true;
  12001. this.reflectionProbes = new Array();
  12002. this._actionManagers = new Array();
  12003. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12004. // Procedural textures
  12005. this.proceduralTexturesEnabled = true;
  12006. this._proceduralTextures = new Array();
  12007. this.soundTracks = new Array();
  12008. this._audioEnabled = true;
  12009. this._headphone = false;
  12010. this._totalVertices = 0;
  12011. this._activeIndices = 0;
  12012. this._activeParticles = 0;
  12013. this._lastFrameDuration = 0;
  12014. this._evaluateActiveMeshesDuration = 0;
  12015. this._renderTargetsDuration = 0;
  12016. this._particlesDuration = 0;
  12017. this._renderDuration = 0;
  12018. this._spritesDuration = 0;
  12019. this._animationRatio = 0;
  12020. this._renderId = 0;
  12021. this._executeWhenReadyTimeoutId = -1;
  12022. this._toBeDisposed = new BABYLON.SmartArray(256);
  12023. this._onReadyCallbacks = new Array();
  12024. this._pendingData = []; //ANY
  12025. this._onBeforeRenderCallbacks = new Array();
  12026. this._onAfterRenderCallbacks = new Array();
  12027. this._activeMeshes = new BABYLON.SmartArray(256);
  12028. this._processedMaterials = new BABYLON.SmartArray(256);
  12029. this._renderTargets = new BABYLON.SmartArray(256);
  12030. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12031. this._activeSkeletons = new BABYLON.SmartArray(32);
  12032. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12033. this._activeBones = 0;
  12034. this._activeAnimatables = new Array();
  12035. this._transformMatrix = BABYLON.Matrix.Zero();
  12036. this._edgesRenderers = new BABYLON.SmartArray(16);
  12037. this._uniqueIdCounter = 0;
  12038. this._engine = engine;
  12039. engine.scenes.push(this);
  12040. this._renderingManager = new BABYLON.RenderingManager(this);
  12041. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12042. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12043. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12044. if (BABYLON.OutlineRenderer) {
  12045. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12046. }
  12047. this.attachControl();
  12048. this._debugLayer = new BABYLON.DebugLayer(this);
  12049. if (BABYLON.SoundTrack) {
  12050. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12051. }
  12052. //simplification queue
  12053. if (BABYLON.SimplificationQueue) {
  12054. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12055. }
  12056. //collision coordinator initialization. For now legacy per default.
  12057. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12058. }
  12059. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12060. get: function () {
  12061. return Scene._FOGMODE_NONE;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12067. get: function () {
  12068. return Scene._FOGMODE_EXP;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12074. get: function () {
  12075. return Scene._FOGMODE_EXP2;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12081. get: function () {
  12082. return Scene._FOGMODE_LINEAR;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(Scene.prototype, "debugLayer", {
  12088. // Properties
  12089. get: function () {
  12090. return this._debugLayer;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12096. get: function () {
  12097. return this._workerCollisions;
  12098. },
  12099. set: function (enabled) {
  12100. enabled = (enabled && !!Worker);
  12101. this._workerCollisions = enabled;
  12102. if (this.collisionCoordinator) {
  12103. this.collisionCoordinator.destroy();
  12104. }
  12105. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12106. this.collisionCoordinator.init(this);
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12112. get: function () {
  12113. return this._selectionOctree;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12119. /**
  12120. * The mesh that is currently under the pointer.
  12121. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12122. */
  12123. get: function () {
  12124. return this._meshUnderPointer;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. Object.defineProperty(Scene.prototype, "pointerX", {
  12130. /**
  12131. * Current on-screen X position of the pointer
  12132. * @return {number} X position of the pointer
  12133. */
  12134. get: function () {
  12135. return this._pointerX;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "pointerY", {
  12141. /**
  12142. * Current on-screen Y position of the pointer
  12143. * @return {number} Y position of the pointer
  12144. */
  12145. get: function () {
  12146. return this._pointerY;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Scene.prototype.getCachedMaterial = function () {
  12152. return this._cachedMaterial;
  12153. };
  12154. Scene.prototype.getBoundingBoxRenderer = function () {
  12155. return this._boundingBoxRenderer;
  12156. };
  12157. Scene.prototype.getOutlineRenderer = function () {
  12158. return this._outlineRenderer;
  12159. };
  12160. Scene.prototype.getEngine = function () {
  12161. return this._engine;
  12162. };
  12163. Scene.prototype.getTotalVertices = function () {
  12164. return this._totalVertices;
  12165. };
  12166. Scene.prototype.getActiveIndices = function () {
  12167. return this._activeIndices;
  12168. };
  12169. Scene.prototype.getActiveParticles = function () {
  12170. return this._activeParticles;
  12171. };
  12172. Scene.prototype.getActiveBones = function () {
  12173. return this._activeBones;
  12174. };
  12175. // Stats
  12176. Scene.prototype.getLastFrameDuration = function () {
  12177. return this._lastFrameDuration;
  12178. };
  12179. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12180. return this._evaluateActiveMeshesDuration;
  12181. };
  12182. Scene.prototype.getActiveMeshes = function () {
  12183. return this._activeMeshes;
  12184. };
  12185. Scene.prototype.getRenderTargetsDuration = function () {
  12186. return this._renderTargetsDuration;
  12187. };
  12188. Scene.prototype.getRenderDuration = function () {
  12189. return this._renderDuration;
  12190. };
  12191. Scene.prototype.getParticlesDuration = function () {
  12192. return this._particlesDuration;
  12193. };
  12194. Scene.prototype.getSpritesDuration = function () {
  12195. return this._spritesDuration;
  12196. };
  12197. Scene.prototype.getAnimationRatio = function () {
  12198. return this._animationRatio;
  12199. };
  12200. Scene.prototype.getRenderId = function () {
  12201. return this._renderId;
  12202. };
  12203. Scene.prototype.incrementRenderId = function () {
  12204. this._renderId++;
  12205. };
  12206. Scene.prototype._updatePointerPosition = function (evt) {
  12207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12208. this._pointerX = evt.clientX - canvasRect.left;
  12209. this._pointerY = evt.clientY - canvasRect.top;
  12210. if (this.cameraToUseForPointers) {
  12211. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12212. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12213. }
  12214. };
  12215. // Pointers handling
  12216. Scene.prototype.attachControl = function () {
  12217. var _this = this;
  12218. var spritePredicate = function (sprite) {
  12219. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12220. };
  12221. this._onPointerMove = function (evt) {
  12222. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12223. return;
  12224. }
  12225. var canvas = _this._engine.getRenderingCanvas();
  12226. _this._updatePointerPosition(evt);
  12227. // Meshes
  12228. 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);
  12229. if (pickResult.hit && pickResult.pickedMesh) {
  12230. _this._meshUnderPointer = pickResult.pickedMesh;
  12231. _this.setPointerOverMesh(pickResult.pickedMesh);
  12232. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12233. canvas.style.cursor = "pointer";
  12234. }
  12235. else {
  12236. canvas.style.cursor = "";
  12237. }
  12238. }
  12239. else {
  12240. // Sprites
  12241. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12242. if (pickResult.hit && pickResult.pickedSprite) {
  12243. canvas.style.cursor = "pointer";
  12244. }
  12245. else {
  12246. // Restore pointer
  12247. _this.setPointerOverMesh(null);
  12248. canvas.style.cursor = "";
  12249. _this._meshUnderPointer = null;
  12250. }
  12251. }
  12252. if (_this.onPointerMove) {
  12253. _this.onPointerMove(evt, pickResult);
  12254. }
  12255. };
  12256. this._onPointerDown = function (evt) {
  12257. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12258. return;
  12259. }
  12260. _this._updatePointerPosition(evt);
  12261. var predicate = null;
  12262. // Meshes
  12263. if (!_this.onPointerDown) {
  12264. predicate = function (mesh) {
  12265. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12266. };
  12267. }
  12268. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12269. if (pickResult.hit && pickResult.pickedMesh) {
  12270. if (pickResult.pickedMesh.actionManager) {
  12271. switch (evt.button) {
  12272. case 0:
  12273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12274. break;
  12275. case 1:
  12276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12277. break;
  12278. case 2:
  12279. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12280. break;
  12281. }
  12282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12283. }
  12284. }
  12285. if (_this.onPointerDown) {
  12286. _this.onPointerDown(evt, pickResult);
  12287. }
  12288. // Sprites
  12289. if (_this.spriteManagers.length > 0) {
  12290. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12291. if (pickResult.hit && pickResult.pickedSprite) {
  12292. if (pickResult.pickedSprite.actionManager) {
  12293. switch (evt.button) {
  12294. case 0:
  12295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12296. break;
  12297. case 1:
  12298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12299. break;
  12300. case 2:
  12301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12302. break;
  12303. }
  12304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12305. }
  12306. }
  12307. }
  12308. };
  12309. this._onPointerUp = function (evt) {
  12310. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12311. return;
  12312. }
  12313. var predicate = null;
  12314. _this._updatePointerPosition(evt);
  12315. if (!_this.onPointerUp) {
  12316. predicate = function (mesh) {
  12317. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12318. };
  12319. }
  12320. // Meshes
  12321. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12322. if (pickResult.hit && pickResult.pickedMesh) {
  12323. if (pickResult.pickedMesh.actionManager) {
  12324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12325. }
  12326. }
  12327. if (_this.onPointerUp) {
  12328. _this.onPointerUp(evt, pickResult);
  12329. }
  12330. // Sprites
  12331. if (_this.spriteManagers.length > 0) {
  12332. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12333. if (pickResult.hit && pickResult.pickedSprite) {
  12334. if (pickResult.pickedSprite.actionManager) {
  12335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12336. }
  12337. }
  12338. }
  12339. };
  12340. this._onKeyDown = function (evt) {
  12341. if (_this.actionManager) {
  12342. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12343. }
  12344. };
  12345. this._onKeyUp = function (evt) {
  12346. if (_this.actionManager) {
  12347. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12348. }
  12349. };
  12350. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12351. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12352. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12353. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12354. // Wheel
  12355. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12356. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12357. BABYLON.Tools.RegisterTopRootEvents([
  12358. { name: "keydown", handler: this._onKeyDown },
  12359. { name: "keyup", handler: this._onKeyUp }
  12360. ]);
  12361. };
  12362. Scene.prototype.detachControl = function () {
  12363. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12364. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12365. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12366. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12367. // Wheel
  12368. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12369. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12370. BABYLON.Tools.UnregisterTopRootEvents([
  12371. { name: "keydown", handler: this._onKeyDown },
  12372. { name: "keyup", handler: this._onKeyUp }
  12373. ]);
  12374. };
  12375. // Ready
  12376. Scene.prototype.isReady = function () {
  12377. if (this._pendingData.length > 0) {
  12378. return false;
  12379. }
  12380. var index;
  12381. for (index = 0; index < this._geometries.length; index++) {
  12382. var geometry = this._geometries[index];
  12383. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12384. return false;
  12385. }
  12386. }
  12387. for (index = 0; index < this.meshes.length; index++) {
  12388. var mesh = this.meshes[index];
  12389. if (!mesh.isReady()) {
  12390. return false;
  12391. }
  12392. var mat = mesh.material;
  12393. if (mat) {
  12394. if (!mat.isReady(mesh)) {
  12395. return false;
  12396. }
  12397. }
  12398. }
  12399. return true;
  12400. };
  12401. Scene.prototype.resetCachedMaterial = function () {
  12402. this._cachedMaterial = null;
  12403. };
  12404. Scene.prototype.registerBeforeRender = function (func) {
  12405. this._onBeforeRenderCallbacks.push(func);
  12406. };
  12407. Scene.prototype.unregisterBeforeRender = function (func) {
  12408. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12409. if (index > -1) {
  12410. this._onBeforeRenderCallbacks.splice(index, 1);
  12411. }
  12412. };
  12413. Scene.prototype.registerAfterRender = function (func) {
  12414. this._onAfterRenderCallbacks.push(func);
  12415. };
  12416. Scene.prototype.unregisterAfterRender = function (func) {
  12417. var index = this._onAfterRenderCallbacks.indexOf(func);
  12418. if (index > -1) {
  12419. this._onAfterRenderCallbacks.splice(index, 1);
  12420. }
  12421. };
  12422. Scene.prototype._addPendingData = function (data) {
  12423. this._pendingData.push(data);
  12424. };
  12425. Scene.prototype._removePendingData = function (data) {
  12426. var index = this._pendingData.indexOf(data);
  12427. if (index !== -1) {
  12428. this._pendingData.splice(index, 1);
  12429. }
  12430. };
  12431. Scene.prototype.getWaitingItemsCount = function () {
  12432. return this._pendingData.length;
  12433. };
  12434. /**
  12435. * Registers a function to be executed when the scene is ready.
  12436. * @param {Function} func - the function to be executed.
  12437. */
  12438. Scene.prototype.executeWhenReady = function (func) {
  12439. var _this = this;
  12440. this._onReadyCallbacks.push(func);
  12441. if (this._executeWhenReadyTimeoutId !== -1) {
  12442. return;
  12443. }
  12444. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12445. _this._checkIsReady();
  12446. }, 150);
  12447. };
  12448. Scene.prototype._checkIsReady = function () {
  12449. var _this = this;
  12450. if (this.isReady()) {
  12451. this._onReadyCallbacks.forEach(function (func) {
  12452. func();
  12453. });
  12454. this._onReadyCallbacks = [];
  12455. this._executeWhenReadyTimeoutId = -1;
  12456. return;
  12457. }
  12458. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12459. _this._checkIsReady();
  12460. }, 150);
  12461. };
  12462. // Animations
  12463. /**
  12464. * Will start the animation sequence of a given target
  12465. * @param target - the target
  12466. * @param {number} from - from which frame should animation start
  12467. * @param {number} to - till which frame should animation run.
  12468. * @param {boolean} [loop] - should the animation loop
  12469. * @param {number} [speedRatio] - the speed in which to run the animation
  12470. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12471. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12472. * @return {BABYLON.Animatable} the animatable object created for this animation
  12473. * @see BABYLON.Animatable
  12474. * @see http://doc.babylonjs.com/page.php?p=22081
  12475. */
  12476. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12477. if (speedRatio === void 0) { speedRatio = 1.0; }
  12478. this.stopAnimation(target);
  12479. if (!animatable) {
  12480. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12481. }
  12482. // Local animations
  12483. if (target.animations) {
  12484. animatable.appendAnimations(target, target.animations);
  12485. }
  12486. // Children animations
  12487. if (target.getAnimatables) {
  12488. var animatables = target.getAnimatables();
  12489. for (var index = 0; index < animatables.length; index++) {
  12490. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12491. }
  12492. }
  12493. return animatable;
  12494. };
  12495. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12496. if (speedRatio === undefined) {
  12497. speedRatio = 1.0;
  12498. }
  12499. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12500. return animatable;
  12501. };
  12502. Scene.prototype.getAnimatableByTarget = function (target) {
  12503. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12504. if (this._activeAnimatables[index].target === target) {
  12505. return this._activeAnimatables[index];
  12506. }
  12507. }
  12508. return null;
  12509. };
  12510. /**
  12511. * Will stop the animation of the given target
  12512. * @param target - the target
  12513. * @see beginAnimation
  12514. */
  12515. Scene.prototype.stopAnimation = function (target) {
  12516. var animatable = this.getAnimatableByTarget(target);
  12517. if (animatable) {
  12518. animatable.stop();
  12519. }
  12520. };
  12521. Scene.prototype._animate = function () {
  12522. if (!this.animationsEnabled) {
  12523. return;
  12524. }
  12525. if (!this._animationStartDate) {
  12526. this._animationStartDate = BABYLON.Tools.Now;
  12527. }
  12528. // Getting time
  12529. var now = BABYLON.Tools.Now;
  12530. var delay = now - this._animationStartDate;
  12531. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12532. this._activeAnimatables[index]._animate(delay);
  12533. }
  12534. };
  12535. // Matrix
  12536. Scene.prototype.getViewMatrix = function () {
  12537. return this._viewMatrix;
  12538. };
  12539. Scene.prototype.getProjectionMatrix = function () {
  12540. return this._projectionMatrix;
  12541. };
  12542. Scene.prototype.getTransformMatrix = function () {
  12543. return this._transformMatrix;
  12544. };
  12545. Scene.prototype.setTransformMatrix = function (view, projection) {
  12546. this._viewMatrix = view;
  12547. this._projectionMatrix = projection;
  12548. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12549. };
  12550. // Methods
  12551. Scene.prototype.addMesh = function (newMesh) {
  12552. newMesh.uniqueId = this._uniqueIdCounter++;
  12553. var position = this.meshes.push(newMesh);
  12554. //notify the collision coordinator
  12555. this.collisionCoordinator.onMeshAdded(newMesh);
  12556. if (this.onNewMeshAdded) {
  12557. this.onNewMeshAdded(newMesh, position, this);
  12558. }
  12559. };
  12560. Scene.prototype.removeMesh = function (toRemove) {
  12561. var index = this.meshes.indexOf(toRemove);
  12562. if (index !== -1) {
  12563. // Remove from the scene if mesh found
  12564. this.meshes.splice(index, 1);
  12565. }
  12566. //notify the collision coordinator
  12567. this.collisionCoordinator.onMeshRemoved(toRemove);
  12568. if (this.onMeshRemoved) {
  12569. this.onMeshRemoved(toRemove);
  12570. }
  12571. return index;
  12572. };
  12573. Scene.prototype.removeSkeleton = function (toRemove) {
  12574. var index = this.skeletons.indexOf(toRemove);
  12575. if (index !== -1) {
  12576. // Remove from the scene if mesh found
  12577. this.skeletons.splice(index, 1);
  12578. }
  12579. return index;
  12580. };
  12581. Scene.prototype.removeLight = function (toRemove) {
  12582. var index = this.lights.indexOf(toRemove);
  12583. if (index !== -1) {
  12584. // Remove from the scene if mesh found
  12585. this.lights.splice(index, 1);
  12586. }
  12587. if (this.onLightRemoved) {
  12588. this.onLightRemoved(toRemove);
  12589. }
  12590. return index;
  12591. };
  12592. Scene.prototype.removeCamera = function (toRemove) {
  12593. var index = this.cameras.indexOf(toRemove);
  12594. if (index !== -1) {
  12595. // Remove from the scene if mesh found
  12596. this.cameras.splice(index, 1);
  12597. }
  12598. // Remove from activeCameras
  12599. var index2 = this.activeCameras.indexOf(toRemove);
  12600. if (index2 !== -1) {
  12601. // Remove from the scene if mesh found
  12602. this.activeCameras.splice(index2, 1);
  12603. }
  12604. // Reset the activeCamera
  12605. if (this.activeCamera === toRemove) {
  12606. if (this.cameras.length > 0) {
  12607. this.activeCamera = this.cameras[0];
  12608. }
  12609. else {
  12610. this.activeCamera = null;
  12611. }
  12612. }
  12613. if (this.onCameraRemoved) {
  12614. this.onCameraRemoved(toRemove);
  12615. }
  12616. return index;
  12617. };
  12618. Scene.prototype.addLight = function (newLight) {
  12619. newLight.uniqueId = this._uniqueIdCounter++;
  12620. var position = this.lights.push(newLight);
  12621. if (this.onNewLightAdded) {
  12622. this.onNewLightAdded(newLight, position, this);
  12623. }
  12624. };
  12625. Scene.prototype.addCamera = function (newCamera) {
  12626. newCamera.uniqueId = this._uniqueIdCounter++;
  12627. var position = this.cameras.push(newCamera);
  12628. if (this.onNewCameraAdded) {
  12629. this.onNewCameraAdded(newCamera, position, this);
  12630. }
  12631. };
  12632. /**
  12633. * sets the active camera of the scene using its ID
  12634. * @param {string} id - the camera's ID
  12635. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12636. * @see activeCamera
  12637. */
  12638. Scene.prototype.setActiveCameraByID = function (id) {
  12639. var camera = this.getCameraByID(id);
  12640. if (camera) {
  12641. this.activeCamera = camera;
  12642. return camera;
  12643. }
  12644. return null;
  12645. };
  12646. /**
  12647. * sets the active camera of the scene using its name
  12648. * @param {string} name - the camera's name
  12649. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12650. * @see activeCamera
  12651. */
  12652. Scene.prototype.setActiveCameraByName = function (name) {
  12653. var camera = this.getCameraByName(name);
  12654. if (camera) {
  12655. this.activeCamera = camera;
  12656. return camera;
  12657. }
  12658. return null;
  12659. };
  12660. /**
  12661. * get a material using its id
  12662. * @param {string} the material's ID
  12663. * @return {BABYLON.Material|null} the material or null if none found.
  12664. */
  12665. Scene.prototype.getMaterialByID = function (id) {
  12666. for (var index = 0; index < this.materials.length; index++) {
  12667. if (this.materials[index].id === id) {
  12668. return this.materials[index];
  12669. }
  12670. }
  12671. return null;
  12672. };
  12673. /**
  12674. * get a material using its name
  12675. * @param {string} the material's name
  12676. * @return {BABYLON.Material|null} the material or null if none found.
  12677. */
  12678. Scene.prototype.getMaterialByName = function (name) {
  12679. for (var index = 0; index < this.materials.length; index++) {
  12680. if (this.materials[index].name === name) {
  12681. return this.materials[index];
  12682. }
  12683. }
  12684. return null;
  12685. };
  12686. Scene.prototype.getLensFlareSystemByName = function (name) {
  12687. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12688. if (this.lensFlareSystems[index].name === name) {
  12689. return this.lensFlareSystems[index];
  12690. }
  12691. }
  12692. return null;
  12693. };
  12694. Scene.prototype.getCameraByID = function (id) {
  12695. for (var index = 0; index < this.cameras.length; index++) {
  12696. if (this.cameras[index].id === id) {
  12697. return this.cameras[index];
  12698. }
  12699. }
  12700. return null;
  12701. };
  12702. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12703. for (var index = 0; index < this.cameras.length; index++) {
  12704. if (this.cameras[index].uniqueId === uniqueId) {
  12705. return this.cameras[index];
  12706. }
  12707. }
  12708. return null;
  12709. };
  12710. /**
  12711. * get a camera using its name
  12712. * @param {string} the camera's name
  12713. * @return {BABYLON.Camera|null} the camera or null if none found.
  12714. */
  12715. Scene.prototype.getCameraByName = function (name) {
  12716. for (var index = 0; index < this.cameras.length; index++) {
  12717. if (this.cameras[index].name === name) {
  12718. return this.cameras[index];
  12719. }
  12720. }
  12721. return null;
  12722. };
  12723. /**
  12724. * get a light node using its name
  12725. * @param {string} the light's name
  12726. * @return {BABYLON.Light|null} the light or null if none found.
  12727. */
  12728. Scene.prototype.getLightByName = function (name) {
  12729. for (var index = 0; index < this.lights.length; index++) {
  12730. if (this.lights[index].name === name) {
  12731. return this.lights[index];
  12732. }
  12733. }
  12734. return null;
  12735. };
  12736. /**
  12737. * get a light node using its ID
  12738. * @param {string} the light's id
  12739. * @return {BABYLON.Light|null} the light or null if none found.
  12740. */
  12741. Scene.prototype.getLightByID = function (id) {
  12742. for (var index = 0; index < this.lights.length; index++) {
  12743. if (this.lights[index].id === id) {
  12744. return this.lights[index];
  12745. }
  12746. }
  12747. return null;
  12748. };
  12749. /**
  12750. * get a light node using its scene-generated unique ID
  12751. * @param {number} the light's unique id
  12752. * @return {BABYLON.Light|null} the light or null if none found.
  12753. */
  12754. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12755. for (var index = 0; index < this.lights.length; index++) {
  12756. if (this.lights[index].uniqueId === uniqueId) {
  12757. return this.lights[index];
  12758. }
  12759. }
  12760. return null;
  12761. };
  12762. /**
  12763. * get a geometry using its ID
  12764. * @param {string} the geometry's id
  12765. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12766. */
  12767. Scene.prototype.getGeometryByID = function (id) {
  12768. for (var index = 0; index < this._geometries.length; index++) {
  12769. if (this._geometries[index].id === id) {
  12770. return this._geometries[index];
  12771. }
  12772. }
  12773. return null;
  12774. };
  12775. /**
  12776. * add a new geometry to this scene.
  12777. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12778. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12779. * @return {boolean} was the geometry added or not
  12780. */
  12781. Scene.prototype.pushGeometry = function (geometry, force) {
  12782. if (!force && this.getGeometryByID(geometry.id)) {
  12783. return false;
  12784. }
  12785. this._geometries.push(geometry);
  12786. //notify the collision coordinator
  12787. this.collisionCoordinator.onGeometryAdded(geometry);
  12788. if (this.onGeometryAdded) {
  12789. this.onGeometryAdded(geometry);
  12790. }
  12791. return true;
  12792. };
  12793. /**
  12794. * Removes an existing geometry
  12795. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12796. * @return {boolean} was the geometry removed or not
  12797. */
  12798. Scene.prototype.removeGeometry = function (geometry) {
  12799. var index = this._geometries.indexOf(geometry);
  12800. if (index > -1) {
  12801. this._geometries.splice(index, 1);
  12802. //notify the collision coordinator
  12803. this.collisionCoordinator.onGeometryDeleted(geometry);
  12804. if (this.onGeometryRemoved) {
  12805. this.onGeometryRemoved(geometry);
  12806. }
  12807. return true;
  12808. }
  12809. return false;
  12810. };
  12811. Scene.prototype.getGeometries = function () {
  12812. return this._geometries;
  12813. };
  12814. /**
  12815. * Get the first added mesh found of a given ID
  12816. * @param {string} id - the id to search for
  12817. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12818. */
  12819. Scene.prototype.getMeshByID = function (id) {
  12820. for (var index = 0; index < this.meshes.length; index++) {
  12821. if (this.meshes[index].id === id) {
  12822. return this.meshes[index];
  12823. }
  12824. }
  12825. return null;
  12826. };
  12827. /**
  12828. * Get a mesh with its auto-generated unique id
  12829. * @param {number} uniqueId - the unique id to search for
  12830. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12831. */
  12832. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12833. for (var index = 0; index < this.meshes.length; index++) {
  12834. if (this.meshes[index].uniqueId === uniqueId) {
  12835. return this.meshes[index];
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. /**
  12841. * Get a the last added mesh found of a given ID
  12842. * @param {string} id - the id to search for
  12843. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12844. */
  12845. Scene.prototype.getLastMeshByID = function (id) {
  12846. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12847. if (this.meshes[index].id === id) {
  12848. return this.meshes[index];
  12849. }
  12850. }
  12851. return null;
  12852. };
  12853. /**
  12854. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12855. * @param {string} id - the id to search for
  12856. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12857. */
  12858. Scene.prototype.getLastEntryByID = function (id) {
  12859. var index;
  12860. for (index = this.meshes.length - 1; index >= 0; index--) {
  12861. if (this.meshes[index].id === id) {
  12862. return this.meshes[index];
  12863. }
  12864. }
  12865. for (index = this.cameras.length - 1; index >= 0; index--) {
  12866. if (this.cameras[index].id === id) {
  12867. return this.cameras[index];
  12868. }
  12869. }
  12870. for (index = this.lights.length - 1; index >= 0; index--) {
  12871. if (this.lights[index].id === id) {
  12872. return this.lights[index];
  12873. }
  12874. }
  12875. return null;
  12876. };
  12877. Scene.prototype.getNodeByID = function (id) {
  12878. var mesh = this.getMeshByID(id);
  12879. if (mesh) {
  12880. return mesh;
  12881. }
  12882. var light = this.getLightByID(id);
  12883. if (light) {
  12884. return light;
  12885. }
  12886. return this.getCameraByID(id);
  12887. };
  12888. Scene.prototype.getNodeByName = function (name) {
  12889. var mesh = this.getMeshByName(name);
  12890. if (mesh) {
  12891. return mesh;
  12892. }
  12893. var light = this.getLightByName(name);
  12894. if (light) {
  12895. return light;
  12896. }
  12897. return this.getCameraByName(name);
  12898. };
  12899. Scene.prototype.getMeshByName = function (name) {
  12900. for (var index = 0; index < this.meshes.length; index++) {
  12901. if (this.meshes[index].name === name) {
  12902. return this.meshes[index];
  12903. }
  12904. }
  12905. return null;
  12906. };
  12907. Scene.prototype.getSoundByName = function (name) {
  12908. var index;
  12909. if (BABYLON.AudioEngine) {
  12910. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12911. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12912. return this.mainSoundTrack.soundCollection[index];
  12913. }
  12914. }
  12915. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12916. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12917. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12918. return this.soundTracks[sdIndex].soundCollection[index];
  12919. }
  12920. }
  12921. }
  12922. }
  12923. return null;
  12924. };
  12925. Scene.prototype.getLastSkeletonByID = function (id) {
  12926. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12927. if (this.skeletons[index].id === id) {
  12928. return this.skeletons[index];
  12929. }
  12930. }
  12931. return null;
  12932. };
  12933. Scene.prototype.getSkeletonById = function (id) {
  12934. for (var index = 0; index < this.skeletons.length; index++) {
  12935. if (this.skeletons[index].id === id) {
  12936. return this.skeletons[index];
  12937. }
  12938. }
  12939. return null;
  12940. };
  12941. Scene.prototype.getSkeletonByName = function (name) {
  12942. for (var index = 0; index < this.skeletons.length; index++) {
  12943. if (this.skeletons[index].name === name) {
  12944. return this.skeletons[index];
  12945. }
  12946. }
  12947. return null;
  12948. };
  12949. Scene.prototype.isActiveMesh = function (mesh) {
  12950. return (this._activeMeshes.indexOf(mesh) !== -1);
  12951. };
  12952. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12953. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12954. var material = subMesh.getMaterial();
  12955. if (mesh.showSubMeshesBoundingBox) {
  12956. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12957. }
  12958. if (material) {
  12959. // Render targets
  12960. if (material.getRenderTargetTextures) {
  12961. if (this._processedMaterials.indexOf(material) === -1) {
  12962. this._processedMaterials.push(material);
  12963. this._renderTargets.concat(material.getRenderTargetTextures());
  12964. }
  12965. }
  12966. // Dispatch
  12967. this._activeIndices += subMesh.indexCount;
  12968. this._renderingManager.dispatch(subMesh);
  12969. }
  12970. }
  12971. };
  12972. Scene.prototype._evaluateActiveMeshes = function () {
  12973. this.activeCamera._activeMeshes.reset();
  12974. this._activeMeshes.reset();
  12975. this._renderingManager.reset();
  12976. this._processedMaterials.reset();
  12977. this._activeParticleSystems.reset();
  12978. this._activeSkeletons.reset();
  12979. this._softwareSkinnedMeshes.reset();
  12980. this._boundingBoxRenderer.reset();
  12981. this._edgesRenderers.reset();
  12982. if (!this._frustumPlanes) {
  12983. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12984. }
  12985. else {
  12986. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12987. }
  12988. // Meshes
  12989. var meshes;
  12990. var len;
  12991. if (this._selectionOctree) {
  12992. var selection = this._selectionOctree.select(this._frustumPlanes);
  12993. meshes = selection.data;
  12994. len = selection.length;
  12995. }
  12996. else {
  12997. len = this.meshes.length;
  12998. meshes = this.meshes;
  12999. }
  13000. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13001. var mesh = meshes[meshIndex];
  13002. if (mesh.isBlocked) {
  13003. continue;
  13004. }
  13005. this._totalVertices += mesh.getTotalVertices();
  13006. if (!mesh.isReady() || !mesh.isEnabled()) {
  13007. continue;
  13008. }
  13009. mesh.computeWorldMatrix();
  13010. // Intersections
  13011. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13012. this._meshesForIntersections.pushNoDuplicate(mesh);
  13013. }
  13014. // Switch to current LOD
  13015. var meshLOD = mesh.getLOD(this.activeCamera);
  13016. if (!meshLOD) {
  13017. continue;
  13018. }
  13019. mesh._preActivate();
  13020. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13021. this._activeMeshes.push(mesh);
  13022. this.activeCamera._activeMeshes.push(mesh);
  13023. mesh._activate(this._renderId);
  13024. this._activeMesh(meshLOD);
  13025. }
  13026. }
  13027. // Particle systems
  13028. var beforeParticlesDate = BABYLON.Tools.Now;
  13029. if (this.particlesEnabled) {
  13030. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13031. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13032. var particleSystem = this.particleSystems[particleIndex];
  13033. if (!particleSystem.isStarted()) {
  13034. continue;
  13035. }
  13036. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13037. this._activeParticleSystems.push(particleSystem);
  13038. particleSystem.animate();
  13039. }
  13040. }
  13041. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13042. }
  13043. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13044. };
  13045. Scene.prototype._activeMesh = function (mesh) {
  13046. if (mesh.skeleton && this.skeletonsEnabled) {
  13047. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13048. if (!mesh.computeBonesUsingShaders) {
  13049. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13050. }
  13051. }
  13052. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13053. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13054. }
  13055. if (mesh._edgesRenderer) {
  13056. this._edgesRenderers.push(mesh._edgesRenderer);
  13057. }
  13058. if (mesh && mesh.subMeshes) {
  13059. // Submeshes Octrees
  13060. var len;
  13061. var subMeshes;
  13062. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13063. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13064. len = intersections.length;
  13065. subMeshes = intersections.data;
  13066. }
  13067. else {
  13068. subMeshes = mesh.subMeshes;
  13069. len = subMeshes.length;
  13070. }
  13071. for (var subIndex = 0; subIndex < len; subIndex++) {
  13072. var subMesh = subMeshes[subIndex];
  13073. this._evaluateSubMesh(subMesh, mesh);
  13074. }
  13075. }
  13076. };
  13077. Scene.prototype.updateTransformMatrix = function (force) {
  13078. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13079. };
  13080. Scene.prototype._renderForCamera = function (camera) {
  13081. var engine = this._engine;
  13082. this.activeCamera = camera;
  13083. if (!this.activeCamera)
  13084. throw new Error("Active camera not set");
  13085. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13086. // Viewport
  13087. engine.setViewport(this.activeCamera.viewport);
  13088. // Camera
  13089. this.resetCachedMaterial();
  13090. this._renderId++;
  13091. this.updateTransformMatrix();
  13092. if (this.beforeCameraRender) {
  13093. this.beforeCameraRender(this.activeCamera);
  13094. }
  13095. // Meshes
  13096. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13097. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13098. this._evaluateActiveMeshes();
  13099. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13100. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13101. // Skeletons
  13102. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13103. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13104. skeleton.prepare();
  13105. }
  13106. // Software skinning
  13107. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13108. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13109. mesh.applySkeleton(mesh.skeleton);
  13110. }
  13111. // Render targets
  13112. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13113. if (this.renderTargetsEnabled) {
  13114. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13115. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13116. var renderTarget = this._renderTargets.data[renderIndex];
  13117. if (renderTarget._shouldRender()) {
  13118. this._renderId++;
  13119. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13120. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13121. }
  13122. }
  13123. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13124. this._renderId++;
  13125. }
  13126. if (this._renderTargets.length > 0) {
  13127. engine.restoreDefaultFramebuffer();
  13128. }
  13129. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13130. // Prepare Frame
  13131. this.postProcessManager._prepareFrame();
  13132. var beforeRenderDate = BABYLON.Tools.Now;
  13133. // Backgrounds
  13134. var layerIndex;
  13135. var layer;
  13136. if (this.layers.length) {
  13137. engine.setDepthBuffer(false);
  13138. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13139. layer = this.layers[layerIndex];
  13140. if (layer.isBackground) {
  13141. layer.render();
  13142. }
  13143. }
  13144. engine.setDepthBuffer(true);
  13145. }
  13146. // Render
  13147. BABYLON.Tools.StartPerformanceCounter("Main render");
  13148. this._renderingManager.render(null, null, true, true);
  13149. BABYLON.Tools.EndPerformanceCounter("Main render");
  13150. // Bounding boxes
  13151. this._boundingBoxRenderer.render();
  13152. // Edges
  13153. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13154. this._edgesRenderers.data[edgesRendererIndex].render();
  13155. }
  13156. // Lens flares
  13157. if (this.lensFlaresEnabled) {
  13158. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13159. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13160. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13161. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13162. lensFlareSystem.render();
  13163. }
  13164. }
  13165. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13166. }
  13167. // Foregrounds
  13168. if (this.layers.length) {
  13169. engine.setDepthBuffer(false);
  13170. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13171. layer = this.layers[layerIndex];
  13172. if (!layer.isBackground) {
  13173. layer.render();
  13174. }
  13175. }
  13176. engine.setDepthBuffer(true);
  13177. }
  13178. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13179. // Finalize frame
  13180. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13181. // Update camera
  13182. this.activeCamera._updateFromScene();
  13183. // Reset some special arrays
  13184. this._renderTargets.reset();
  13185. if (this.afterCameraRender) {
  13186. this.afterCameraRender(this.activeCamera);
  13187. }
  13188. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13189. };
  13190. Scene.prototype._processSubCameras = function (camera) {
  13191. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13192. this._renderForCamera(camera);
  13193. return;
  13194. }
  13195. // rig cameras
  13196. for (var index = 0; index < camera._rigCameras.length; index++) {
  13197. this._renderForCamera(camera._rigCameras[index]);
  13198. }
  13199. this.activeCamera = camera;
  13200. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13201. // Update camera
  13202. this.activeCamera._updateFromScene();
  13203. };
  13204. Scene.prototype._checkIntersections = function () {
  13205. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13206. var sourceMesh = this._meshesForIntersections.data[index];
  13207. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13208. var action = sourceMesh.actionManager.actions[actionIndex];
  13209. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13210. var parameters = action.getTriggerParameter();
  13211. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13212. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13213. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13214. if (areIntersecting && currentIntersectionInProgress === -1) {
  13215. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13216. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13217. sourceMesh._intersectionsInProgress.push(otherMesh);
  13218. }
  13219. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13220. sourceMesh._intersectionsInProgress.push(otherMesh);
  13221. }
  13222. }
  13223. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13224. //They intersected, and now they don't.
  13225. //is this trigger an exit trigger? execute an event.
  13226. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13227. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13228. }
  13229. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13230. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13231. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13232. }
  13233. }
  13234. }
  13235. }
  13236. }
  13237. };
  13238. Scene.prototype.render = function () {
  13239. var startDate = BABYLON.Tools.Now;
  13240. this._particlesDuration = 0;
  13241. this._spritesDuration = 0;
  13242. this._activeParticles = 0;
  13243. this._renderDuration = 0;
  13244. this._renderTargetsDuration = 0;
  13245. this._evaluateActiveMeshesDuration = 0;
  13246. this._totalVertices = 0;
  13247. this._activeIndices = 0;
  13248. this._activeBones = 0;
  13249. this.getEngine().resetDrawCalls();
  13250. this._meshesForIntersections.reset();
  13251. this.resetCachedMaterial();
  13252. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13253. // Actions
  13254. if (this.actionManager) {
  13255. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13256. }
  13257. //Simplification Queue
  13258. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13259. this.simplificationQueue.executeNext();
  13260. }
  13261. // Animations
  13262. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13263. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13264. this._animate();
  13265. // Physics
  13266. if (this._physicsEngine) {
  13267. BABYLON.Tools.StartPerformanceCounter("Physics");
  13268. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13269. BABYLON.Tools.EndPerformanceCounter("Physics");
  13270. }
  13271. // Before render
  13272. if (this.beforeRender) {
  13273. this.beforeRender();
  13274. }
  13275. var callbackIndex;
  13276. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13277. this._onBeforeRenderCallbacks[callbackIndex]();
  13278. }
  13279. // Customs render targets
  13280. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13281. var engine = this.getEngine();
  13282. var currentActiveCamera = this.activeCamera;
  13283. if (this.renderTargetsEnabled) {
  13284. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13285. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13286. var renderTarget = this.customRenderTargets[customIndex];
  13287. if (renderTarget._shouldRender()) {
  13288. this._renderId++;
  13289. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13290. if (!this.activeCamera)
  13291. throw new Error("Active camera not set");
  13292. // Viewport
  13293. engine.setViewport(this.activeCamera.viewport);
  13294. // Camera
  13295. this.updateTransformMatrix();
  13296. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13297. }
  13298. }
  13299. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13300. this._renderId++;
  13301. }
  13302. if (this.customRenderTargets.length > 0) {
  13303. engine.restoreDefaultFramebuffer();
  13304. }
  13305. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13306. this.activeCamera = currentActiveCamera;
  13307. // Procedural textures
  13308. if (this.proceduralTexturesEnabled) {
  13309. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13310. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13311. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13312. if (proceduralTexture._shouldRender()) {
  13313. proceduralTexture.render();
  13314. }
  13315. }
  13316. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13317. }
  13318. // Clear
  13319. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13320. // Shadows
  13321. if (this.shadowsEnabled) {
  13322. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13323. var light = this.lights[lightIndex];
  13324. var shadowGenerator = light.getShadowGenerator();
  13325. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13326. this._renderTargets.push(shadowGenerator.getShadowMap());
  13327. }
  13328. }
  13329. }
  13330. // Depth renderer
  13331. if (this._depthRenderer) {
  13332. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13333. }
  13334. // RenderPipeline
  13335. this.postProcessRenderPipelineManager.update();
  13336. // Multi-cameras?
  13337. if (this.activeCameras.length > 0) {
  13338. var currentRenderId = this._renderId;
  13339. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13340. this._renderId = currentRenderId;
  13341. this._processSubCameras(this.activeCameras[cameraIndex]);
  13342. }
  13343. }
  13344. else {
  13345. if (!this.activeCamera) {
  13346. throw new Error("No camera defined");
  13347. }
  13348. this._processSubCameras(this.activeCamera);
  13349. }
  13350. // Intersection checks
  13351. this._checkIntersections();
  13352. // Update the audio listener attached to the camera
  13353. if (BABYLON.AudioEngine) {
  13354. this._updateAudioParameters();
  13355. }
  13356. // After render
  13357. if (this.afterRender) {
  13358. this.afterRender();
  13359. }
  13360. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13361. this._onAfterRenderCallbacks[callbackIndex]();
  13362. }
  13363. // Cleaning
  13364. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13365. this._toBeDisposed.data[index].dispose();
  13366. this._toBeDisposed[index] = null;
  13367. }
  13368. this._toBeDisposed.reset();
  13369. if (this.dumpNextRenderTargets) {
  13370. this.dumpNextRenderTargets = false;
  13371. }
  13372. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13373. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13374. };
  13375. Scene.prototype._updateAudioParameters = function () {
  13376. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13377. return;
  13378. }
  13379. var listeningCamera;
  13380. var audioEngine = BABYLON.Engine.audioEngine;
  13381. if (this.activeCameras.length > 0) {
  13382. listeningCamera = this.activeCameras[0];
  13383. }
  13384. else {
  13385. listeningCamera = this.activeCamera;
  13386. }
  13387. if (listeningCamera && audioEngine.canUseWebAudio) {
  13388. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13389. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13390. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13391. cameraDirection.normalize();
  13392. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13393. var i;
  13394. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13395. var sound = this.mainSoundTrack.soundCollection[i];
  13396. if (sound.useCustomAttenuation) {
  13397. sound.updateDistanceFromListener();
  13398. }
  13399. }
  13400. for (i = 0; i < this.soundTracks.length; i++) {
  13401. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13402. sound = this.soundTracks[i].soundCollection[j];
  13403. if (sound.useCustomAttenuation) {
  13404. sound.updateDistanceFromListener();
  13405. }
  13406. }
  13407. }
  13408. }
  13409. };
  13410. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13411. // Audio
  13412. get: function () {
  13413. return this._audioEnabled;
  13414. },
  13415. set: function (value) {
  13416. this._audioEnabled = value;
  13417. if (BABYLON.AudioEngine) {
  13418. if (this._audioEnabled) {
  13419. this._enableAudio();
  13420. }
  13421. else {
  13422. this._disableAudio();
  13423. }
  13424. }
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. Scene.prototype._disableAudio = function () {
  13430. var i;
  13431. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13432. this.mainSoundTrack.soundCollection[i].pause();
  13433. }
  13434. for (i = 0; i < this.soundTracks.length; i++) {
  13435. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13436. this.soundTracks[i].soundCollection[j].pause();
  13437. }
  13438. }
  13439. };
  13440. Scene.prototype._enableAudio = function () {
  13441. var i;
  13442. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13443. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13444. this.mainSoundTrack.soundCollection[i].play();
  13445. }
  13446. }
  13447. for (i = 0; i < this.soundTracks.length; i++) {
  13448. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13449. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13450. this.soundTracks[i].soundCollection[j].play();
  13451. }
  13452. }
  13453. }
  13454. };
  13455. Object.defineProperty(Scene.prototype, "headphone", {
  13456. get: function () {
  13457. return this._headphone;
  13458. },
  13459. set: function (value) {
  13460. this._headphone = value;
  13461. if (BABYLON.AudioEngine) {
  13462. if (this._headphone) {
  13463. this._switchAudioModeForHeadphones();
  13464. }
  13465. else {
  13466. this._switchAudioModeForNormalSpeakers();
  13467. }
  13468. }
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. Scene.prototype._switchAudioModeForHeadphones = function () {
  13474. this.mainSoundTrack.switchPanningModelToHRTF();
  13475. for (var i = 0; i < this.soundTracks.length; i++) {
  13476. this.soundTracks[i].switchPanningModelToHRTF();
  13477. }
  13478. };
  13479. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13480. this.mainSoundTrack.switchPanningModelToEqualPower();
  13481. for (var i = 0; i < this.soundTracks.length; i++) {
  13482. this.soundTracks[i].switchPanningModelToEqualPower();
  13483. }
  13484. };
  13485. Scene.prototype.enableDepthRenderer = function () {
  13486. if (this._depthRenderer) {
  13487. return this._depthRenderer;
  13488. }
  13489. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13490. return this._depthRenderer;
  13491. };
  13492. Scene.prototype.disableDepthRenderer = function () {
  13493. if (!this._depthRenderer) {
  13494. return;
  13495. }
  13496. this._depthRenderer.dispose();
  13497. this._depthRenderer = null;
  13498. };
  13499. Scene.prototype.dispose = function () {
  13500. this.beforeRender = null;
  13501. this.afterRender = null;
  13502. this.skeletons = [];
  13503. this._boundingBoxRenderer.dispose();
  13504. if (this._depthRenderer) {
  13505. this._depthRenderer.dispose();
  13506. }
  13507. // Debug layer
  13508. this.debugLayer.hide();
  13509. // Events
  13510. if (this.onDispose) {
  13511. this.onDispose();
  13512. }
  13513. this._onBeforeRenderCallbacks = [];
  13514. this._onAfterRenderCallbacks = [];
  13515. this.detachControl();
  13516. // Release sounds & sounds tracks
  13517. if (BABYLON.AudioEngine) {
  13518. this.disposeSounds();
  13519. }
  13520. // Detach cameras
  13521. var canvas = this._engine.getRenderingCanvas();
  13522. var index;
  13523. for (index = 0; index < this.cameras.length; index++) {
  13524. this.cameras[index].detachControl(canvas);
  13525. }
  13526. // Release lights
  13527. while (this.lights.length) {
  13528. this.lights[0].dispose();
  13529. }
  13530. // Release meshes
  13531. while (this.meshes.length) {
  13532. this.meshes[0].dispose(true);
  13533. }
  13534. // Release cameras
  13535. while (this.cameras.length) {
  13536. this.cameras[0].dispose();
  13537. }
  13538. // Release materials
  13539. while (this.materials.length) {
  13540. this.materials[0].dispose();
  13541. }
  13542. // Release particles
  13543. while (this.particleSystems.length) {
  13544. this.particleSystems[0].dispose();
  13545. }
  13546. // Release sprites
  13547. while (this.spriteManagers.length) {
  13548. this.spriteManagers[0].dispose();
  13549. }
  13550. // Release layers
  13551. while (this.layers.length) {
  13552. this.layers[0].dispose();
  13553. }
  13554. // Release textures
  13555. while (this.textures.length) {
  13556. this.textures[0].dispose();
  13557. }
  13558. // Post-processes
  13559. this.postProcessManager.dispose();
  13560. // Physics
  13561. if (this._physicsEngine) {
  13562. this.disablePhysicsEngine();
  13563. }
  13564. // Remove from engine
  13565. index = this._engine.scenes.indexOf(this);
  13566. if (index > -1) {
  13567. this._engine.scenes.splice(index, 1);
  13568. }
  13569. this._engine.wipeCaches();
  13570. };
  13571. // Release sounds & sounds tracks
  13572. Scene.prototype.disposeSounds = function () {
  13573. this.mainSoundTrack.dispose();
  13574. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13575. this.soundTracks[scIndex].dispose();
  13576. }
  13577. };
  13578. // Octrees
  13579. Scene.prototype.getWorldExtends = function () {
  13580. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13581. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13582. for (var index = 0; index < this.meshes.length; index++) {
  13583. var mesh = this.meshes[index];
  13584. mesh.computeWorldMatrix(true);
  13585. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13586. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13587. BABYLON.Tools.CheckExtends(minBox, min, max);
  13588. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13589. }
  13590. return {
  13591. min: min,
  13592. max: max
  13593. };
  13594. };
  13595. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13596. if (maxCapacity === void 0) { maxCapacity = 64; }
  13597. if (maxDepth === void 0) { maxDepth = 2; }
  13598. if (!this._selectionOctree) {
  13599. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13600. }
  13601. var worldExtends = this.getWorldExtends();
  13602. // Update octree
  13603. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13604. return this._selectionOctree;
  13605. };
  13606. // Picking
  13607. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13608. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13609. var engine = this._engine;
  13610. if (!camera) {
  13611. if (!this.activeCamera)
  13612. throw new Error("Active camera not set");
  13613. camera = this.activeCamera;
  13614. }
  13615. var cameraViewport = camera.viewport;
  13616. var viewport = cameraViewport.toGlobal(engine);
  13617. // Moving coordinates to local viewport world
  13618. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13619. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13620. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13621. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13622. };
  13623. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13624. var engine = this._engine;
  13625. if (!camera) {
  13626. if (!this.activeCamera)
  13627. throw new Error("Active camera not set");
  13628. camera = this.activeCamera;
  13629. }
  13630. var cameraViewport = camera.viewport;
  13631. var viewport = cameraViewport.toGlobal(engine);
  13632. var identity = BABYLON.Matrix.Identity();
  13633. // Moving coordinates to local viewport world
  13634. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13635. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13636. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13637. };
  13638. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13639. var pickingInfo = null;
  13640. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13641. var mesh = this.meshes[meshIndex];
  13642. if (predicate) {
  13643. if (!predicate(mesh)) {
  13644. continue;
  13645. }
  13646. }
  13647. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13648. continue;
  13649. }
  13650. var world = mesh.getWorldMatrix();
  13651. var ray = rayFunction(world);
  13652. var result = mesh.intersects(ray, fastCheck);
  13653. if (!result || !result.hit)
  13654. continue;
  13655. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13656. continue;
  13657. pickingInfo = result;
  13658. if (fastCheck) {
  13659. break;
  13660. }
  13661. }
  13662. return pickingInfo || new BABYLON.PickingInfo();
  13663. };
  13664. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13665. var pickingInfo = null;
  13666. camera = camera || this.activeCamera;
  13667. if (this.spriteManagers.length > 0) {
  13668. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13669. var spriteManager = this.spriteManagers[spriteIndex];
  13670. if (!spriteManager.isPickable) {
  13671. continue;
  13672. }
  13673. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13674. if (!result || !result.hit)
  13675. continue;
  13676. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13677. continue;
  13678. pickingInfo = result;
  13679. if (fastCheck) {
  13680. break;
  13681. }
  13682. }
  13683. }
  13684. return pickingInfo || new BABYLON.PickingInfo();
  13685. };
  13686. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13687. var _this = this;
  13688. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13689. /// <param name="x">X position on screen</param>
  13690. /// <param name="y">Y position on screen</param>
  13691. /// <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>
  13692. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13693. /// <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>
  13694. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13695. };
  13696. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13697. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13698. /// <param name="x">X position on screen</param>
  13699. /// <param name="y">Y position on screen</param>
  13700. /// <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>
  13701. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13702. /// <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>
  13703. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13704. };
  13705. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13706. var _this = this;
  13707. return this._internalPick(function (world) {
  13708. if (!_this._pickWithRayInverseMatrix) {
  13709. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13710. }
  13711. world.invertToRef(_this._pickWithRayInverseMatrix);
  13712. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13713. }, predicate, fastCheck);
  13714. };
  13715. Scene.prototype.setPointerOverMesh = function (mesh) {
  13716. if (this._pointerOverMesh === mesh) {
  13717. return;
  13718. }
  13719. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13720. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13721. }
  13722. this._pointerOverMesh = mesh;
  13723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13725. }
  13726. };
  13727. Scene.prototype.getPointerOverMesh = function () {
  13728. return this._pointerOverMesh;
  13729. };
  13730. // Physics
  13731. Scene.prototype.getPhysicsEngine = function () {
  13732. return this._physicsEngine;
  13733. };
  13734. /**
  13735. * Enables physics to the current scene
  13736. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13737. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13738. * @return {boolean} was the physics engine initialized
  13739. */
  13740. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13741. if (this._physicsEngine) {
  13742. return true;
  13743. }
  13744. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13745. if (!this._physicsEngine.isSupported()) {
  13746. this._physicsEngine = null;
  13747. return false;
  13748. }
  13749. this._physicsEngine._initialize(gravity);
  13750. return true;
  13751. };
  13752. Scene.prototype.disablePhysicsEngine = function () {
  13753. if (!this._physicsEngine) {
  13754. return;
  13755. }
  13756. this._physicsEngine.dispose();
  13757. this._physicsEngine = undefined;
  13758. };
  13759. Scene.prototype.isPhysicsEnabled = function () {
  13760. return this._physicsEngine !== undefined;
  13761. };
  13762. /**
  13763. * Sets the gravity of the physics engine (and NOT of the scene)
  13764. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13765. */
  13766. Scene.prototype.setGravity = function (gravity) {
  13767. if (!this._physicsEngine) {
  13768. return;
  13769. }
  13770. this._physicsEngine._setGravity(gravity);
  13771. };
  13772. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13773. if (parts.parts) {
  13774. options = parts;
  13775. parts = parts.parts;
  13776. }
  13777. if (!this._physicsEngine) {
  13778. return null;
  13779. }
  13780. for (var index = 0; index < parts.length; index++) {
  13781. var mesh = parts[index].mesh;
  13782. mesh._physicImpostor = parts[index].impostor;
  13783. mesh._physicsMass = options.mass / parts.length;
  13784. mesh._physicsFriction = options.friction;
  13785. mesh._physicRestitution = options.restitution;
  13786. }
  13787. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13788. };
  13789. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13790. for (var index = 0; index < compound.parts.length; index++) {
  13791. var mesh = compound.parts[index].mesh;
  13792. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13793. this._physicsEngine._unregisterMesh(mesh);
  13794. }
  13795. };
  13796. // Misc.
  13797. Scene.prototype.createDefaultCameraOrLight = function () {
  13798. // Light
  13799. if (this.lights.length === 0) {
  13800. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13801. }
  13802. // Camera
  13803. if (!this.activeCamera) {
  13804. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13805. // Compute position
  13806. var worldExtends = this.getWorldExtends();
  13807. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13808. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13809. camera.setTarget(worldCenter);
  13810. this.activeCamera = camera;
  13811. }
  13812. };
  13813. // Tags
  13814. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13815. if (tagsQuery === undefined) {
  13816. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13817. return list;
  13818. }
  13819. var listByTags = [];
  13820. forEach = forEach || (function (item) { return; });
  13821. for (var i in list) {
  13822. var item = list[i];
  13823. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13824. listByTags.push(item);
  13825. forEach(item);
  13826. }
  13827. }
  13828. return listByTags;
  13829. };
  13830. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13831. return this._getByTags(this.meshes, tagsQuery, forEach);
  13832. };
  13833. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13834. return this._getByTags(this.cameras, tagsQuery, forEach);
  13835. };
  13836. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13837. return this._getByTags(this.lights, tagsQuery, forEach);
  13838. };
  13839. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13840. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13841. };
  13842. // Statics
  13843. Scene._FOGMODE_NONE = 0;
  13844. Scene._FOGMODE_EXP = 1;
  13845. Scene._FOGMODE_EXP2 = 2;
  13846. Scene._FOGMODE_LINEAR = 3;
  13847. Scene.MinDeltaTime = 1.0;
  13848. Scene.MaxDeltaTime = 1000.0;
  13849. return Scene;
  13850. })();
  13851. BABYLON.Scene = Scene;
  13852. })(BABYLON || (BABYLON = {}));
  13853. var BABYLON;
  13854. (function (BABYLON) {
  13855. var VertexBuffer = (function () {
  13856. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13857. if (engine instanceof BABYLON.Mesh) {
  13858. this._engine = engine.getScene().getEngine();
  13859. }
  13860. else {
  13861. this._engine = engine;
  13862. }
  13863. this._updatable = updatable;
  13864. this._data = data;
  13865. if (!postponeInternalCreation) {
  13866. this.create();
  13867. }
  13868. this._kind = kind;
  13869. if (stride) {
  13870. this._strideSize = stride;
  13871. return;
  13872. }
  13873. // Deduce stride from kind
  13874. switch (kind) {
  13875. case VertexBuffer.PositionKind:
  13876. this._strideSize = 3;
  13877. break;
  13878. case VertexBuffer.NormalKind:
  13879. this._strideSize = 3;
  13880. break;
  13881. case VertexBuffer.UVKind:
  13882. case VertexBuffer.UV2Kind:
  13883. case VertexBuffer.UV3Kind:
  13884. case VertexBuffer.UV4Kind:
  13885. case VertexBuffer.UV5Kind:
  13886. case VertexBuffer.UV6Kind:
  13887. this._strideSize = 2;
  13888. break;
  13889. case VertexBuffer.ColorKind:
  13890. this._strideSize = 4;
  13891. break;
  13892. case VertexBuffer.MatricesIndicesKind:
  13893. case VertexBuffer.MatricesIndicesExtraKind:
  13894. this._strideSize = 4;
  13895. break;
  13896. case VertexBuffer.MatricesWeightsKind:
  13897. case VertexBuffer.MatricesWeightsExtraKind:
  13898. this._strideSize = 4;
  13899. break;
  13900. }
  13901. }
  13902. // Properties
  13903. VertexBuffer.prototype.isUpdatable = function () {
  13904. return this._updatable;
  13905. };
  13906. VertexBuffer.prototype.getData = function () {
  13907. return this._data;
  13908. };
  13909. VertexBuffer.prototype.getBuffer = function () {
  13910. return this._buffer;
  13911. };
  13912. VertexBuffer.prototype.getStrideSize = function () {
  13913. return this._strideSize;
  13914. };
  13915. // Methods
  13916. VertexBuffer.prototype.create = function (data) {
  13917. if (!data && this._buffer) {
  13918. return; // nothing to do
  13919. }
  13920. data = data || this._data;
  13921. if (!this._buffer) {
  13922. if (this._updatable) {
  13923. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13924. }
  13925. else {
  13926. this._buffer = this._engine.createVertexBuffer(data);
  13927. }
  13928. }
  13929. if (this._updatable) {
  13930. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13931. this._data = data;
  13932. }
  13933. };
  13934. VertexBuffer.prototype.update = function (data) {
  13935. this.create(data);
  13936. };
  13937. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13938. if (!this._buffer) {
  13939. return;
  13940. }
  13941. if (this._updatable) {
  13942. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13943. this._data = null;
  13944. }
  13945. };
  13946. VertexBuffer.prototype.dispose = function () {
  13947. if (!this._buffer) {
  13948. return;
  13949. }
  13950. if (this._engine._releaseBuffer(this._buffer)) {
  13951. this._buffer = null;
  13952. }
  13953. };
  13954. Object.defineProperty(VertexBuffer, "PositionKind", {
  13955. get: function () {
  13956. return VertexBuffer._PositionKind;
  13957. },
  13958. enumerable: true,
  13959. configurable: true
  13960. });
  13961. Object.defineProperty(VertexBuffer, "NormalKind", {
  13962. get: function () {
  13963. return VertexBuffer._NormalKind;
  13964. },
  13965. enumerable: true,
  13966. configurable: true
  13967. });
  13968. Object.defineProperty(VertexBuffer, "UVKind", {
  13969. get: function () {
  13970. return VertexBuffer._UVKind;
  13971. },
  13972. enumerable: true,
  13973. configurable: true
  13974. });
  13975. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13976. get: function () {
  13977. return VertexBuffer._UV2Kind;
  13978. },
  13979. enumerable: true,
  13980. configurable: true
  13981. });
  13982. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13983. get: function () {
  13984. return VertexBuffer._UV3Kind;
  13985. },
  13986. enumerable: true,
  13987. configurable: true
  13988. });
  13989. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13990. get: function () {
  13991. return VertexBuffer._UV4Kind;
  13992. },
  13993. enumerable: true,
  13994. configurable: true
  13995. });
  13996. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13997. get: function () {
  13998. return VertexBuffer._UV5Kind;
  13999. },
  14000. enumerable: true,
  14001. configurable: true
  14002. });
  14003. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14004. get: function () {
  14005. return VertexBuffer._UV6Kind;
  14006. },
  14007. enumerable: true,
  14008. configurable: true
  14009. });
  14010. Object.defineProperty(VertexBuffer, "ColorKind", {
  14011. get: function () {
  14012. return VertexBuffer._ColorKind;
  14013. },
  14014. enumerable: true,
  14015. configurable: true
  14016. });
  14017. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14018. get: function () {
  14019. return VertexBuffer._MatricesIndicesKind;
  14020. },
  14021. enumerable: true,
  14022. configurable: true
  14023. });
  14024. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14025. get: function () {
  14026. return VertexBuffer._MatricesWeightsKind;
  14027. },
  14028. enumerable: true,
  14029. configurable: true
  14030. });
  14031. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14032. get: function () {
  14033. return VertexBuffer._MatricesIndicesExtraKind;
  14034. },
  14035. enumerable: true,
  14036. configurable: true
  14037. });
  14038. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14039. get: function () {
  14040. return VertexBuffer._MatricesWeightsExtraKind;
  14041. },
  14042. enumerable: true,
  14043. configurable: true
  14044. });
  14045. // Enums
  14046. VertexBuffer._PositionKind = "position";
  14047. VertexBuffer._NormalKind = "normal";
  14048. VertexBuffer._UVKind = "uv";
  14049. VertexBuffer._UV2Kind = "uv2";
  14050. VertexBuffer._UV3Kind = "uv3";
  14051. VertexBuffer._UV4Kind = "uv4";
  14052. VertexBuffer._UV5Kind = "uv5";
  14053. VertexBuffer._UV6Kind = "uv6";
  14054. VertexBuffer._ColorKind = "color";
  14055. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14056. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14057. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14058. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14059. return VertexBuffer;
  14060. })();
  14061. BABYLON.VertexBuffer = VertexBuffer;
  14062. })(BABYLON || (BABYLON = {}));
  14063. var BABYLON;
  14064. (function (BABYLON) {
  14065. /**
  14066. * Creates an instance based on a source mesh.
  14067. */
  14068. var InstancedMesh = (function (_super) {
  14069. __extends(InstancedMesh, _super);
  14070. function InstancedMesh(name, source) {
  14071. _super.call(this, name, source.getScene());
  14072. source.instances.push(this);
  14073. this._sourceMesh = source;
  14074. this.position.copyFrom(source.position);
  14075. this.rotation.copyFrom(source.rotation);
  14076. this.scaling.copyFrom(source.scaling);
  14077. if (source.rotationQuaternion) {
  14078. this.rotationQuaternion = source.rotationQuaternion.clone();
  14079. }
  14080. this.infiniteDistance = source.infiniteDistance;
  14081. this.setPivotMatrix(source.getPivotMatrix());
  14082. this.refreshBoundingInfo();
  14083. this._syncSubMeshes();
  14084. }
  14085. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14086. // Methods
  14087. get: function () {
  14088. return this._sourceMesh.receiveShadows;
  14089. },
  14090. enumerable: true,
  14091. configurable: true
  14092. });
  14093. Object.defineProperty(InstancedMesh.prototype, "material", {
  14094. get: function () {
  14095. return this._sourceMesh.material;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14101. get: function () {
  14102. return this._sourceMesh.visibility;
  14103. },
  14104. enumerable: true,
  14105. configurable: true
  14106. });
  14107. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14108. get: function () {
  14109. return this._sourceMesh.skeleton;
  14110. },
  14111. enumerable: true,
  14112. configurable: true
  14113. });
  14114. InstancedMesh.prototype.getTotalVertices = function () {
  14115. return this._sourceMesh.getTotalVertices();
  14116. };
  14117. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14118. get: function () {
  14119. return this._sourceMesh;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. InstancedMesh.prototype.getVerticesData = function (kind) {
  14125. return this._sourceMesh.getVerticesData(kind);
  14126. };
  14127. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14128. return this._sourceMesh.isVerticesDataPresent(kind);
  14129. };
  14130. InstancedMesh.prototype.getIndices = function () {
  14131. return this._sourceMesh.getIndices();
  14132. };
  14133. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14134. get: function () {
  14135. return this._sourceMesh._positions;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14141. var meshBB = this._sourceMesh.getBoundingInfo();
  14142. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14143. this._updateBoundingInfo();
  14144. };
  14145. InstancedMesh.prototype._preActivate = function () {
  14146. if (this._currentLOD) {
  14147. this._currentLOD._preActivate();
  14148. }
  14149. };
  14150. InstancedMesh.prototype._activate = function (renderId) {
  14151. if (this._currentLOD) {
  14152. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14153. }
  14154. };
  14155. InstancedMesh.prototype.getLOD = function (camera) {
  14156. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14157. if (this._currentLOD === this.sourceMesh) {
  14158. return this;
  14159. }
  14160. return this._currentLOD;
  14161. };
  14162. InstancedMesh.prototype._syncSubMeshes = function () {
  14163. this.releaseSubMeshes();
  14164. if (this._sourceMesh.subMeshes) {
  14165. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14166. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14167. }
  14168. }
  14169. };
  14170. InstancedMesh.prototype._generatePointsArray = function () {
  14171. return this._sourceMesh._generatePointsArray();
  14172. };
  14173. // Clone
  14174. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14175. var result = this._sourceMesh.createInstance(name);
  14176. // Deep copy
  14177. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14178. // Bounding info
  14179. this.refreshBoundingInfo();
  14180. // Parent
  14181. if (newParent) {
  14182. result.parent = newParent;
  14183. }
  14184. if (!doNotCloneChildren) {
  14185. // Children
  14186. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14187. var mesh = this.getScene().meshes[index];
  14188. if (mesh.parent === this) {
  14189. mesh.clone(mesh.name, result);
  14190. }
  14191. }
  14192. }
  14193. result.computeWorldMatrix(true);
  14194. return result;
  14195. };
  14196. // Dispoe
  14197. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14198. // Remove from mesh
  14199. var index = this._sourceMesh.instances.indexOf(this);
  14200. this._sourceMesh.instances.splice(index, 1);
  14201. _super.prototype.dispose.call(this, doNotRecurse);
  14202. };
  14203. return InstancedMesh;
  14204. })(BABYLON.AbstractMesh);
  14205. BABYLON.InstancedMesh = InstancedMesh;
  14206. })(BABYLON || (BABYLON = {}));
  14207. var BABYLON;
  14208. (function (BABYLON) {
  14209. var _InstancesBatch = (function () {
  14210. function _InstancesBatch() {
  14211. this.mustReturn = false;
  14212. this.visibleInstances = new Array();
  14213. this.renderSelf = new Array();
  14214. }
  14215. return _InstancesBatch;
  14216. })();
  14217. BABYLON._InstancesBatch = _InstancesBatch;
  14218. var Mesh = (function (_super) {
  14219. __extends(Mesh, _super);
  14220. /**
  14221. * @constructor
  14222. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14223. * @param {Scene} scene - The scene to add this mesh to.
  14224. * @param {Node} parent - The parent of this mesh, if it has one
  14225. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14226. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14227. * When false, achieved by calling a clone(), also passing False.
  14228. * This will make creation of children, recursive.
  14229. */
  14230. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14231. if (parent === void 0) { parent = null; }
  14232. _super.call(this, name, scene);
  14233. // Members
  14234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14235. this.instances = new Array();
  14236. this._LODLevels = new Array();
  14237. this._onBeforeRenderCallbacks = new Array();
  14238. this._onAfterRenderCallbacks = new Array();
  14239. this._visibleInstances = {};
  14240. this._renderIdForInstances = new Array();
  14241. this._batchCache = new _InstancesBatch();
  14242. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14243. this._sideOrientation = Mesh._DEFAULTSIDE;
  14244. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14245. if (source) {
  14246. // Geometry
  14247. if (source._geometry) {
  14248. source._geometry.applyToMesh(this);
  14249. }
  14250. // Deep copy
  14251. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14252. this.id = name + "." + source.id;
  14253. // Material
  14254. this.material = source.material;
  14255. var index;
  14256. if (!doNotCloneChildren) {
  14257. // Children
  14258. for (index = 0; index < scene.meshes.length; index++) {
  14259. var mesh = scene.meshes[index];
  14260. if (mesh.parent === source) {
  14261. // doNotCloneChildren is always going to be False
  14262. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14263. }
  14264. }
  14265. }
  14266. // Particles
  14267. for (index = 0; index < scene.particleSystems.length; index++) {
  14268. var system = scene.particleSystems[index];
  14269. if (system.emitter === source) {
  14270. system.clone(system.name, this);
  14271. }
  14272. }
  14273. this.computeWorldMatrix(true);
  14274. }
  14275. // Parent
  14276. if (parent !== null) {
  14277. this.parent = parent;
  14278. }
  14279. }
  14280. Object.defineProperty(Mesh, "FRONTSIDE", {
  14281. get: function () {
  14282. return Mesh._FRONTSIDE;
  14283. },
  14284. enumerable: true,
  14285. configurable: true
  14286. });
  14287. Object.defineProperty(Mesh, "BACKSIDE", {
  14288. get: function () {
  14289. return Mesh._BACKSIDE;
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14295. get: function () {
  14296. return Mesh._DOUBLESIDE;
  14297. },
  14298. enumerable: true,
  14299. configurable: true
  14300. });
  14301. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14302. get: function () {
  14303. return Mesh._DEFAULTSIDE;
  14304. },
  14305. enumerable: true,
  14306. configurable: true
  14307. });
  14308. Object.defineProperty(Mesh, "NO_CAP", {
  14309. get: function () {
  14310. return Mesh._NO_CAP;
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. Object.defineProperty(Mesh, "CAP_START", {
  14316. get: function () {
  14317. return Mesh._CAP_START;
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(Mesh, "CAP_END", {
  14323. get: function () {
  14324. return Mesh._CAP_END;
  14325. },
  14326. enumerable: true,
  14327. configurable: true
  14328. });
  14329. Object.defineProperty(Mesh, "CAP_ALL", {
  14330. get: function () {
  14331. return Mesh._CAP_ALL;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14337. // Methods
  14338. get: function () {
  14339. return this._LODLevels.length > 0;
  14340. },
  14341. enumerable: true,
  14342. configurable: true
  14343. });
  14344. Mesh.prototype._sortLODLevels = function () {
  14345. this._LODLevels.sort(function (a, b) {
  14346. if (a.distance < b.distance) {
  14347. return 1;
  14348. }
  14349. if (a.distance > b.distance) {
  14350. return -1;
  14351. }
  14352. return 0;
  14353. });
  14354. };
  14355. /**
  14356. * Add a mesh as LOD level triggered at the given distance.
  14357. * @param {number} distance - the distance from the center of the object to show this level
  14358. * @param {Mesh} mesh - the mesh to be added as LOD level
  14359. * @return {Mesh} this mesh (for chaining)
  14360. */
  14361. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14362. if (mesh && mesh._masterMesh) {
  14363. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14364. return this;
  14365. }
  14366. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14367. this._LODLevels.push(level);
  14368. if (mesh) {
  14369. mesh._masterMesh = this;
  14370. }
  14371. this._sortLODLevels();
  14372. return this;
  14373. };
  14374. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14375. for (var index = 0; index < this._LODLevels.length; index++) {
  14376. var level = this._LODLevels[index];
  14377. if (level.distance === distance) {
  14378. return level.mesh;
  14379. }
  14380. }
  14381. return null;
  14382. };
  14383. /**
  14384. * Remove a mesh from the LOD array
  14385. * @param {Mesh} mesh - the mesh to be removed.
  14386. * @return {Mesh} this mesh (for chaining)
  14387. */
  14388. Mesh.prototype.removeLODLevel = function (mesh) {
  14389. for (var index = 0; index < this._LODLevels.length; index++) {
  14390. if (this._LODLevels[index].mesh === mesh) {
  14391. this._LODLevels.splice(index, 1);
  14392. if (mesh) {
  14393. mesh._masterMesh = null;
  14394. }
  14395. }
  14396. }
  14397. this._sortLODLevels();
  14398. return this;
  14399. };
  14400. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14401. if (!this._LODLevels || this._LODLevels.length === 0) {
  14402. return this;
  14403. }
  14404. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14405. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14406. if (this.onLODLevelSelection) {
  14407. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14408. }
  14409. return this;
  14410. }
  14411. for (var index = 0; index < this._LODLevels.length; index++) {
  14412. var level = this._LODLevels[index];
  14413. if (level.distance < distanceToCamera) {
  14414. if (level.mesh) {
  14415. level.mesh._preActivate();
  14416. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14417. }
  14418. if (this.onLODLevelSelection) {
  14419. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14420. }
  14421. return level.mesh;
  14422. }
  14423. }
  14424. if (this.onLODLevelSelection) {
  14425. this.onLODLevelSelection(distanceToCamera, this, this);
  14426. }
  14427. return this;
  14428. };
  14429. Object.defineProperty(Mesh.prototype, "geometry", {
  14430. get: function () {
  14431. return this._geometry;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Mesh.prototype.getTotalVertices = function () {
  14437. if (!this._geometry) {
  14438. return 0;
  14439. }
  14440. return this._geometry.getTotalVertices();
  14441. };
  14442. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14443. if (!this._geometry) {
  14444. return null;
  14445. }
  14446. return this._geometry.getVerticesData(kind, copyWhenShared);
  14447. };
  14448. Mesh.prototype.getVertexBuffer = function (kind) {
  14449. if (!this._geometry) {
  14450. return undefined;
  14451. }
  14452. return this._geometry.getVertexBuffer(kind);
  14453. };
  14454. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14455. if (!this._geometry) {
  14456. if (this._delayInfo) {
  14457. return this._delayInfo.indexOf(kind) !== -1;
  14458. }
  14459. return false;
  14460. }
  14461. return this._geometry.isVerticesDataPresent(kind);
  14462. };
  14463. Mesh.prototype.getVerticesDataKinds = function () {
  14464. if (!this._geometry) {
  14465. var result = [];
  14466. if (this._delayInfo) {
  14467. for (var kind in this._delayInfo) {
  14468. result.push(kind);
  14469. }
  14470. }
  14471. return result;
  14472. }
  14473. return this._geometry.getVerticesDataKinds();
  14474. };
  14475. Mesh.prototype.getTotalIndices = function () {
  14476. if (!this._geometry) {
  14477. return 0;
  14478. }
  14479. return this._geometry.getTotalIndices();
  14480. };
  14481. Mesh.prototype.getIndices = function (copyWhenShared) {
  14482. if (!this._geometry) {
  14483. return [];
  14484. }
  14485. return this._geometry.getIndices(copyWhenShared);
  14486. };
  14487. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14488. get: function () {
  14489. return this._masterMesh !== null && this._masterMesh !== undefined;
  14490. },
  14491. enumerable: true,
  14492. configurable: true
  14493. });
  14494. Mesh.prototype.isReady = function () {
  14495. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14496. return false;
  14497. }
  14498. return _super.prototype.isReady.call(this);
  14499. };
  14500. Mesh.prototype.isDisposed = function () {
  14501. return this._isDisposed;
  14502. };
  14503. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14504. get: function () {
  14505. return this._sideOrientation;
  14506. },
  14507. set: function (sideO) {
  14508. this._sideOrientation = sideO;
  14509. },
  14510. enumerable: true,
  14511. configurable: true
  14512. });
  14513. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14514. get: function () {
  14515. return this._areNormalsFrozen;
  14516. },
  14517. enumerable: true,
  14518. configurable: true
  14519. });
  14520. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14521. Mesh.prototype.freezeNormals = function () {
  14522. this._areNormalsFrozen = true;
  14523. };
  14524. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14525. Mesh.prototype.unfreezeNormals = function () {
  14526. this._areNormalsFrozen = false;
  14527. };
  14528. // Methods
  14529. Mesh.prototype._preActivate = function () {
  14530. var sceneRenderId = this.getScene().getRenderId();
  14531. if (this._preActivateId === sceneRenderId) {
  14532. return;
  14533. }
  14534. this._preActivateId = sceneRenderId;
  14535. this._visibleInstances = null;
  14536. };
  14537. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14538. if (!this._visibleInstances) {
  14539. this._visibleInstances = {};
  14540. this._visibleInstances.defaultRenderId = renderId;
  14541. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14542. }
  14543. if (!this._visibleInstances[renderId]) {
  14544. this._visibleInstances[renderId] = new Array();
  14545. }
  14546. this._visibleInstances[renderId].push(instance);
  14547. };
  14548. Mesh.prototype.refreshBoundingInfo = function () {
  14549. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14550. if (data) {
  14551. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14552. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14553. }
  14554. if (this.subMeshes) {
  14555. for (var index = 0; index < this.subMeshes.length; index++) {
  14556. this.subMeshes[index].refreshBoundingInfo();
  14557. }
  14558. }
  14559. this._updateBoundingInfo();
  14560. };
  14561. Mesh.prototype._createGlobalSubMesh = function () {
  14562. var totalVertices = this.getTotalVertices();
  14563. if (!totalVertices || !this.getIndices()) {
  14564. return null;
  14565. }
  14566. this.releaseSubMeshes();
  14567. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14568. };
  14569. Mesh.prototype.subdivide = function (count) {
  14570. if (count < 1) {
  14571. return;
  14572. }
  14573. var totalIndices = this.getTotalIndices();
  14574. var subdivisionSize = (totalIndices / count) | 0;
  14575. var offset = 0;
  14576. // Ensure that subdivisionSize is a multiple of 3
  14577. while (subdivisionSize % 3 !== 0) {
  14578. subdivisionSize++;
  14579. }
  14580. this.releaseSubMeshes();
  14581. for (var index = 0; index < count; index++) {
  14582. if (offset >= totalIndices) {
  14583. break;
  14584. }
  14585. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14586. offset += subdivisionSize;
  14587. }
  14588. this.synchronizeInstances();
  14589. };
  14590. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14591. if (!this._geometry) {
  14592. var vertexData = new BABYLON.VertexData();
  14593. vertexData.set(data, kind);
  14594. var scene = this.getScene();
  14595. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14596. }
  14597. else {
  14598. this._geometry.setVerticesData(kind, data, updatable, stride);
  14599. }
  14600. };
  14601. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14602. if (!this._geometry) {
  14603. return;
  14604. }
  14605. if (!makeItUnique) {
  14606. this._geometry.updateVerticesData(kind, data, updateExtends);
  14607. }
  14608. else {
  14609. this.makeGeometryUnique();
  14610. this.updateVerticesData(kind, data, updateExtends, false);
  14611. }
  14612. };
  14613. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14614. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14615. if (!this._geometry) {
  14616. return;
  14617. }
  14618. if (!makeItUnique) {
  14619. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14620. }
  14621. else {
  14622. this.makeGeometryUnique();
  14623. this.updateVerticesDataDirectly(kind, data, offset, false);
  14624. }
  14625. };
  14626. // Mesh positions update function :
  14627. // updates the mesh positions according to the positionFunction returned values.
  14628. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14629. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14630. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14631. if (computeNormals === void 0) { computeNormals = true; }
  14632. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14633. positionFunction(positions);
  14634. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14635. if (computeNormals) {
  14636. var indices = this.getIndices();
  14637. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14638. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14639. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14640. }
  14641. };
  14642. Mesh.prototype.makeGeometryUnique = function () {
  14643. if (!this._geometry) {
  14644. return;
  14645. }
  14646. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14647. geometry.applyToMesh(this);
  14648. };
  14649. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14650. if (!this._geometry) {
  14651. var vertexData = new BABYLON.VertexData();
  14652. vertexData.indices = indices;
  14653. var scene = this.getScene();
  14654. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14655. }
  14656. else {
  14657. this._geometry.setIndices(indices, totalVertices);
  14658. }
  14659. };
  14660. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14661. var engine = this.getScene().getEngine();
  14662. // Wireframe
  14663. var indexToBind;
  14664. switch (fillMode) {
  14665. case BABYLON.Material.PointFillMode:
  14666. indexToBind = null;
  14667. break;
  14668. case BABYLON.Material.WireFrameFillMode:
  14669. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14670. break;
  14671. default:
  14672. case BABYLON.Material.TriangleFillMode:
  14673. indexToBind = this._geometry.getIndexBuffer();
  14674. break;
  14675. }
  14676. // VBOs
  14677. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14678. };
  14679. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14680. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14681. return;
  14682. }
  14683. var engine = this.getScene().getEngine();
  14684. // Draw order
  14685. switch (fillMode) {
  14686. case BABYLON.Material.PointFillMode:
  14687. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14688. break;
  14689. case BABYLON.Material.WireFrameFillMode:
  14690. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14691. break;
  14692. default:
  14693. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14694. }
  14695. };
  14696. Mesh.prototype.registerBeforeRender = function (func) {
  14697. this._onBeforeRenderCallbacks.push(func);
  14698. };
  14699. Mesh.prototype.unregisterBeforeRender = function (func) {
  14700. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14701. if (index > -1) {
  14702. this._onBeforeRenderCallbacks.splice(index, 1);
  14703. }
  14704. };
  14705. Mesh.prototype.registerAfterRender = function (func) {
  14706. this._onAfterRenderCallbacks.push(func);
  14707. };
  14708. Mesh.prototype.unregisterAfterRender = function (func) {
  14709. var index = this._onAfterRenderCallbacks.indexOf(func);
  14710. if (index > -1) {
  14711. this._onAfterRenderCallbacks.splice(index, 1);
  14712. }
  14713. };
  14714. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14715. var scene = this.getScene();
  14716. this._batchCache.mustReturn = false;
  14717. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14718. this._batchCache.visibleInstances[subMeshId] = null;
  14719. if (this._visibleInstances) {
  14720. var currentRenderId = scene.getRenderId();
  14721. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14722. var selfRenderId = this._renderId;
  14723. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14724. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14725. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14726. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14727. }
  14728. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14729. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14730. this._batchCache.mustReturn = true;
  14731. return this._batchCache;
  14732. }
  14733. if (currentRenderId !== selfRenderId) {
  14734. this._batchCache.renderSelf[subMeshId] = false;
  14735. }
  14736. }
  14737. this._renderIdForInstances[subMeshId] = currentRenderId;
  14738. }
  14739. return this._batchCache;
  14740. };
  14741. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14742. var visibleInstances = batch.visibleInstances[subMesh._id];
  14743. var matricesCount = visibleInstances.length + 1;
  14744. var bufferSize = matricesCount * 16 * 4;
  14745. while (this._instancesBufferSize < bufferSize) {
  14746. this._instancesBufferSize *= 2;
  14747. }
  14748. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14749. if (this._worldMatricesInstancesBuffer) {
  14750. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14751. }
  14752. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14753. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14754. }
  14755. var offset = 0;
  14756. var instancesCount = 0;
  14757. var world = this.getWorldMatrix();
  14758. if (batch.renderSelf[subMesh._id]) {
  14759. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14760. offset += 16;
  14761. instancesCount++;
  14762. }
  14763. if (visibleInstances) {
  14764. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14765. var instance = visibleInstances[instanceIndex];
  14766. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14767. offset += 16;
  14768. instancesCount++;
  14769. }
  14770. }
  14771. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14772. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14773. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14774. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14775. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14776. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14777. this._draw(subMesh, fillMode, instancesCount);
  14778. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14779. };
  14780. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14781. var scene = this.getScene();
  14782. var engine = scene.getEngine();
  14783. if (hardwareInstancedRendering) {
  14784. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14785. }
  14786. else {
  14787. if (batch.renderSelf[subMesh._id]) {
  14788. // Draw
  14789. if (onBeforeDraw) {
  14790. onBeforeDraw(false, this.getWorldMatrix());
  14791. }
  14792. this._draw(subMesh, fillMode);
  14793. }
  14794. if (batch.visibleInstances[subMesh._id]) {
  14795. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14796. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14797. // World
  14798. var world = instance.getWorldMatrix();
  14799. if (onBeforeDraw) {
  14800. onBeforeDraw(true, world);
  14801. }
  14802. // Draw
  14803. this._draw(subMesh, fillMode);
  14804. }
  14805. }
  14806. }
  14807. };
  14808. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14809. var scene = this.getScene();
  14810. // Managing instances
  14811. var batch = this._getInstancesRenderList(subMesh._id);
  14812. if (batch.mustReturn) {
  14813. return;
  14814. }
  14815. // Checking geometry state
  14816. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14817. return;
  14818. }
  14819. var callbackIndex;
  14820. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14821. this._onBeforeRenderCallbacks[callbackIndex](this);
  14822. }
  14823. var engine = scene.getEngine();
  14824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14825. // Material
  14826. var effectiveMaterial = subMesh.getMaterial();
  14827. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14828. return;
  14829. }
  14830. // Outline - step 1
  14831. var savedDepthWrite = engine.getDepthWrite();
  14832. if (this.renderOutline) {
  14833. engine.setDepthWrite(false);
  14834. scene.getOutlineRenderer().render(subMesh, batch);
  14835. engine.setDepthWrite(savedDepthWrite);
  14836. }
  14837. effectiveMaterial._preBind();
  14838. var effect = effectiveMaterial.getEffect();
  14839. // Bind
  14840. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14841. this._bind(subMesh, effect, fillMode);
  14842. var world = this.getWorldMatrix();
  14843. effectiveMaterial.bind(world, this);
  14844. // Alpha mode
  14845. if (enableAlphaMode) {
  14846. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14847. }
  14848. // Draw
  14849. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14850. if (isInstance) {
  14851. effectiveMaterial.bindOnlyWorldMatrix(world);
  14852. }
  14853. });
  14854. // Unbind
  14855. effectiveMaterial.unbind();
  14856. // Outline - step 2
  14857. if (this.renderOutline && savedDepthWrite) {
  14858. engine.setDepthWrite(true);
  14859. engine.setColorWrite(false);
  14860. scene.getOutlineRenderer().render(subMesh, batch);
  14861. engine.setColorWrite(true);
  14862. }
  14863. // Overlay
  14864. if (this.renderOverlay) {
  14865. var currentMode = engine.getAlphaMode();
  14866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14867. scene.getOutlineRenderer().render(subMesh, batch, true);
  14868. engine.setAlphaMode(currentMode);
  14869. }
  14870. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14871. this._onAfterRenderCallbacks[callbackIndex](this);
  14872. }
  14873. };
  14874. Mesh.prototype.getEmittedParticleSystems = function () {
  14875. var results = new Array();
  14876. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14877. var particleSystem = this.getScene().particleSystems[index];
  14878. if (particleSystem.emitter === this) {
  14879. results.push(particleSystem);
  14880. }
  14881. }
  14882. return results;
  14883. };
  14884. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14885. var results = new Array();
  14886. var descendants = this.getDescendants();
  14887. descendants.push(this);
  14888. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14889. var particleSystem = this.getScene().particleSystems[index];
  14890. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14891. results.push(particleSystem);
  14892. }
  14893. }
  14894. return results;
  14895. };
  14896. Mesh.prototype.getChildren = function () {
  14897. var results = [];
  14898. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14899. var mesh = this.getScene().meshes[index];
  14900. if (mesh.parent === this) {
  14901. results.push(mesh);
  14902. }
  14903. }
  14904. return results;
  14905. };
  14906. Mesh.prototype._checkDelayState = function () {
  14907. var _this = this;
  14908. var that = this;
  14909. var scene = this.getScene();
  14910. if (this._geometry) {
  14911. this._geometry.load(scene);
  14912. }
  14913. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14914. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14915. scene._addPendingData(that);
  14916. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14917. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14918. if (data instanceof ArrayBuffer) {
  14919. _this._delayLoadingFunction(data, _this);
  14920. }
  14921. else {
  14922. _this._delayLoadingFunction(JSON.parse(data), _this);
  14923. }
  14924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14925. scene._removePendingData(_this);
  14926. }, function () { }, scene.database, getBinaryData);
  14927. }
  14928. };
  14929. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14930. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14931. return false;
  14932. }
  14933. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14934. return false;
  14935. }
  14936. this._checkDelayState();
  14937. return true;
  14938. };
  14939. Mesh.prototype.setMaterialByID = function (id) {
  14940. var materials = this.getScene().materials;
  14941. var index;
  14942. for (index = 0; index < materials.length; index++) {
  14943. if (materials[index].id === id) {
  14944. this.material = materials[index];
  14945. return;
  14946. }
  14947. }
  14948. // Multi
  14949. var multiMaterials = this.getScene().multiMaterials;
  14950. for (index = 0; index < multiMaterials.length; index++) {
  14951. if (multiMaterials[index].id === id) {
  14952. this.material = multiMaterials[index];
  14953. return;
  14954. }
  14955. }
  14956. };
  14957. Mesh.prototype.getAnimatables = function () {
  14958. var results = [];
  14959. if (this.material) {
  14960. results.push(this.material);
  14961. }
  14962. if (this.skeleton) {
  14963. results.push(this.skeleton);
  14964. }
  14965. return results;
  14966. };
  14967. // Geometry
  14968. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14969. // Position
  14970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14971. return;
  14972. }
  14973. this._resetPointsArrayCache();
  14974. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14975. var temp = [];
  14976. var index;
  14977. for (index = 0; index < data.length; index += 3) {
  14978. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14979. }
  14980. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14981. // Normals
  14982. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14983. return;
  14984. }
  14985. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14986. temp = [];
  14987. for (index = 0; index < data.length; index += 3) {
  14988. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14989. }
  14990. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14991. // flip faces?
  14992. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14993. this.flipFaces();
  14994. }
  14995. };
  14996. // Will apply current transform to mesh and reset world matrix
  14997. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14998. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14999. this.scaling.copyFromFloats(1, 1, 1);
  15000. this.position.copyFromFloats(0, 0, 0);
  15001. this.rotation.copyFromFloats(0, 0, 0);
  15002. //only if quaternion is already set
  15003. if (this.rotationQuaternion) {
  15004. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15005. }
  15006. this._worldMatrix = BABYLON.Matrix.Identity();
  15007. };
  15008. // Cache
  15009. Mesh.prototype._resetPointsArrayCache = function () {
  15010. this._positions = null;
  15011. };
  15012. Mesh.prototype._generatePointsArray = function () {
  15013. if (this._positions)
  15014. return true;
  15015. this._positions = [];
  15016. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15017. if (!data) {
  15018. return false;
  15019. }
  15020. for (var index = 0; index < data.length; index += 3) {
  15021. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15022. }
  15023. return true;
  15024. };
  15025. // Clone
  15026. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15027. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15028. };
  15029. // Dispose
  15030. Mesh.prototype.dispose = function (doNotRecurse) {
  15031. if (this._geometry) {
  15032. this._geometry.releaseForMesh(this, true);
  15033. }
  15034. // Instances
  15035. if (this._worldMatricesInstancesBuffer) {
  15036. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15037. this._worldMatricesInstancesBuffer = null;
  15038. }
  15039. while (this.instances.length) {
  15040. this.instances[0].dispose();
  15041. }
  15042. _super.prototype.dispose.call(this, doNotRecurse);
  15043. };
  15044. // Geometric tools
  15045. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15046. var _this = this;
  15047. var scene = this.getScene();
  15048. var onload = function (img) {
  15049. // Getting height map data
  15050. var canvas = document.createElement("canvas");
  15051. var context = canvas.getContext("2d");
  15052. var heightMapWidth = img.width;
  15053. var heightMapHeight = img.height;
  15054. canvas.width = heightMapWidth;
  15055. canvas.height = heightMapHeight;
  15056. context.drawImage(img, 0, 0);
  15057. // Create VertexData from map data
  15058. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15059. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15060. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15061. //execute success callback, if set
  15062. if (onSuccess) {
  15063. onSuccess(_this);
  15064. }
  15065. };
  15066. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15067. };
  15068. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15069. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15070. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15071. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15072. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15073. return;
  15074. }
  15075. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15076. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15077. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15078. var position = BABYLON.Vector3.Zero();
  15079. var normal = BABYLON.Vector3.Zero();
  15080. var uv = BABYLON.Vector2.Zero();
  15081. for (var index = 0; index < positions.length; index += 3) {
  15082. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15083. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15084. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15085. // Compute height
  15086. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15087. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15088. var pos = (u + v * heightMapWidth) * 4;
  15089. var r = buffer[pos] / 255.0;
  15090. var g = buffer[pos + 1] / 255.0;
  15091. var b = buffer[pos + 2] / 255.0;
  15092. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15093. normal.normalize();
  15094. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15095. position = position.add(normal);
  15096. position.toArray(positions, index);
  15097. }
  15098. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15099. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15100. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15101. };
  15102. Mesh.prototype.convertToFlatShadedMesh = function () {
  15103. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15104. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15105. var kinds = this.getVerticesDataKinds();
  15106. var vbs = [];
  15107. var data = [];
  15108. var newdata = [];
  15109. var updatableNormals = false;
  15110. var kindIndex;
  15111. var kind;
  15112. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15113. kind = kinds[kindIndex];
  15114. var vertexBuffer = this.getVertexBuffer(kind);
  15115. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15116. updatableNormals = vertexBuffer.isUpdatable();
  15117. kinds.splice(kindIndex, 1);
  15118. kindIndex--;
  15119. continue;
  15120. }
  15121. vbs[kind] = vertexBuffer;
  15122. data[kind] = vbs[kind].getData();
  15123. newdata[kind] = [];
  15124. }
  15125. // Save previous submeshes
  15126. var previousSubmeshes = this.subMeshes.slice(0);
  15127. var indices = this.getIndices();
  15128. var totalIndices = this.getTotalIndices();
  15129. // Generating unique vertices per face
  15130. var index;
  15131. for (index = 0; index < totalIndices; index++) {
  15132. var vertexIndex = indices[index];
  15133. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15134. kind = kinds[kindIndex];
  15135. var stride = vbs[kind].getStrideSize();
  15136. for (var offset = 0; offset < stride; offset++) {
  15137. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15138. }
  15139. }
  15140. }
  15141. // Updating faces & normal
  15142. var normals = [];
  15143. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15144. for (index = 0; index < totalIndices; index += 3) {
  15145. indices[index] = index;
  15146. indices[index + 1] = index + 1;
  15147. indices[index + 2] = index + 2;
  15148. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15149. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15150. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15151. var p1p2 = p1.subtract(p2);
  15152. var p3p2 = p3.subtract(p2);
  15153. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15154. // Store same normals for every vertex
  15155. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15156. normals.push(normal.x);
  15157. normals.push(normal.y);
  15158. normals.push(normal.z);
  15159. }
  15160. }
  15161. this.setIndices(indices);
  15162. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15163. // Updating vertex buffers
  15164. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15165. kind = kinds[kindIndex];
  15166. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15167. }
  15168. // Updating submeshes
  15169. this.releaseSubMeshes();
  15170. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15171. var previousOne = previousSubmeshes[submeshIndex];
  15172. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15173. }
  15174. this.synchronizeInstances();
  15175. };
  15176. // will inverse faces orientations, and invert normals too if specified
  15177. Mesh.prototype.flipFaces = function (flipNormals) {
  15178. if (flipNormals === void 0) { flipNormals = false; }
  15179. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15180. var i;
  15181. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15182. for (i = 0; i < vertex_data.normals.length; i++) {
  15183. vertex_data.normals[i] *= -1;
  15184. }
  15185. }
  15186. var temp;
  15187. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15188. // reassign indices
  15189. temp = vertex_data.indices[i + 1];
  15190. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15191. vertex_data.indices[i + 2] = temp;
  15192. }
  15193. vertex_data.applyToMesh(this);
  15194. };
  15195. // Instances
  15196. Mesh.prototype.createInstance = function (name) {
  15197. return new BABYLON.InstancedMesh(name, this);
  15198. };
  15199. Mesh.prototype.synchronizeInstances = function () {
  15200. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15201. var instance = this.instances[instanceIndex];
  15202. instance._syncSubMeshes();
  15203. }
  15204. };
  15205. /**
  15206. * Simplify the mesh according to the given array of settings.
  15207. * Function will return immediately and will simplify async.
  15208. * @param settings a collection of simplification settings.
  15209. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15210. * @param type the type of simplification to run.
  15211. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15212. */
  15213. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15214. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15215. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15216. this.getScene().simplificationQueue.addTask({
  15217. settings: settings,
  15218. parallelProcessing: parallelProcessing,
  15219. mesh: this,
  15220. simplificationType: simplificationType,
  15221. successCallback: successCallback
  15222. });
  15223. };
  15224. /**
  15225. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15226. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15227. * This should be used together with the simplification to avoid disappearing triangles.
  15228. * @param successCallback an optional success callback to be called after the optimization finished.
  15229. */
  15230. Mesh.prototype.optimizeIndices = function (successCallback) {
  15231. var _this = this;
  15232. var indices = this.getIndices();
  15233. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15234. var vectorPositions = [];
  15235. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15236. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15237. }
  15238. var dupes = [];
  15239. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15240. var realPos = vectorPositions.length - 1 - iteration;
  15241. var testedPosition = vectorPositions[realPos];
  15242. for (var j = 0; j < realPos; ++j) {
  15243. var againstPosition = vectorPositions[j];
  15244. if (testedPosition.equals(againstPosition)) {
  15245. dupes[realPos] = j;
  15246. break;
  15247. }
  15248. }
  15249. }, function () {
  15250. for (var i = 0; i < indices.length; ++i) {
  15251. indices[i] = dupes[indices[i]] || indices[i];
  15252. }
  15253. //indices are now reordered
  15254. var originalSubMeshes = _this.subMeshes.slice(0);
  15255. _this.setIndices(indices);
  15256. _this.subMeshes = originalSubMeshes;
  15257. if (successCallback) {
  15258. successCallback(_this);
  15259. }
  15260. });
  15261. };
  15262. // Statics
  15263. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15264. var mesh = new Mesh(parsedMesh.name, scene);
  15265. mesh.id = parsedMesh.id;
  15266. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15267. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15268. if (parsedMesh.rotationQuaternion) {
  15269. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15270. }
  15271. else if (parsedMesh.rotation) {
  15272. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15273. }
  15274. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15275. if (parsedMesh.localMatrix) {
  15276. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15277. }
  15278. else if (parsedMesh.pivotMatrix) {
  15279. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15280. }
  15281. mesh.setEnabled(parsedMesh.isEnabled);
  15282. mesh.isVisible = parsedMesh.isVisible;
  15283. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15284. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15285. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15286. if (parsedMesh.applyFog !== undefined) {
  15287. mesh.applyFog = parsedMesh.applyFog;
  15288. }
  15289. if (parsedMesh.pickable !== undefined) {
  15290. mesh.isPickable = parsedMesh.pickable;
  15291. }
  15292. if (parsedMesh.alphaIndex !== undefined) {
  15293. mesh.alphaIndex = parsedMesh.alphaIndex;
  15294. }
  15295. mesh.receiveShadows = parsedMesh.receiveShadows;
  15296. mesh.billboardMode = parsedMesh.billboardMode;
  15297. if (parsedMesh.visibility !== undefined) {
  15298. mesh.visibility = parsedMesh.visibility;
  15299. }
  15300. mesh.checkCollisions = parsedMesh.checkCollisions;
  15301. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15302. // freezeWorldMatrix
  15303. if (parsedMesh.freezeWorldMatrix) {
  15304. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15305. }
  15306. // Parent
  15307. if (parsedMesh.parentId) {
  15308. mesh._waitingParentId = parsedMesh.parentId;
  15309. }
  15310. // Actions
  15311. if (parsedMesh.actions !== undefined) {
  15312. mesh._waitingActions = parsedMesh.actions;
  15313. }
  15314. // Geometry
  15315. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15316. if (parsedMesh.delayLoadingFile) {
  15317. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15318. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15319. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15320. if (parsedMesh._binaryInfo) {
  15321. mesh._binaryInfo = parsedMesh._binaryInfo;
  15322. }
  15323. mesh._delayInfo = [];
  15324. if (parsedMesh.hasUVs) {
  15325. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15326. }
  15327. if (parsedMesh.hasUVs2) {
  15328. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15329. }
  15330. if (parsedMesh.hasUVs3) {
  15331. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15332. }
  15333. if (parsedMesh.hasUVs4) {
  15334. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15335. }
  15336. if (parsedMesh.hasUVs5) {
  15337. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15338. }
  15339. if (parsedMesh.hasUVs6) {
  15340. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15341. }
  15342. if (parsedMesh.hasColors) {
  15343. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15344. }
  15345. if (parsedMesh.hasMatricesIndices) {
  15346. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15347. }
  15348. if (parsedMesh.hasMatricesWeights) {
  15349. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15350. }
  15351. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15352. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15353. mesh._checkDelayState();
  15354. }
  15355. }
  15356. else {
  15357. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15358. }
  15359. // Material
  15360. if (parsedMesh.materialId) {
  15361. mesh.setMaterialByID(parsedMesh.materialId);
  15362. }
  15363. else {
  15364. mesh.material = null;
  15365. }
  15366. // Skeleton
  15367. if (parsedMesh.skeletonId > -1) {
  15368. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15369. if (parsedMesh.numBoneInfluencers) {
  15370. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15371. }
  15372. }
  15373. // Physics
  15374. if (parsedMesh.physicsImpostor) {
  15375. if (!scene.isPhysicsEnabled()) {
  15376. scene.enablePhysics();
  15377. }
  15378. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15379. }
  15380. // Animations
  15381. if (parsedMesh.animations) {
  15382. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15383. var parsedAnimation = parsedMesh.animations[animationIndex];
  15384. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15385. }
  15386. }
  15387. if (parsedMesh.autoAnimate) {
  15388. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15389. }
  15390. // Layer Mask
  15391. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15392. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15393. }
  15394. else {
  15395. mesh.layerMask = 0x0FFFFFFF;
  15396. }
  15397. // Instances
  15398. if (parsedMesh.instances) {
  15399. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15400. var parsedInstance = parsedMesh.instances[index];
  15401. var instance = mesh.createInstance(parsedInstance.name);
  15402. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15403. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15404. if (parsedInstance.rotationQuaternion) {
  15405. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15406. }
  15407. else if (parsedInstance.rotation) {
  15408. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15409. }
  15410. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15411. instance.checkCollisions = mesh.checkCollisions;
  15412. if (parsedMesh.animations) {
  15413. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15414. parsedAnimation = parsedMesh.animations[animationIndex];
  15415. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15416. }
  15417. }
  15418. }
  15419. }
  15420. return mesh;
  15421. };
  15422. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15423. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15424. pathArray: pathArray,
  15425. closeArray: closeArray,
  15426. closePath: closePath,
  15427. offset: offset,
  15428. updatable: updatable,
  15429. sideOrientation: sideOrientation,
  15430. instance: instance
  15431. }, scene);
  15432. };
  15433. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15434. var options = {
  15435. radius: radius,
  15436. tessellation: tessellation,
  15437. sideOrientation: sideOrientation,
  15438. updatable: updatable
  15439. };
  15440. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15441. };
  15442. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15443. var options = {
  15444. size: size,
  15445. sideOrientation: sideOrientation,
  15446. updatable: updatable
  15447. };
  15448. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15449. };
  15450. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15451. var options = {
  15452. segments: segments,
  15453. diameterX: diameter,
  15454. diameterY: diameter,
  15455. diameterZ: diameter,
  15456. sideOrientation: sideOrientation,
  15457. updatable: updatable
  15458. };
  15459. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15460. };
  15461. // Cylinder and cone
  15462. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15463. var options = {
  15464. height: height,
  15465. diameterTop: diameterTop,
  15466. diameterBottom: diameterBottom,
  15467. tessellation: tessellation,
  15468. subdivisions: subdivisions,
  15469. sideOrientation: sideOrientation,
  15470. updatable: updatable
  15471. };
  15472. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15473. };
  15474. // Torus (Code from SharpDX.org)
  15475. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15476. var options = {
  15477. diameter: diameter,
  15478. thickness: thickness,
  15479. tessellation: tessellation,
  15480. sideOrientation: sideOrientation,
  15481. updatable: updatable
  15482. };
  15483. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15484. };
  15485. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15486. var options = {
  15487. radius: radius,
  15488. tube: tube,
  15489. radialSegments: radialSegments,
  15490. tubularSegments: tubularSegments,
  15491. p: p,
  15492. q: q,
  15493. sideOrientation: sideOrientation,
  15494. updatable: updatable
  15495. };
  15496. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15497. };
  15498. // Lines
  15499. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15500. var options = {
  15501. points: points,
  15502. updatable: updatable,
  15503. instance: instance
  15504. };
  15505. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15506. };
  15507. // Dashed Lines
  15508. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15509. var options = {
  15510. points: points,
  15511. dashSize: dashSize,
  15512. gapSize: gapSize,
  15513. dashNb: dashNb,
  15514. updatable: updatable
  15515. };
  15516. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15517. };
  15518. // Extrusion
  15519. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15520. var options = {
  15521. shape: shape,
  15522. path: path,
  15523. scale: scale,
  15524. rotation: rotation,
  15525. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15526. sideOrientation: sideOrientation,
  15527. instance: instance,
  15528. updatable: updatable
  15529. };
  15530. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15531. };
  15532. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15533. var options = {
  15534. shape: shape,
  15535. path: path,
  15536. scaleFunction: scaleFunction,
  15537. rotationFunction: rotationFunction,
  15538. ribbonCloseArray: ribbonCloseArray,
  15539. ribbonClosePath: ribbonClosePath,
  15540. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15541. sideOrientation: sideOrientation,
  15542. instance: instance,
  15543. updatable: updatable
  15544. };
  15545. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15546. };
  15547. // Lathe
  15548. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15549. var options = {
  15550. shape: shape,
  15551. radius: radius,
  15552. tessellation: tessellation,
  15553. sideOrientation: sideOrientation,
  15554. updatable: updatable
  15555. };
  15556. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15557. };
  15558. // Plane & ground
  15559. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15560. var options = {
  15561. size: size,
  15562. width: size,
  15563. height: size,
  15564. sideOrientation: sideOrientation,
  15565. updatable: updatable
  15566. };
  15567. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15568. };
  15569. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15570. var options = {
  15571. width: width,
  15572. height: height,
  15573. subdivisions: subdivisions,
  15574. updatable: updatable
  15575. };
  15576. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15577. };
  15578. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15579. var options = {
  15580. xmin: xmin,
  15581. zmin: zmin,
  15582. xmax: xmax,
  15583. zmax: zmax,
  15584. subdivisions: subdivisions,
  15585. precision: precision,
  15586. updatable: updatable
  15587. };
  15588. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15589. };
  15590. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15591. var options = {
  15592. width: width,
  15593. height: height,
  15594. subdivisions: subdivisions,
  15595. minHeight: minHeight,
  15596. maxHeight: maxHeight,
  15597. updatable: updatable,
  15598. onReady: onReady
  15599. };
  15600. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15601. };
  15602. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15603. var options = {
  15604. path: path,
  15605. radius: radius,
  15606. tessellation: tessellation,
  15607. radiusFunction: radiusFunction,
  15608. arc: 1,
  15609. cap: cap,
  15610. updatable: updatable,
  15611. sideOrientation: sideOrientation,
  15612. instance: instance
  15613. };
  15614. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15615. };
  15616. Mesh.CreatePolyhedron = function (name, options, scene) {
  15617. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15618. };
  15619. Mesh.CreateIcoSphere = function (name, options, scene) {
  15620. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15621. };
  15622. // Decals
  15623. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15624. var options = {
  15625. position: position,
  15626. normal: normal,
  15627. size: size,
  15628. angle: angle
  15629. };
  15630. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15631. };
  15632. // Skeletons
  15633. /**
  15634. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15635. */
  15636. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15637. var source;
  15638. if (!this._sourcePositions) {
  15639. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15640. this._sourcePositions = new Float32Array(source);
  15641. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15642. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15643. }
  15644. }
  15645. return this._sourcePositions;
  15646. };
  15647. /**
  15648. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15649. */
  15650. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15651. var source;
  15652. if (!this._sourceNormals) {
  15653. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15654. this._sourceNormals = new Float32Array(source);
  15655. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15656. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15657. }
  15658. }
  15659. return this._sourceNormals;
  15660. };
  15661. /**
  15662. * Update the vertex buffers by applying transformation from the bones
  15663. * @param {skeleton} skeleton to apply
  15664. */
  15665. Mesh.prototype.applySkeleton = function (skeleton) {
  15666. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15667. return this;
  15668. }
  15669. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15670. return this;
  15671. }
  15672. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15673. return this;
  15674. }
  15675. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15676. return this;
  15677. }
  15678. if (!this._sourcePositions) {
  15679. this.setPositionsForCPUSkinning();
  15680. }
  15681. if (!this._sourceNormals) {
  15682. this.setNormalsForCPUSkinning();
  15683. }
  15684. // positionsData checks for not being Float32Array will only pass at most once
  15685. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15686. if (!(positionsData instanceof Float32Array)) {
  15687. positionsData = new Float32Array(positionsData);
  15688. }
  15689. // normalsData checks for not being Float32Array will only pass at most once
  15690. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15691. if (!(normalsData instanceof Float32Array)) {
  15692. normalsData = new Float32Array(normalsData);
  15693. }
  15694. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15695. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15696. var needExtras = this.numBoneInfluencers > 4;
  15697. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15698. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15699. var skeletonMatrices = skeleton.getTransformMatrices();
  15700. var tempVector3 = BABYLON.Vector3.Zero();
  15701. var finalMatrix = new BABYLON.Matrix();
  15702. var tempMatrix = new BABYLON.Matrix();
  15703. var matWeightIdx = 0;
  15704. var inf;
  15705. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15706. var weight;
  15707. for (inf = 0; inf < 4; inf++) {
  15708. weight = matricesWeightsData[matWeightIdx + inf];
  15709. if (weight > 0) {
  15710. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15711. finalMatrix.addToSelf(tempMatrix);
  15712. }
  15713. else
  15714. break;
  15715. }
  15716. if (needExtras) {
  15717. for (inf = 0; inf < 4; inf++) {
  15718. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15719. if (weight > 0) {
  15720. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15721. finalMatrix.addToSelf(tempMatrix);
  15722. }
  15723. else
  15724. break;
  15725. }
  15726. }
  15727. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15728. tempVector3.toArray(positionsData, index);
  15729. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15730. tempVector3.toArray(normalsData, index);
  15731. finalMatrix.reset();
  15732. }
  15733. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15734. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15735. return this;
  15736. };
  15737. // Tools
  15738. Mesh.MinMax = function (meshes) {
  15739. var minVector = null;
  15740. var maxVector = null;
  15741. for (var i in meshes) {
  15742. var mesh = meshes[i];
  15743. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15744. if (!minVector) {
  15745. minVector = boundingBox.minimumWorld;
  15746. maxVector = boundingBox.maximumWorld;
  15747. continue;
  15748. }
  15749. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15750. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15751. }
  15752. return {
  15753. min: minVector,
  15754. max: maxVector
  15755. };
  15756. };
  15757. Mesh.Center = function (meshesOrMinMaxVector) {
  15758. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15759. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15760. };
  15761. /**
  15762. * Merge the array of meshes into a single mesh for performance reasons.
  15763. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15764. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15765. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15766. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15767. */
  15768. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15769. if (disposeSource === void 0) { disposeSource = true; }
  15770. var index;
  15771. if (!allow32BitsIndices) {
  15772. var totalVertices = 0;
  15773. // Counting vertices
  15774. for (index = 0; index < meshes.length; index++) {
  15775. if (meshes[index]) {
  15776. totalVertices += meshes[index].getTotalVertices();
  15777. if (totalVertices > 65536) {
  15778. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15779. return null;
  15780. }
  15781. }
  15782. }
  15783. }
  15784. // Merge
  15785. var vertexData;
  15786. var otherVertexData;
  15787. var source;
  15788. for (index = 0; index < meshes.length; index++) {
  15789. if (meshes[index]) {
  15790. meshes[index].computeWorldMatrix(true);
  15791. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15792. otherVertexData.transform(meshes[index].getWorldMatrix());
  15793. if (vertexData) {
  15794. vertexData.merge(otherVertexData);
  15795. }
  15796. else {
  15797. vertexData = otherVertexData;
  15798. source = meshes[index];
  15799. }
  15800. }
  15801. }
  15802. if (!meshSubclass) {
  15803. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15804. }
  15805. vertexData.applyToMesh(meshSubclass);
  15806. // Setting properties
  15807. meshSubclass.material = source.material;
  15808. meshSubclass.checkCollisions = source.checkCollisions;
  15809. // Cleaning
  15810. if (disposeSource) {
  15811. for (index = 0; index < meshes.length; index++) {
  15812. if (meshes[index]) {
  15813. meshes[index].dispose();
  15814. }
  15815. }
  15816. }
  15817. return meshSubclass;
  15818. };
  15819. // Consts
  15820. Mesh._FRONTSIDE = 0;
  15821. Mesh._BACKSIDE = 1;
  15822. Mesh._DOUBLESIDE = 2;
  15823. Mesh._DEFAULTSIDE = 0;
  15824. Mesh._NO_CAP = 0;
  15825. Mesh._CAP_START = 1;
  15826. Mesh._CAP_END = 2;
  15827. Mesh._CAP_ALL = 3;
  15828. return Mesh;
  15829. })(BABYLON.AbstractMesh);
  15830. BABYLON.Mesh = Mesh;
  15831. })(BABYLON || (BABYLON = {}));
  15832. var BABYLON;
  15833. (function (BABYLON) {
  15834. var SubMesh = (function () {
  15835. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15836. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15837. this.materialIndex = materialIndex;
  15838. this.verticesStart = verticesStart;
  15839. this.verticesCount = verticesCount;
  15840. this.indexStart = indexStart;
  15841. this.indexCount = indexCount;
  15842. this._renderId = 0;
  15843. this._mesh = mesh;
  15844. this._renderingMesh = renderingMesh || mesh;
  15845. mesh.subMeshes.push(this);
  15846. this._trianglePlanes = [];
  15847. this._id = mesh.subMeshes.length - 1;
  15848. if (createBoundingBox) {
  15849. this.refreshBoundingInfo();
  15850. mesh.computeWorldMatrix(true);
  15851. }
  15852. }
  15853. SubMesh.prototype.getBoundingInfo = function () {
  15854. return this._boundingInfo;
  15855. };
  15856. SubMesh.prototype.getMesh = function () {
  15857. return this._mesh;
  15858. };
  15859. SubMesh.prototype.getRenderingMesh = function () {
  15860. return this._renderingMesh;
  15861. };
  15862. SubMesh.prototype.getMaterial = function () {
  15863. var rootMaterial = this._renderingMesh.material;
  15864. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15865. var multiMaterial = rootMaterial;
  15866. return multiMaterial.getSubMaterial(this.materialIndex);
  15867. }
  15868. if (!rootMaterial) {
  15869. return this._mesh.getScene().defaultMaterial;
  15870. }
  15871. return rootMaterial;
  15872. };
  15873. // Methods
  15874. SubMesh.prototype.refreshBoundingInfo = function () {
  15875. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15876. if (!data) {
  15877. this._boundingInfo = this._mesh._boundingInfo;
  15878. return;
  15879. }
  15880. var indices = this._renderingMesh.getIndices();
  15881. var extend;
  15882. //is this the only submesh?
  15883. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15884. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15885. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15886. }
  15887. else {
  15888. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15889. }
  15890. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15891. };
  15892. SubMesh.prototype._checkCollision = function (collider) {
  15893. return this._boundingInfo._checkCollision(collider);
  15894. };
  15895. SubMesh.prototype.updateBoundingInfo = function (world) {
  15896. if (!this._boundingInfo) {
  15897. this.refreshBoundingInfo();
  15898. }
  15899. this._boundingInfo._update(world);
  15900. };
  15901. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15902. return this._boundingInfo.isInFrustum(frustumPlanes);
  15903. };
  15904. SubMesh.prototype.render = function (enableAlphaMode) {
  15905. this._renderingMesh.render(this, enableAlphaMode);
  15906. };
  15907. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15908. if (!this._linesIndexBuffer) {
  15909. var linesIndices = [];
  15910. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15911. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15912. }
  15913. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15914. this.linesIndexCount = linesIndices.length;
  15915. }
  15916. return this._linesIndexBuffer;
  15917. };
  15918. SubMesh.prototype.canIntersects = function (ray) {
  15919. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15920. };
  15921. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15922. var intersectInfo = null;
  15923. // Triangles test
  15924. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15925. var p0 = positions[indices[index]];
  15926. var p1 = positions[indices[index + 1]];
  15927. var p2 = positions[indices[index + 2]];
  15928. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15929. if (currentIntersectInfo) {
  15930. if (currentIntersectInfo.distance < 0) {
  15931. continue;
  15932. }
  15933. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15934. intersectInfo = currentIntersectInfo;
  15935. intersectInfo.faceId = index / 3;
  15936. if (fastCheck) {
  15937. break;
  15938. }
  15939. }
  15940. }
  15941. }
  15942. return intersectInfo;
  15943. };
  15944. // Clone
  15945. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15946. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15947. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15948. return result;
  15949. };
  15950. // Dispose
  15951. SubMesh.prototype.dispose = function () {
  15952. if (this._linesIndexBuffer) {
  15953. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15954. this._linesIndexBuffer = null;
  15955. }
  15956. // Remove from mesh
  15957. var index = this._mesh.subMeshes.indexOf(this);
  15958. this._mesh.subMeshes.splice(index, 1);
  15959. };
  15960. // Statics
  15961. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15962. var minVertexIndex = Number.MAX_VALUE;
  15963. var maxVertexIndex = -Number.MAX_VALUE;
  15964. renderingMesh = renderingMesh || mesh;
  15965. var indices = renderingMesh.getIndices();
  15966. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15967. var vertexIndex = indices[index];
  15968. if (vertexIndex < minVertexIndex)
  15969. minVertexIndex = vertexIndex;
  15970. if (vertexIndex > maxVertexIndex)
  15971. maxVertexIndex = vertexIndex;
  15972. }
  15973. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15974. };
  15975. return SubMesh;
  15976. })();
  15977. BABYLON.SubMesh = SubMesh;
  15978. })(BABYLON || (BABYLON = {}));
  15979. var BABYLON;
  15980. (function (BABYLON) {
  15981. var MeshBuilder = (function () {
  15982. function MeshBuilder() {
  15983. }
  15984. MeshBuilder.CreateBox = function (name, options, scene) {
  15985. var box = new BABYLON.Mesh(name, scene);
  15986. var vertexData = BABYLON.VertexData.CreateBox(options);
  15987. vertexData.applyToMesh(box, options.updatable);
  15988. return box;
  15989. };
  15990. MeshBuilder.CreateSphere = function (name, options, scene) {
  15991. var sphere = new BABYLON.Mesh(name, scene);
  15992. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15993. vertexData.applyToMesh(sphere, options.updatable);
  15994. return sphere;
  15995. };
  15996. MeshBuilder.CreateDisc = function (name, options, scene) {
  15997. var disc = new BABYLON.Mesh(name, scene);
  15998. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15999. vertexData.applyToMesh(disc, options.updatable);
  16000. return disc;
  16001. };
  16002. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16003. var sphere = new BABYLON.Mesh(name, scene);
  16004. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16005. vertexData.applyToMesh(sphere, options.updatable);
  16006. return sphere;
  16007. };
  16008. ;
  16009. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16010. var pathArray = options.pathArray;
  16011. var closeArray = options.closeArray;
  16012. var closePath = options.closePath;
  16013. var offset = options.offset;
  16014. var sideOrientation = options.sideOrientation;
  16015. var instance = options.instance;
  16016. var updatable = options.updatable;
  16017. if (instance) {
  16018. // positionFunction : ribbon case
  16019. // only pathArray and sideOrientation parameters are taken into account for positions update
  16020. var positionFunction = function (positions) {
  16021. var minlg = pathArray[0].length;
  16022. var i = 0;
  16023. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16024. for (var si = 1; si <= ns; si++) {
  16025. for (var p = 0; p < pathArray.length; p++) {
  16026. var path = pathArray[p];
  16027. var l = path.length;
  16028. minlg = (minlg < l) ? minlg : l;
  16029. var j = 0;
  16030. while (j < minlg) {
  16031. positions[i] = path[j].x;
  16032. positions[i + 1] = path[j].y;
  16033. positions[i + 2] = path[j].z;
  16034. j++;
  16035. i += 3;
  16036. }
  16037. if (instance._closePath) {
  16038. positions[i] = path[0].x;
  16039. positions[i + 1] = path[0].y;
  16040. positions[i + 2] = path[0].z;
  16041. i += 3;
  16042. }
  16043. }
  16044. }
  16045. };
  16046. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16047. positionFunction(positions);
  16048. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16049. if (!(instance.areNormalsFrozen)) {
  16050. var indices = instance.getIndices();
  16051. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16052. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16053. if (instance._closePath) {
  16054. var indexFirst = 0;
  16055. var indexLast = 0;
  16056. for (var p = 0; p < pathArray.length; p++) {
  16057. indexFirst = instance._idx[p] * 3;
  16058. if (p + 1 < pathArray.length) {
  16059. indexLast = (instance._idx[p + 1] - 1) * 3;
  16060. }
  16061. else {
  16062. indexLast = normals.length - 3;
  16063. }
  16064. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16065. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16066. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16067. normals[indexLast] = normals[indexFirst];
  16068. normals[indexLast + 1] = normals[indexFirst + 1];
  16069. normals[indexLast + 2] = normals[indexFirst + 2];
  16070. }
  16071. }
  16072. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16073. }
  16074. return instance;
  16075. }
  16076. else {
  16077. var ribbon = new BABYLON.Mesh(name, scene);
  16078. ribbon.sideOrientation = sideOrientation;
  16079. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16080. if (closePath) {
  16081. ribbon._idx = vertexData._idx;
  16082. }
  16083. ribbon._closePath = closePath;
  16084. ribbon._closeArray = closeArray;
  16085. vertexData.applyToMesh(ribbon, updatable);
  16086. return ribbon;
  16087. }
  16088. };
  16089. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16090. var cylinder = new BABYLON.Mesh(name, scene);
  16091. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16092. vertexData.applyToMesh(cylinder, options.updatable);
  16093. return cylinder;
  16094. };
  16095. MeshBuilder.CreateTorus = function (name, options, scene) {
  16096. var torus = new BABYLON.Mesh(name, scene);
  16097. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16098. vertexData.applyToMesh(torus, options.updatable);
  16099. return torus;
  16100. };
  16101. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16102. var torusKnot = new BABYLON.Mesh(name, scene);
  16103. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16104. vertexData.applyToMesh(torusKnot, options.updatable);
  16105. return torusKnot;
  16106. };
  16107. MeshBuilder.CreateLines = function (name, options, scene) {
  16108. var instance = options.instance;
  16109. var points = options.points;
  16110. if (instance) {
  16111. var positionFunction = function (positions) {
  16112. var i = 0;
  16113. for (var p = 0; p < points.length; p++) {
  16114. positions[i] = points[p].x;
  16115. positions[i + 1] = points[p].y;
  16116. positions[i + 2] = points[p].z;
  16117. i += 3;
  16118. }
  16119. };
  16120. instance.updateMeshPositions(positionFunction, false);
  16121. return instance;
  16122. }
  16123. // lines creation
  16124. var lines = new BABYLON.LinesMesh(name, scene);
  16125. var vertexData = BABYLON.VertexData.CreateLines(options);
  16126. vertexData.applyToMesh(lines, options.updatable);
  16127. return lines;
  16128. };
  16129. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16130. var points = options.points;
  16131. var instance = options.instance;
  16132. var gapSize = options.gapSize;
  16133. var dashNb = options.dashNb;
  16134. var dashSize = options.dashSize;
  16135. if (instance) {
  16136. var positionFunction = function (positions) {
  16137. var curvect = BABYLON.Vector3.Zero();
  16138. var nbSeg = positions.length / 6;
  16139. var lg = 0;
  16140. var nb = 0;
  16141. var shft = 0;
  16142. var dashshft = 0;
  16143. var curshft = 0;
  16144. var p = 0;
  16145. var i = 0;
  16146. var j = 0;
  16147. for (i = 0; i < points.length - 1; i++) {
  16148. points[i + 1].subtractToRef(points[i], curvect);
  16149. lg += curvect.length();
  16150. }
  16151. shft = lg / nbSeg;
  16152. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16153. for (i = 0; i < points.length - 1; i++) {
  16154. points[i + 1].subtractToRef(points[i], curvect);
  16155. nb = Math.floor(curvect.length() / shft);
  16156. curvect.normalize();
  16157. j = 0;
  16158. while (j < nb && p < positions.length) {
  16159. curshft = shft * j;
  16160. positions[p] = points[i].x + curshft * curvect.x;
  16161. positions[p + 1] = points[i].y + curshft * curvect.y;
  16162. positions[p + 2] = points[i].z + curshft * curvect.z;
  16163. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16164. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16165. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16166. p += 6;
  16167. j++;
  16168. }
  16169. }
  16170. while (p < positions.length) {
  16171. positions[p] = points[i].x;
  16172. positions[p + 1] = points[i].y;
  16173. positions[p + 2] = points[i].z;
  16174. p += 3;
  16175. }
  16176. };
  16177. instance.updateMeshPositions(positionFunction, false);
  16178. return instance;
  16179. }
  16180. // dashed lines creation
  16181. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16182. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16183. vertexData.applyToMesh(dashedLines, options.updatable);
  16184. dashedLines.dashSize = dashSize;
  16185. dashedLines.gapSize = gapSize;
  16186. return dashedLines;
  16187. };
  16188. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16189. var path = options.path;
  16190. var shape = options.shape;
  16191. var scale = options.scale || 1;
  16192. var rotation = options.rotation || 0;
  16193. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16194. var updatable = options.updatable;
  16195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16196. var instance = options.instance;
  16197. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16198. };
  16199. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16200. var path = options.path;
  16201. var shape = options.shape;
  16202. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16203. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16204. var ribbonCloseArray = options.ribbonCloseArray || false;
  16205. var ribbonClosePath = options.ribbonClosePath || false;
  16206. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16207. var updatable = options.updatable;
  16208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16209. var instance = options.instance;
  16210. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16211. };
  16212. MeshBuilder.CreateLathe = function (name, options, scene) {
  16213. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16214. var closed = (options.closed === undefined) ? true : options.closed;
  16215. var shape = options.shape;
  16216. var radius = options.radius || 1;
  16217. var tessellation = options.tessellation || 64;
  16218. var updatable = options.updatable;
  16219. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16220. var pi2 = Math.PI * 2;
  16221. var shapeLathe = new Array();
  16222. // first rotatable point
  16223. var i = 0;
  16224. while (shape[i].x === 0) {
  16225. i++;
  16226. }
  16227. var pt = shape[i];
  16228. for (i = 0; i < shape.length; i++) {
  16229. shapeLathe.push(shape[i].subtract(pt));
  16230. }
  16231. // circle path
  16232. var step = pi2 / tessellation * arc;
  16233. var rotated;
  16234. var path = new Array();
  16235. ;
  16236. for (i = 0; i <= tessellation; i++) {
  16237. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16238. path.push(rotated);
  16239. }
  16240. if (closed) {
  16241. path.push(path[0]);
  16242. }
  16243. // extrusion
  16244. var scaleFunction = function () { return 1; };
  16245. var rotateFunction = function () { return 0; };
  16246. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16247. return lathe;
  16248. };
  16249. MeshBuilder.CreatePlane = function (name, options, scene) {
  16250. var plane = new BABYLON.Mesh(name, scene);
  16251. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16252. vertexData.applyToMesh(plane, options.updatable);
  16253. if (options.sourcePlane) {
  16254. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16255. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16256. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16257. plane.rotate(vectorProduct, product);
  16258. }
  16259. return plane;
  16260. };
  16261. MeshBuilder.CreateGround = function (name, options, scene) {
  16262. var ground = new BABYLON.GroundMesh(name, scene);
  16263. ground._setReady(false);
  16264. ground._subdivisions = options.subdivisions || 1;
  16265. var vertexData = BABYLON.VertexData.CreateGround(options);
  16266. vertexData.applyToMesh(ground, options.updatable);
  16267. ground._setReady(true);
  16268. return ground;
  16269. };
  16270. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16271. var tiledGround = new BABYLON.Mesh(name, scene);
  16272. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16273. vertexData.applyToMesh(tiledGround, options.updatable);
  16274. return tiledGround;
  16275. };
  16276. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16277. var width = options.width || 10;
  16278. var height = options.height || 10;
  16279. var subdivisions = options.subdivisions || 1;
  16280. var minHeight = options.minHeight;
  16281. var maxHeight = options.maxHeight || 10;
  16282. var updatable = options.updatable;
  16283. var onReady = options.onReady;
  16284. var ground = new BABYLON.GroundMesh(name, scene);
  16285. ground._subdivisions = subdivisions;
  16286. ground._setReady(false);
  16287. var onload = function (img) {
  16288. // Getting height map data
  16289. var canvas = document.createElement("canvas");
  16290. var context = canvas.getContext("2d");
  16291. var bufferWidth = img.width;
  16292. var bufferHeight = img.height;
  16293. canvas.width = bufferWidth;
  16294. canvas.height = bufferHeight;
  16295. context.drawImage(img, 0, 0);
  16296. // Create VertexData from map data
  16297. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16298. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16299. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16300. width: width, height: height,
  16301. subdivisions: subdivisions,
  16302. minHeight: minHeight, maxHeight: maxHeight,
  16303. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16304. });
  16305. vertexData.applyToMesh(ground, updatable);
  16306. ground._setReady(true);
  16307. //execute ready callback, if set
  16308. if (onReady) {
  16309. onReady(ground);
  16310. }
  16311. };
  16312. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16313. return ground;
  16314. };
  16315. MeshBuilder.CreateTube = function (name, options, scene) {
  16316. var path = options.path;
  16317. var radius = options.radius || 1;
  16318. var tessellation = options.tessellation || 64;
  16319. var radiusFunction = options.radiusFunction;
  16320. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16321. var updatable = options.updatable;
  16322. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16323. var instance = options.instance;
  16324. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16325. // tube geometry
  16326. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16327. var tangents = path3D.getTangents();
  16328. var normals = path3D.getNormals();
  16329. var distances = path3D.getDistances();
  16330. var pi2 = Math.PI * 2;
  16331. var step = pi2 / tessellation * arc;
  16332. var returnRadius = function () { return radius; };
  16333. var radiusFunctionFinal = radiusFunction || returnRadius;
  16334. var circlePath;
  16335. var rad;
  16336. var normal;
  16337. var rotated;
  16338. var rotationMatrix = BABYLON.Matrix.Zero();
  16339. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16340. for (var i = 0; i < path.length; i++) {
  16341. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16342. circlePath = Array(); // current circle array
  16343. normal = normals[i]; // current normal
  16344. for (var t = 0; t < tessellation; t++) {
  16345. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16346. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16347. circlePath.push(rotated);
  16348. }
  16349. circlePaths[index] = circlePath;
  16350. index++;
  16351. }
  16352. // cap
  16353. var capPath = function (nbPoints, pathIndex) {
  16354. var pointCap = Array();
  16355. for (var i = 0; i < nbPoints; i++) {
  16356. pointCap.push(path[pathIndex]);
  16357. }
  16358. return pointCap;
  16359. };
  16360. switch (cap) {
  16361. case BABYLON.Mesh.NO_CAP:
  16362. break;
  16363. case BABYLON.Mesh.CAP_START:
  16364. circlePaths[0] = capPath(tessellation, 0);
  16365. circlePaths[1] = circlePaths[2].slice(0);
  16366. break;
  16367. case BABYLON.Mesh.CAP_END:
  16368. circlePaths[index] = circlePaths[index - 1].slice(0);
  16369. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16370. break;
  16371. case BABYLON.Mesh.CAP_ALL:
  16372. circlePaths[0] = capPath(tessellation, 0);
  16373. circlePaths[1] = circlePaths[2].slice(0);
  16374. circlePaths[index] = circlePaths[index - 1].slice(0);
  16375. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16376. break;
  16377. default:
  16378. break;
  16379. }
  16380. return circlePaths;
  16381. };
  16382. var path3D;
  16383. var pathArray;
  16384. if (instance) {
  16385. var arc = options.arc || instance.arc;
  16386. path3D = (instance.path3D).update(path);
  16387. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16388. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16389. instance.path3D = path3D;
  16390. instance.pathArray = pathArray;
  16391. instance.arc = arc;
  16392. return instance;
  16393. }
  16394. // tube creation
  16395. path3D = new BABYLON.Path3D(path);
  16396. var newPathArray = new Array();
  16397. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16398. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16399. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16400. tube.pathArray = pathArray;
  16401. tube.path3D = path3D;
  16402. tube.tessellation = tessellation;
  16403. tube.cap = cap;
  16404. tube.arc = options.arc;
  16405. return tube;
  16406. };
  16407. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16408. var polyhedron = new BABYLON.Mesh(name, scene);
  16409. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16410. vertexData.applyToMesh(polyhedron, options.updatable);
  16411. return polyhedron;
  16412. };
  16413. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16414. var indices = sourceMesh.getIndices();
  16415. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16416. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16417. var position = options.position || BABYLON.Vector3.Zero();
  16418. var normal = options.normal || BABYLON.Vector3.Up();
  16419. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16420. var angle = options.angle || 0;
  16421. // Getting correct rotation
  16422. if (!normal) {
  16423. var target = new BABYLON.Vector3(0, 0, 1);
  16424. var camera = sourceMesh.getScene().activeCamera;
  16425. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16426. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16427. }
  16428. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16429. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16430. var pitch = Math.atan2(normal.y, len);
  16431. // Matrix
  16432. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16433. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16434. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16435. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16436. var vertexData = new BABYLON.VertexData();
  16437. vertexData.indices = [];
  16438. vertexData.positions = [];
  16439. vertexData.normals = [];
  16440. vertexData.uvs = [];
  16441. var currentVertexDataIndex = 0;
  16442. var extractDecalVector3 = function (indexId) {
  16443. var vertexId = indices[indexId];
  16444. var result = new BABYLON.PositionNormalVertex();
  16445. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16446. // Send vector to decal local world
  16447. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16448. // Get normal
  16449. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16450. return result;
  16451. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16452. var clip = function (vertices, axis) {
  16453. if (vertices.length === 0) {
  16454. return vertices;
  16455. }
  16456. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16457. var clipVertices = function (v0, v1) {
  16458. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16459. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16460. };
  16461. var result = new Array();
  16462. for (var index = 0; index < vertices.length; index += 3) {
  16463. var v1Out;
  16464. var v2Out;
  16465. var v3Out;
  16466. var total = 0;
  16467. var nV1, nV2, nV3, nV4;
  16468. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16469. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16470. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16471. v1Out = d1 > 0;
  16472. v2Out = d2 > 0;
  16473. v3Out = d3 > 0;
  16474. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16475. switch (total) {
  16476. case 0:
  16477. result.push(vertices[index]);
  16478. result.push(vertices[index + 1]);
  16479. result.push(vertices[index + 2]);
  16480. break;
  16481. case 1:
  16482. if (v1Out) {
  16483. nV1 = vertices[index + 1];
  16484. nV2 = vertices[index + 2];
  16485. nV3 = clipVertices(vertices[index], nV1);
  16486. nV4 = clipVertices(vertices[index], nV2);
  16487. }
  16488. if (v2Out) {
  16489. nV1 = vertices[index];
  16490. nV2 = vertices[index + 2];
  16491. nV3 = clipVertices(vertices[index + 1], nV1);
  16492. nV4 = clipVertices(vertices[index + 1], nV2);
  16493. result.push(nV3);
  16494. result.push(nV2.clone());
  16495. result.push(nV1.clone());
  16496. result.push(nV2.clone());
  16497. result.push(nV3.clone());
  16498. result.push(nV4);
  16499. break;
  16500. }
  16501. if (v3Out) {
  16502. nV1 = vertices[index];
  16503. nV2 = vertices[index + 1];
  16504. nV3 = clipVertices(vertices[index + 2], nV1);
  16505. nV4 = clipVertices(vertices[index + 2], nV2);
  16506. }
  16507. result.push(nV1.clone());
  16508. result.push(nV2.clone());
  16509. result.push(nV3);
  16510. result.push(nV4);
  16511. result.push(nV3.clone());
  16512. result.push(nV2.clone());
  16513. break;
  16514. case 2:
  16515. if (!v1Out) {
  16516. nV1 = vertices[index].clone();
  16517. nV2 = clipVertices(nV1, vertices[index + 1]);
  16518. nV3 = clipVertices(nV1, vertices[index + 2]);
  16519. result.push(nV1);
  16520. result.push(nV2);
  16521. result.push(nV3);
  16522. }
  16523. if (!v2Out) {
  16524. nV1 = vertices[index + 1].clone();
  16525. nV2 = clipVertices(nV1, vertices[index + 2]);
  16526. nV3 = clipVertices(nV1, vertices[index]);
  16527. result.push(nV1);
  16528. result.push(nV2);
  16529. result.push(nV3);
  16530. }
  16531. if (!v3Out) {
  16532. nV1 = vertices[index + 2].clone();
  16533. nV2 = clipVertices(nV1, vertices[index]);
  16534. nV3 = clipVertices(nV1, vertices[index + 1]);
  16535. result.push(nV1);
  16536. result.push(nV2);
  16537. result.push(nV3);
  16538. }
  16539. break;
  16540. case 3:
  16541. break;
  16542. }
  16543. }
  16544. return result;
  16545. };
  16546. for (var index = 0; index < indices.length; index += 3) {
  16547. var faceVertices = new Array();
  16548. faceVertices.push(extractDecalVector3(index));
  16549. faceVertices.push(extractDecalVector3(index + 1));
  16550. faceVertices.push(extractDecalVector3(index + 2));
  16551. // Clip
  16552. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16553. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16554. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16555. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16556. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16557. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16558. if (faceVertices.length === 0) {
  16559. continue;
  16560. }
  16561. // Add UVs and get back to world
  16562. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16563. var vertex = faceVertices[vIndex];
  16564. //TODO check for Int32Array
  16565. vertexData.indices.push(currentVertexDataIndex);
  16566. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16567. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16568. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16569. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16570. currentVertexDataIndex++;
  16571. }
  16572. }
  16573. // Return mesh
  16574. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16575. vertexData.applyToMesh(decal);
  16576. decal.position = position.clone();
  16577. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16578. return decal;
  16579. };
  16580. // Privates
  16581. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16582. // extrusion geometry
  16583. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16584. var tangents = path3D.getTangents();
  16585. var normals = path3D.getNormals();
  16586. var binormals = path3D.getBinormals();
  16587. var distances = path3D.getDistances();
  16588. var angle = 0;
  16589. var returnScale = function () { return scale; };
  16590. var returnRotation = function () { return rotation; };
  16591. var rotate = custom ? rotateFunction : returnRotation;
  16592. var scl = custom ? scaleFunction : returnScale;
  16593. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16594. var rotationMatrix = BABYLON.Matrix.Zero();
  16595. for (var i = 0; i < curve.length; i++) {
  16596. var shapePath = new Array();
  16597. var angleStep = rotate(i, distances[i]);
  16598. var scaleRatio = scl(i, distances[i]);
  16599. for (var p = 0; p < shape.length; p++) {
  16600. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16601. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16602. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16603. shapePath.push(rotated);
  16604. }
  16605. shapePaths[index] = shapePath;
  16606. angle += angleStep;
  16607. index++;
  16608. }
  16609. // cap
  16610. var capPath = function (shapePath) {
  16611. var pointCap = Array();
  16612. var barycenter = BABYLON.Vector3.Zero();
  16613. var i;
  16614. for (i = 0; i < shapePath.length; i++) {
  16615. barycenter.addInPlace(shapePath[i]);
  16616. }
  16617. barycenter.scaleInPlace(1 / shapePath.length);
  16618. for (i = 0; i < shapePath.length; i++) {
  16619. pointCap.push(barycenter);
  16620. }
  16621. return pointCap;
  16622. };
  16623. switch (cap) {
  16624. case BABYLON.Mesh.NO_CAP:
  16625. break;
  16626. case BABYLON.Mesh.CAP_START:
  16627. shapePaths[0] = capPath(shapePaths[2]);
  16628. shapePaths[1] = shapePaths[2].slice(0);
  16629. break;
  16630. case BABYLON.Mesh.CAP_END:
  16631. shapePaths[index] = shapePaths[index - 1];
  16632. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16633. break;
  16634. case BABYLON.Mesh.CAP_ALL:
  16635. shapePaths[0] = capPath(shapePaths[2]);
  16636. shapePaths[1] = shapePaths[2].slice(0);
  16637. shapePaths[index] = shapePaths[index - 1];
  16638. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16639. break;
  16640. default:
  16641. break;
  16642. }
  16643. return shapePaths;
  16644. };
  16645. var path3D;
  16646. var pathArray;
  16647. if (instance) {
  16648. path3D = (instance.path3D).update(curve);
  16649. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16650. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16651. return instance;
  16652. }
  16653. // extruded shape creation
  16654. path3D = new BABYLON.Path3D(curve);
  16655. var newShapePaths = new Array();
  16656. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16657. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16658. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16659. extrudedGeneric.pathArray = pathArray;
  16660. extrudedGeneric.path3D = path3D;
  16661. extrudedGeneric.cap = cap;
  16662. return extrudedGeneric;
  16663. };
  16664. return MeshBuilder;
  16665. })();
  16666. BABYLON.MeshBuilder = MeshBuilder;
  16667. })(BABYLON || (BABYLON = {}));
  16668. var BABYLON;
  16669. (function (BABYLON) {
  16670. var BaseTexture = (function () {
  16671. function BaseTexture(scene) {
  16672. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16673. this.hasAlpha = false;
  16674. this.getAlphaFromRGB = false;
  16675. this.level = 1;
  16676. this.isCube = false;
  16677. this.isRenderTarget = false;
  16678. this.animations = new Array();
  16679. this.coordinatesIndex = 0;
  16680. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16681. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16682. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16683. this.anisotropicFilteringLevel = 4;
  16684. this._scene = scene;
  16685. this._scene.textures.push(this);
  16686. }
  16687. BaseTexture.prototype.getScene = function () {
  16688. return this._scene;
  16689. };
  16690. BaseTexture.prototype.getTextureMatrix = function () {
  16691. return null;
  16692. };
  16693. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16694. return null;
  16695. };
  16696. BaseTexture.prototype.getInternalTexture = function () {
  16697. return this._texture;
  16698. };
  16699. BaseTexture.prototype.isReady = function () {
  16700. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16701. return true;
  16702. }
  16703. if (this._texture) {
  16704. return this._texture.isReady;
  16705. }
  16706. return false;
  16707. };
  16708. BaseTexture.prototype.getSize = function () {
  16709. if (this._texture._width) {
  16710. return { width: this._texture._width, height: this._texture._height };
  16711. }
  16712. if (this._texture._size) {
  16713. return { width: this._texture._size, height: this._texture._size };
  16714. }
  16715. return { width: 0, height: 0 };
  16716. };
  16717. BaseTexture.prototype.getBaseSize = function () {
  16718. if (!this.isReady())
  16719. return { width: 0, height: 0 };
  16720. if (this._texture._size) {
  16721. return { width: this._texture._size, height: this._texture._size };
  16722. }
  16723. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16724. };
  16725. BaseTexture.prototype.scale = function (ratio) {
  16726. };
  16727. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16728. get: function () {
  16729. return false;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16735. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16736. for (var index = 0; index < texturesCache.length; index++) {
  16737. var texturesCacheEntry = texturesCache[index];
  16738. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16739. texturesCache.splice(index, 1);
  16740. return;
  16741. }
  16742. }
  16743. };
  16744. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16745. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16746. for (var index = 0; index < texturesCache.length; index++) {
  16747. var texturesCacheEntry = texturesCache[index];
  16748. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16749. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16750. texturesCacheEntry.references++;
  16751. return texturesCacheEntry;
  16752. }
  16753. }
  16754. }
  16755. return null;
  16756. };
  16757. BaseTexture.prototype.delayLoad = function () {
  16758. };
  16759. BaseTexture.prototype.clone = function () {
  16760. return null;
  16761. };
  16762. BaseTexture.prototype.releaseInternalTexture = function () {
  16763. if (this._texture) {
  16764. this._scene.getEngine().releaseInternalTexture(this._texture);
  16765. delete this._texture;
  16766. }
  16767. };
  16768. BaseTexture.prototype.dispose = function () {
  16769. // Animations
  16770. this.getScene().stopAnimation(this);
  16771. // Remove from scene
  16772. var index = this._scene.textures.indexOf(this);
  16773. if (index >= 0) {
  16774. this._scene.textures.splice(index, 1);
  16775. }
  16776. if (this._texture === undefined) {
  16777. return;
  16778. }
  16779. // Callback
  16780. if (this.onDispose) {
  16781. this.onDispose();
  16782. }
  16783. };
  16784. BaseTexture.prototype.serialize = function () {
  16785. var serializationObject = {};
  16786. if (!this.name) {
  16787. return null;
  16788. }
  16789. serializationObject.name = this.name;
  16790. serializationObject.hasAlpha = this.hasAlpha;
  16791. serializationObject.level = this.level;
  16792. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16793. serializationObject.coordinatesMode = this.coordinatesMode;
  16794. serializationObject.wrapU = this.wrapU;
  16795. serializationObject.wrapV = this.wrapV;
  16796. // Animations
  16797. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16798. return serializationObject;
  16799. };
  16800. return BaseTexture;
  16801. })();
  16802. BABYLON.BaseTexture = BaseTexture;
  16803. })(BABYLON || (BABYLON = {}));
  16804. var BABYLON;
  16805. (function (BABYLON) {
  16806. var Texture = (function (_super) {
  16807. __extends(Texture, _super);
  16808. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16809. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16810. if (onLoad === void 0) { onLoad = null; }
  16811. if (onError === void 0) { onError = null; }
  16812. if (buffer === void 0) { buffer = null; }
  16813. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16814. _super.call(this, scene);
  16815. this.uOffset = 0;
  16816. this.vOffset = 0;
  16817. this.uScale = 1.0;
  16818. this.vScale = 1.0;
  16819. this.uAng = 0;
  16820. this.vAng = 0;
  16821. this.wAng = 0;
  16822. this.name = url;
  16823. this.url = url;
  16824. this._noMipmap = noMipmap;
  16825. this._invertY = invertY;
  16826. this._samplingMode = samplingMode;
  16827. this._buffer = buffer;
  16828. this._deleteBuffer = deleteBuffer;
  16829. if (!url) {
  16830. return;
  16831. }
  16832. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16833. if (!this._texture) {
  16834. if (!scene.useDelayedTextureLoading) {
  16835. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16836. if (deleteBuffer) {
  16837. delete this._buffer;
  16838. }
  16839. }
  16840. else {
  16841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16842. }
  16843. }
  16844. else {
  16845. BABYLON.Tools.SetImmediate(function () {
  16846. if (onLoad) {
  16847. onLoad();
  16848. }
  16849. });
  16850. }
  16851. }
  16852. Texture.prototype.delayLoad = function () {
  16853. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16854. return;
  16855. }
  16856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16857. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16858. if (!this._texture) {
  16859. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16860. if (this._deleteBuffer) {
  16861. delete this._buffer;
  16862. }
  16863. }
  16864. };
  16865. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16866. if (!this._texture) {
  16867. return;
  16868. }
  16869. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16870. };
  16871. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16872. x *= this.uScale;
  16873. y *= this.vScale;
  16874. x -= 0.5 * this.uScale;
  16875. y -= 0.5 * this.vScale;
  16876. z -= 0.5;
  16877. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16878. t.x += 0.5 * this.uScale + this.uOffset;
  16879. t.y += 0.5 * this.vScale + this.vOffset;
  16880. t.z += 0.5;
  16881. };
  16882. Texture.prototype.getTextureMatrix = function () {
  16883. if (this.uOffset === this._cachedUOffset &&
  16884. this.vOffset === this._cachedVOffset &&
  16885. this.uScale === this._cachedUScale &&
  16886. this.vScale === this._cachedVScale &&
  16887. this.uAng === this._cachedUAng &&
  16888. this.vAng === this._cachedVAng &&
  16889. this.wAng === this._cachedWAng) {
  16890. return this._cachedTextureMatrix;
  16891. }
  16892. this._cachedUOffset = this.uOffset;
  16893. this._cachedVOffset = this.vOffset;
  16894. this._cachedUScale = this.uScale;
  16895. this._cachedVScale = this.vScale;
  16896. this._cachedUAng = this.uAng;
  16897. this._cachedVAng = this.vAng;
  16898. this._cachedWAng = this.wAng;
  16899. if (!this._cachedTextureMatrix) {
  16900. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16901. this._rowGenerationMatrix = new BABYLON.Matrix();
  16902. this._t0 = BABYLON.Vector3.Zero();
  16903. this._t1 = BABYLON.Vector3.Zero();
  16904. this._t2 = BABYLON.Vector3.Zero();
  16905. }
  16906. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16907. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16908. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16909. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16910. this._t1.subtractInPlace(this._t0);
  16911. this._t2.subtractInPlace(this._t0);
  16912. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16913. this._cachedTextureMatrix.m[0] = this._t1.x;
  16914. this._cachedTextureMatrix.m[1] = this._t1.y;
  16915. this._cachedTextureMatrix.m[2] = this._t1.z;
  16916. this._cachedTextureMatrix.m[4] = this._t2.x;
  16917. this._cachedTextureMatrix.m[5] = this._t2.y;
  16918. this._cachedTextureMatrix.m[6] = this._t2.z;
  16919. this._cachedTextureMatrix.m[8] = this._t0.x;
  16920. this._cachedTextureMatrix.m[9] = this._t0.y;
  16921. this._cachedTextureMatrix.m[10] = this._t0.z;
  16922. return this._cachedTextureMatrix;
  16923. };
  16924. Texture.prototype.getReflectionTextureMatrix = function () {
  16925. if (this.uOffset === this._cachedUOffset &&
  16926. this.vOffset === this._cachedVOffset &&
  16927. this.uScale === this._cachedUScale &&
  16928. this.vScale === this._cachedVScale &&
  16929. this.coordinatesMode === this._cachedCoordinatesMode) {
  16930. return this._cachedTextureMatrix;
  16931. }
  16932. if (!this._cachedTextureMatrix) {
  16933. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16934. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16935. }
  16936. this._cachedCoordinatesMode = this.coordinatesMode;
  16937. switch (this.coordinatesMode) {
  16938. case Texture.PLANAR_MODE:
  16939. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16940. this._cachedTextureMatrix[0] = this.uScale;
  16941. this._cachedTextureMatrix[5] = this.vScale;
  16942. this._cachedTextureMatrix[12] = this.uOffset;
  16943. this._cachedTextureMatrix[13] = this.vOffset;
  16944. break;
  16945. case Texture.PROJECTION_MODE:
  16946. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16947. this._projectionModeMatrix.m[0] = 0.5;
  16948. this._projectionModeMatrix.m[5] = -0.5;
  16949. this._projectionModeMatrix.m[10] = 0.0;
  16950. this._projectionModeMatrix.m[12] = 0.5;
  16951. this._projectionModeMatrix.m[13] = 0.5;
  16952. this._projectionModeMatrix.m[14] = 1.0;
  16953. this._projectionModeMatrix.m[15] = 1.0;
  16954. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16955. break;
  16956. default:
  16957. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16958. break;
  16959. }
  16960. return this._cachedTextureMatrix;
  16961. };
  16962. Texture.prototype.clone = function () {
  16963. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16964. // Base texture
  16965. newTexture.hasAlpha = this.hasAlpha;
  16966. newTexture.level = this.level;
  16967. newTexture.wrapU = this.wrapU;
  16968. newTexture.wrapV = this.wrapV;
  16969. newTexture.coordinatesIndex = this.coordinatesIndex;
  16970. newTexture.coordinatesMode = this.coordinatesMode;
  16971. // Texture
  16972. newTexture.uOffset = this.uOffset;
  16973. newTexture.vOffset = this.vOffset;
  16974. newTexture.uScale = this.uScale;
  16975. newTexture.vScale = this.vScale;
  16976. newTexture.uAng = this.uAng;
  16977. newTexture.vAng = this.vAng;
  16978. newTexture.wAng = this.wAng;
  16979. return newTexture;
  16980. };
  16981. Texture.prototype.serialize = function () {
  16982. if (!this.name) {
  16983. return null;
  16984. }
  16985. var serializationObject = _super.prototype.serialize.call(this);
  16986. serializationObject.uOffset = this.uOffset;
  16987. serializationObject.vOffset = this.vOffset;
  16988. serializationObject.uScale = this.uScale;
  16989. serializationObject.vScale = this.vScale;
  16990. serializationObject.uAng = this.uAng;
  16991. serializationObject.vAng = this.vAng;
  16992. serializationObject.wAng = this.wAng;
  16993. return serializationObject;
  16994. };
  16995. // Statics
  16996. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16997. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16998. if (onLoad === void 0) { onLoad = null; }
  16999. if (onError === void 0) { onError = null; }
  17000. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17001. };
  17002. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17003. if (parsedTexture.isCube) {
  17004. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17005. }
  17006. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17007. return null;
  17008. }
  17009. var texture;
  17010. if (parsedTexture.mirrorPlane) {
  17011. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17012. texture._waitingRenderList = parsedTexture.renderList;
  17013. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17014. }
  17015. else if (parsedTexture.isRenderTarget) {
  17016. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17017. texture._waitingRenderList = parsedTexture.renderList;
  17018. }
  17019. else {
  17020. if (parsedTexture.base64String) {
  17021. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17022. }
  17023. else {
  17024. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17025. }
  17026. }
  17027. texture.name = parsedTexture.name;
  17028. texture.hasAlpha = parsedTexture.hasAlpha;
  17029. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17030. texture.level = parsedTexture.level;
  17031. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17032. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17033. texture.uOffset = parsedTexture.uOffset;
  17034. texture.vOffset = parsedTexture.vOffset;
  17035. texture.uScale = parsedTexture.uScale;
  17036. texture.vScale = parsedTexture.vScale;
  17037. texture.uAng = parsedTexture.uAng;
  17038. texture.vAng = parsedTexture.vAng;
  17039. texture.wAng = parsedTexture.wAng;
  17040. texture.wrapU = parsedTexture.wrapU;
  17041. texture.wrapV = parsedTexture.wrapV;
  17042. // Animations
  17043. if (parsedTexture.animations) {
  17044. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17045. var parsedAnimation = parsedTexture.animations[animationIndex];
  17046. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17047. }
  17048. }
  17049. return texture;
  17050. };
  17051. // Constants
  17052. Texture.NEAREST_SAMPLINGMODE = 1;
  17053. Texture.BILINEAR_SAMPLINGMODE = 2;
  17054. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17055. Texture.EXPLICIT_MODE = 0;
  17056. Texture.SPHERICAL_MODE = 1;
  17057. Texture.PLANAR_MODE = 2;
  17058. Texture.CUBIC_MODE = 3;
  17059. Texture.PROJECTION_MODE = 4;
  17060. Texture.SKYBOX_MODE = 5;
  17061. Texture.INVCUBIC_MODE = 6;
  17062. Texture.EQUIRECTANGULAR_MODE = 7;
  17063. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17064. Texture.CLAMP_ADDRESSMODE = 0;
  17065. Texture.WRAP_ADDRESSMODE = 1;
  17066. Texture.MIRROR_ADDRESSMODE = 2;
  17067. return Texture;
  17068. })(BABYLON.BaseTexture);
  17069. BABYLON.Texture = Texture;
  17070. })(BABYLON || (BABYLON = {}));
  17071. var BABYLON;
  17072. (function (BABYLON) {
  17073. var CubeTexture = (function (_super) {
  17074. __extends(CubeTexture, _super);
  17075. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17076. _super.call(this, scene);
  17077. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17078. this.name = rootUrl;
  17079. this.url = rootUrl;
  17080. this._noMipmap = noMipmap;
  17081. this.hasAlpha = false;
  17082. if (!rootUrl) {
  17083. return;
  17084. }
  17085. this._texture = this._getFromCache(rootUrl, noMipmap);
  17086. if (!extensions) {
  17087. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17088. }
  17089. this._extensions = extensions;
  17090. if (!this._texture) {
  17091. if (!scene.useDelayedTextureLoading) {
  17092. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17093. }
  17094. else {
  17095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17096. }
  17097. }
  17098. this.isCube = true;
  17099. this._textureMatrix = BABYLON.Matrix.Identity();
  17100. }
  17101. CubeTexture.prototype.clone = function () {
  17102. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17103. // Base texture
  17104. newTexture.level = this.level;
  17105. newTexture.wrapU = this.wrapU;
  17106. newTexture.wrapV = this.wrapV;
  17107. newTexture.coordinatesIndex = this.coordinatesIndex;
  17108. newTexture.coordinatesMode = this.coordinatesMode;
  17109. return newTexture;
  17110. };
  17111. // Methods
  17112. CubeTexture.prototype.delayLoad = function () {
  17113. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17114. return;
  17115. }
  17116. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17117. this._texture = this._getFromCache(this.url, this._noMipmap);
  17118. if (!this._texture) {
  17119. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17120. }
  17121. };
  17122. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17123. return this._textureMatrix;
  17124. };
  17125. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17126. var texture = null;
  17127. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17128. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17129. texture.name = parsedTexture.name;
  17130. texture.hasAlpha = parsedTexture.hasAlpha;
  17131. texture.level = parsedTexture.level;
  17132. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17133. }
  17134. return texture;
  17135. };
  17136. CubeTexture.prototype.serialize = function () {
  17137. if (!this.name) {
  17138. return null;
  17139. }
  17140. var serializationObject = {};
  17141. serializationObject.name = this.name;
  17142. serializationObject.hasAlpha = this.hasAlpha;
  17143. serializationObject.isCube = true;
  17144. serializationObject.level = this.level;
  17145. serializationObject.coordinatesMode = this.coordinatesMode;
  17146. return serializationObject;
  17147. };
  17148. return CubeTexture;
  17149. })(BABYLON.BaseTexture);
  17150. BABYLON.CubeTexture = CubeTexture;
  17151. })(BABYLON || (BABYLON = {}));
  17152. var BABYLON;
  17153. (function (BABYLON) {
  17154. var RenderTargetTexture = (function (_super) {
  17155. __extends(RenderTargetTexture, _super);
  17156. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17157. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17158. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17159. if (isCube === void 0) { isCube = false; }
  17160. _super.call(this, null, scene, !generateMipMaps);
  17161. this.isCube = isCube;
  17162. this.renderList = new Array();
  17163. this.renderParticles = true;
  17164. this.renderSprites = false;
  17165. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17166. this._currentRefreshId = -1;
  17167. this._refreshRate = 1;
  17168. this.name = name;
  17169. this.isRenderTarget = true;
  17170. this._size = size;
  17171. this._generateMipMaps = generateMipMaps;
  17172. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17173. if (isCube) {
  17174. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17175. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17176. this._textureMatrix = BABYLON.Matrix.Identity();
  17177. }
  17178. else {
  17179. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17180. }
  17181. // Rendering groups
  17182. this._renderingManager = new BABYLON.RenderingManager(scene);
  17183. }
  17184. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17185. get: function () {
  17186. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17192. get: function () {
  17193. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17199. get: function () {
  17200. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17201. },
  17202. enumerable: true,
  17203. configurable: true
  17204. });
  17205. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17206. this._currentRefreshId = -1;
  17207. };
  17208. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17209. get: function () {
  17210. return this._refreshRate;
  17211. },
  17212. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17213. set: function (value) {
  17214. this._refreshRate = value;
  17215. this.resetRefreshCounter();
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. RenderTargetTexture.prototype._shouldRender = function () {
  17221. if (this._currentRefreshId === -1) {
  17222. this._currentRefreshId = 1;
  17223. return true;
  17224. }
  17225. if (this.refreshRate === this._currentRefreshId) {
  17226. this._currentRefreshId = 1;
  17227. return true;
  17228. }
  17229. this._currentRefreshId++;
  17230. return false;
  17231. };
  17232. RenderTargetTexture.prototype.isReady = function () {
  17233. if (!this.getScene().renderTargetsEnabled) {
  17234. return false;
  17235. }
  17236. return _super.prototype.isReady.call(this);
  17237. };
  17238. RenderTargetTexture.prototype.getRenderSize = function () {
  17239. return this._size;
  17240. };
  17241. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17242. get: function () {
  17243. return true;
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. RenderTargetTexture.prototype.scale = function (ratio) {
  17249. var newSize = this._size * ratio;
  17250. this.resize(newSize, this._generateMipMaps);
  17251. };
  17252. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17253. if (this.isCube) {
  17254. return this._textureMatrix;
  17255. }
  17256. return _super.prototype.getReflectionTextureMatrix.call(this);
  17257. };
  17258. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17259. this.releaseInternalTexture();
  17260. if (this.isCube) {
  17261. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17262. }
  17263. else {
  17264. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17265. }
  17266. };
  17267. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17268. var scene = this.getScene();
  17269. if (this._waitingRenderList) {
  17270. this.renderList = [];
  17271. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17272. var id = this._waitingRenderList[index];
  17273. this.renderList.push(scene.getMeshByID(id));
  17274. }
  17275. delete this._waitingRenderList;
  17276. }
  17277. if (this.renderList && this.renderList.length === 0) {
  17278. return;
  17279. }
  17280. // Prepare renderingManager
  17281. this._renderingManager.reset();
  17282. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17283. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17284. var mesh = currentRenderList[meshIndex];
  17285. if (mesh) {
  17286. if (!mesh.isReady()) {
  17287. // Reset _currentRefreshId
  17288. this.resetRefreshCounter();
  17289. continue;
  17290. }
  17291. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17292. mesh._activate(scene.getRenderId());
  17293. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17294. var subMesh = mesh.subMeshes[subIndex];
  17295. scene._activeIndices += subMesh.indexCount;
  17296. this._renderingManager.dispatch(subMesh);
  17297. }
  17298. }
  17299. }
  17300. }
  17301. if (this.isCube) {
  17302. for (var face = 0; face < 6; face++) {
  17303. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17304. }
  17305. }
  17306. else {
  17307. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17308. }
  17309. if (this.onAfterUnbind) {
  17310. this.onAfterUnbind();
  17311. }
  17312. scene.resetCachedMaterial();
  17313. };
  17314. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17315. var scene = this.getScene();
  17316. var engine = scene.getEngine();
  17317. // Bind
  17318. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17319. if (this.isCube) {
  17320. engine.bindFramebuffer(this._texture, faceIndex);
  17321. }
  17322. else {
  17323. engine.bindFramebuffer(this._texture);
  17324. }
  17325. }
  17326. if (this.onBeforeRender) {
  17327. this.onBeforeRender(faceIndex);
  17328. }
  17329. // Clear
  17330. if (this.onClear) {
  17331. this.onClear(engine);
  17332. }
  17333. else {
  17334. engine.clear(scene.clearColor, true, true);
  17335. }
  17336. if (!this._doNotChangeAspectRatio) {
  17337. scene.updateTransformMatrix(true);
  17338. }
  17339. // Render
  17340. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17341. if (useCameraPostProcess) {
  17342. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17343. }
  17344. if (!this._doNotChangeAspectRatio) {
  17345. scene.updateTransformMatrix(true);
  17346. }
  17347. if (this.onAfterRender) {
  17348. this.onAfterRender(faceIndex);
  17349. }
  17350. // Dump ?
  17351. if (dumpForDebug) {
  17352. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17353. }
  17354. // Unbind
  17355. if (!this.isCube || faceIndex === 5) {
  17356. if (this.isCube) {
  17357. if (faceIndex === 5) {
  17358. engine.generateMipMapsForCubemap(this._texture);
  17359. }
  17360. }
  17361. engine.unBindFramebuffer(this._texture, this.isCube);
  17362. }
  17363. };
  17364. RenderTargetTexture.prototype.clone = function () {
  17365. var textureSize = this.getSize();
  17366. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17367. // Base texture
  17368. newTexture.hasAlpha = this.hasAlpha;
  17369. newTexture.level = this.level;
  17370. // RenderTarget Texture
  17371. newTexture.coordinatesMode = this.coordinatesMode;
  17372. newTexture.renderList = this.renderList.slice(0);
  17373. return newTexture;
  17374. };
  17375. RenderTargetTexture.prototype.serialize = function () {
  17376. if (!this.name) {
  17377. return null;
  17378. }
  17379. var serializationObject = _super.prototype.serialize.call(this);
  17380. serializationObject.renderTargetSize = this.getRenderSize();
  17381. serializationObject.renderList = [];
  17382. for (var index = 0; index < this.renderList.length; index++) {
  17383. serializationObject.renderList.push(this.renderList[index].id);
  17384. }
  17385. return serializationObject;
  17386. };
  17387. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17388. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17389. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17390. return RenderTargetTexture;
  17391. })(BABYLON.Texture);
  17392. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17393. })(BABYLON || (BABYLON = {}));
  17394. var BABYLON;
  17395. (function (BABYLON) {
  17396. var ProceduralTexture = (function (_super) {
  17397. __extends(ProceduralTexture, _super);
  17398. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17399. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17400. _super.call(this, null, scene, !generateMipMaps);
  17401. this.isEnabled = true;
  17402. this._currentRefreshId = -1;
  17403. this._refreshRate = 1;
  17404. this._vertexDeclaration = [2];
  17405. this._vertexStrideSize = 2 * 4;
  17406. this._uniforms = new Array();
  17407. this._samplers = new Array();
  17408. this._textures = new Array();
  17409. this._floats = new Array();
  17410. this._floatsArrays = {};
  17411. this._colors3 = new Array();
  17412. this._colors4 = new Array();
  17413. this._vectors2 = new Array();
  17414. this._vectors3 = new Array();
  17415. this._matrices = new Array();
  17416. this._fallbackTextureUsed = false;
  17417. scene._proceduralTextures.push(this);
  17418. this.name = name;
  17419. this.isRenderTarget = true;
  17420. this._size = size;
  17421. this._generateMipMaps = generateMipMaps;
  17422. this.setFragment(fragment);
  17423. this._fallbackTexture = fallbackTexture;
  17424. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17425. // VBO
  17426. var vertices = [];
  17427. vertices.push(1, 1);
  17428. vertices.push(-1, 1);
  17429. vertices.push(-1, -1);
  17430. vertices.push(1, -1);
  17431. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17432. // Indices
  17433. var indices = [];
  17434. indices.push(0);
  17435. indices.push(1);
  17436. indices.push(2);
  17437. indices.push(0);
  17438. indices.push(2);
  17439. indices.push(3);
  17440. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17441. }
  17442. ProceduralTexture.prototype.reset = function () {
  17443. if (this._effect === undefined) {
  17444. return;
  17445. }
  17446. var engine = this.getScene().getEngine();
  17447. engine._releaseEffect(this._effect);
  17448. };
  17449. ProceduralTexture.prototype.isReady = function () {
  17450. var _this = this;
  17451. var engine = this.getScene().getEngine();
  17452. var shaders;
  17453. if (!this._fragment) {
  17454. return false;
  17455. }
  17456. if (this._fallbackTextureUsed) {
  17457. return true;
  17458. }
  17459. if (this._fragment.fragmentElement !== undefined) {
  17460. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17461. }
  17462. else {
  17463. shaders = { vertex: "procedural", fragment: this._fragment };
  17464. }
  17465. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17466. _this.releaseInternalTexture();
  17467. if (_this._fallbackTexture) {
  17468. _this._texture = _this._fallbackTexture._texture;
  17469. _this._texture.references++;
  17470. }
  17471. _this._fallbackTextureUsed = true;
  17472. });
  17473. return this._effect.isReady();
  17474. };
  17475. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17476. this._currentRefreshId = -1;
  17477. };
  17478. ProceduralTexture.prototype.setFragment = function (fragment) {
  17479. this._fragment = fragment;
  17480. };
  17481. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17482. get: function () {
  17483. return this._refreshRate;
  17484. },
  17485. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17486. set: function (value) {
  17487. this._refreshRate = value;
  17488. this.resetRefreshCounter();
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. ProceduralTexture.prototype._shouldRender = function () {
  17494. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17495. return false;
  17496. }
  17497. if (this._fallbackTextureUsed) {
  17498. return false;
  17499. }
  17500. if (this._currentRefreshId === -1) {
  17501. this._currentRefreshId = 1;
  17502. return true;
  17503. }
  17504. if (this.refreshRate === this._currentRefreshId) {
  17505. this._currentRefreshId = 1;
  17506. return true;
  17507. }
  17508. this._currentRefreshId++;
  17509. return false;
  17510. };
  17511. ProceduralTexture.prototype.getRenderSize = function () {
  17512. return this._size;
  17513. };
  17514. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17515. if (this._fallbackTextureUsed) {
  17516. return;
  17517. }
  17518. this.releaseInternalTexture();
  17519. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17520. };
  17521. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17522. if (this._uniforms.indexOf(uniformName) === -1) {
  17523. this._uniforms.push(uniformName);
  17524. }
  17525. };
  17526. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17527. if (this._samplers.indexOf(name) === -1) {
  17528. this._samplers.push(name);
  17529. }
  17530. this._textures[name] = texture;
  17531. return this;
  17532. };
  17533. ProceduralTexture.prototype.setFloat = function (name, value) {
  17534. this._checkUniform(name);
  17535. this._floats[name] = value;
  17536. return this;
  17537. };
  17538. ProceduralTexture.prototype.setFloats = function (name, value) {
  17539. this._checkUniform(name);
  17540. this._floatsArrays[name] = value;
  17541. return this;
  17542. };
  17543. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17544. this._checkUniform(name);
  17545. this._colors3[name] = value;
  17546. return this;
  17547. };
  17548. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17549. this._checkUniform(name);
  17550. this._colors4[name] = value;
  17551. return this;
  17552. };
  17553. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17554. this._checkUniform(name);
  17555. this._vectors2[name] = value;
  17556. return this;
  17557. };
  17558. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17559. this._checkUniform(name);
  17560. this._vectors3[name] = value;
  17561. return this;
  17562. };
  17563. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17564. this._checkUniform(name);
  17565. this._matrices[name] = value;
  17566. return this;
  17567. };
  17568. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17569. var scene = this.getScene();
  17570. var engine = scene.getEngine();
  17571. engine.bindFramebuffer(this._texture);
  17572. // Clear
  17573. engine.clear(scene.clearColor, true, true);
  17574. // Render
  17575. engine.enableEffect(this._effect);
  17576. engine.setState(false);
  17577. // Texture
  17578. for (var name in this._textures) {
  17579. this._effect.setTexture(name, this._textures[name]);
  17580. }
  17581. // Float
  17582. for (name in this._floats) {
  17583. this._effect.setFloat(name, this._floats[name]);
  17584. }
  17585. // Floats
  17586. for (name in this._floatsArrays) {
  17587. this._effect.setArray(name, this._floatsArrays[name]);
  17588. }
  17589. // Color3
  17590. for (name in this._colors3) {
  17591. this._effect.setColor3(name, this._colors3[name]);
  17592. }
  17593. // Color4
  17594. for (name in this._colors4) {
  17595. var color = this._colors4[name];
  17596. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17597. }
  17598. // Vector2
  17599. for (name in this._vectors2) {
  17600. this._effect.setVector2(name, this._vectors2[name]);
  17601. }
  17602. // Vector3
  17603. for (name in this._vectors3) {
  17604. this._effect.setVector3(name, this._vectors3[name]);
  17605. }
  17606. // Matrix
  17607. for (name in this._matrices) {
  17608. this._effect.setMatrix(name, this._matrices[name]);
  17609. }
  17610. // VBOs
  17611. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17612. // Draw order
  17613. engine.draw(true, 0, 6);
  17614. // Unbind
  17615. engine.unBindFramebuffer(this._texture);
  17616. };
  17617. ProceduralTexture.prototype.clone = function () {
  17618. var textureSize = this.getSize();
  17619. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17620. // Base texture
  17621. newTexture.hasAlpha = this.hasAlpha;
  17622. newTexture.level = this.level;
  17623. // RenderTarget Texture
  17624. newTexture.coordinatesMode = this.coordinatesMode;
  17625. return newTexture;
  17626. };
  17627. ProceduralTexture.prototype.dispose = function () {
  17628. var index = this.getScene()._proceduralTextures.indexOf(this);
  17629. if (index >= 0) {
  17630. this.getScene()._proceduralTextures.splice(index, 1);
  17631. }
  17632. _super.prototype.dispose.call(this);
  17633. };
  17634. return ProceduralTexture;
  17635. })(BABYLON.Texture);
  17636. BABYLON.ProceduralTexture = ProceduralTexture;
  17637. })(BABYLON || (BABYLON = {}));
  17638. var BABYLON;
  17639. (function (BABYLON) {
  17640. var MirrorTexture = (function (_super) {
  17641. __extends(MirrorTexture, _super);
  17642. function MirrorTexture(name, size, scene, generateMipMaps) {
  17643. var _this = this;
  17644. _super.call(this, name, size, scene, generateMipMaps, true);
  17645. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17646. this._transformMatrix = BABYLON.Matrix.Zero();
  17647. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17648. this.onBeforeRender = function () {
  17649. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17650. _this._savedViewMatrix = scene.getViewMatrix();
  17651. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17652. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17653. scene.clipPlane = _this.mirrorPlane;
  17654. scene.getEngine().cullBackFaces = false;
  17655. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17656. };
  17657. this.onAfterRender = function () {
  17658. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17659. scene.getEngine().cullBackFaces = true;
  17660. scene._mirroredCameraPosition = null;
  17661. delete scene.clipPlane;
  17662. };
  17663. }
  17664. MirrorTexture.prototype.clone = function () {
  17665. var textureSize = this.getSize();
  17666. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17667. // Base texture
  17668. newTexture.hasAlpha = this.hasAlpha;
  17669. newTexture.level = this.level;
  17670. // Mirror Texture
  17671. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17672. newTexture.renderList = this.renderList.slice(0);
  17673. return newTexture;
  17674. };
  17675. MirrorTexture.prototype.serialize = function () {
  17676. if (!this.name) {
  17677. return null;
  17678. }
  17679. var serializationObject = _super.prototype.serialize.call(this);
  17680. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17681. return serializationObject;
  17682. };
  17683. return MirrorTexture;
  17684. })(BABYLON.RenderTargetTexture);
  17685. BABYLON.MirrorTexture = MirrorTexture;
  17686. })(BABYLON || (BABYLON = {}));
  17687. var BABYLON;
  17688. (function (BABYLON) {
  17689. var DynamicTexture = (function (_super) {
  17690. __extends(DynamicTexture, _super);
  17691. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17693. _super.call(this, null, scene, !generateMipMaps);
  17694. this.name = name;
  17695. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17696. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17697. this._generateMipMaps = generateMipMaps;
  17698. if (options.getContext) {
  17699. this._canvas = options;
  17700. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17701. }
  17702. else {
  17703. this._canvas = document.createElement("canvas");
  17704. if (options.width) {
  17705. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17706. }
  17707. else {
  17708. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17709. }
  17710. }
  17711. var textureSize = this.getSize();
  17712. this._canvas.width = textureSize.width;
  17713. this._canvas.height = textureSize.height;
  17714. this._context = this._canvas.getContext("2d");
  17715. }
  17716. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17717. get: function () {
  17718. return true;
  17719. },
  17720. enumerable: true,
  17721. configurable: true
  17722. });
  17723. DynamicTexture.prototype.scale = function (ratio) {
  17724. var textureSize = this.getSize();
  17725. textureSize.width *= ratio;
  17726. textureSize.height *= ratio;
  17727. this._canvas.width = textureSize.width;
  17728. this._canvas.height = textureSize.height;
  17729. this.releaseInternalTexture();
  17730. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17731. };
  17732. DynamicTexture.prototype.getContext = function () {
  17733. return this._context;
  17734. };
  17735. DynamicTexture.prototype.clear = function () {
  17736. var size = this.getSize();
  17737. this._context.fillRect(0, 0, size.width, size.height);
  17738. };
  17739. DynamicTexture.prototype.update = function (invertY) {
  17740. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17741. };
  17742. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17743. if (update === void 0) { update = true; }
  17744. var size = this.getSize();
  17745. if (clearColor) {
  17746. this._context.fillStyle = clearColor;
  17747. this._context.fillRect(0, 0, size.width, size.height);
  17748. }
  17749. this._context.font = font;
  17750. if (x === null) {
  17751. var textSize = this._context.measureText(text);
  17752. x = (size.width - textSize.width) / 2;
  17753. }
  17754. this._context.fillStyle = color;
  17755. this._context.fillText(text, x, y);
  17756. if (update) {
  17757. this.update(invertY);
  17758. }
  17759. };
  17760. DynamicTexture.prototype.clone = function () {
  17761. var textureSize = this.getSize();
  17762. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17763. // Base texture
  17764. newTexture.hasAlpha = this.hasAlpha;
  17765. newTexture.level = this.level;
  17766. // Dynamic Texture
  17767. newTexture.wrapU = this.wrapU;
  17768. newTexture.wrapV = this.wrapV;
  17769. return newTexture;
  17770. };
  17771. return DynamicTexture;
  17772. })(BABYLON.Texture);
  17773. BABYLON.DynamicTexture = DynamicTexture;
  17774. })(BABYLON || (BABYLON = {}));
  17775. var BABYLON;
  17776. (function (BABYLON) {
  17777. var VideoTexture = (function (_super) {
  17778. __extends(VideoTexture, _super);
  17779. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17780. var _this = this;
  17781. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17782. if (invertY === void 0) { invertY = false; }
  17783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17784. _super.call(this, null, scene, !generateMipMaps, invertY);
  17785. this._autoLaunch = true;
  17786. this.name = name;
  17787. this.video = document.createElement("video");
  17788. this.video.autoplay = false;
  17789. this.video.loop = true;
  17790. this.video.addEventListener("canplaythrough", function () {
  17791. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17792. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17793. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17794. }
  17795. else {
  17796. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17797. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17798. generateMipMaps = false;
  17799. }
  17800. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17801. _this._texture.isReady = true;
  17802. });
  17803. urls.forEach(function (url) {
  17804. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17805. var source = document.createElement("source");
  17806. source.src = url;
  17807. _this.video.appendChild(source);
  17808. });
  17809. this._lastUpdate = BABYLON.Tools.Now;
  17810. }
  17811. VideoTexture.prototype.update = function () {
  17812. if (this._autoLaunch) {
  17813. this._autoLaunch = false;
  17814. this.video.play();
  17815. }
  17816. var now = BABYLON.Tools.Now;
  17817. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17818. return false;
  17819. }
  17820. this._lastUpdate = now;
  17821. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17822. return true;
  17823. };
  17824. return VideoTexture;
  17825. })(BABYLON.Texture);
  17826. BABYLON.VideoTexture = VideoTexture;
  17827. })(BABYLON || (BABYLON = {}));
  17828. var BABYLON;
  17829. (function (BABYLON) {
  17830. var CustomProceduralTexture = (function (_super) {
  17831. __extends(CustomProceduralTexture, _super);
  17832. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17833. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17834. this._animate = true;
  17835. this._time = 0;
  17836. this._texturePath = texturePath;
  17837. //Try to load json
  17838. this.loadJson(texturePath);
  17839. this.refreshRate = 1;
  17840. }
  17841. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17842. var _this = this;
  17843. var that = this;
  17844. function noConfigFile() {
  17845. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17846. try {
  17847. that.setFragment(that._texturePath);
  17848. }
  17849. catch (ex) {
  17850. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17851. }
  17852. }
  17853. var configFileUrl = jsonUrl + "/config.json";
  17854. var xhr = new XMLHttpRequest();
  17855. xhr.open("GET", configFileUrl, true);
  17856. xhr.addEventListener("load", function () {
  17857. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17858. try {
  17859. _this._config = JSON.parse(xhr.response);
  17860. _this.updateShaderUniforms();
  17861. _this.updateTextures();
  17862. _this.setFragment(_this._texturePath + "/custom");
  17863. _this._animate = _this._config.animate;
  17864. _this.refreshRate = _this._config.refreshrate;
  17865. }
  17866. catch (ex) {
  17867. noConfigFile();
  17868. }
  17869. }
  17870. else {
  17871. noConfigFile();
  17872. }
  17873. }, false);
  17874. xhr.addEventListener("error", function () {
  17875. noConfigFile();
  17876. }, false);
  17877. try {
  17878. xhr.send();
  17879. }
  17880. catch (ex) {
  17881. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17882. }
  17883. };
  17884. CustomProceduralTexture.prototype.isReady = function () {
  17885. if (!_super.prototype.isReady.call(this)) {
  17886. return false;
  17887. }
  17888. for (var name in this._textures) {
  17889. var texture = this._textures[name];
  17890. if (!texture.isReady()) {
  17891. return false;
  17892. }
  17893. }
  17894. return true;
  17895. };
  17896. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17897. if (this._animate) {
  17898. this._time += this.getScene().getAnimationRatio() * 0.03;
  17899. this.updateShaderUniforms();
  17900. }
  17901. _super.prototype.render.call(this, useCameraPostProcess);
  17902. };
  17903. CustomProceduralTexture.prototype.updateTextures = function () {
  17904. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17905. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17906. }
  17907. };
  17908. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17909. if (this._config) {
  17910. for (var j = 0; j < this._config.uniforms.length; j++) {
  17911. var uniform = this._config.uniforms[j];
  17912. switch (uniform.type) {
  17913. case "float":
  17914. this.setFloat(uniform.name, uniform.value);
  17915. break;
  17916. case "color3":
  17917. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17918. break;
  17919. case "color4":
  17920. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17921. break;
  17922. case "vector2":
  17923. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17924. break;
  17925. case "vector3":
  17926. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17927. break;
  17928. }
  17929. }
  17930. }
  17931. this.setFloat("time", this._time);
  17932. };
  17933. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17934. get: function () {
  17935. return this._animate;
  17936. },
  17937. set: function (value) {
  17938. this._animate = value;
  17939. },
  17940. enumerable: true,
  17941. configurable: true
  17942. });
  17943. return CustomProceduralTexture;
  17944. })(BABYLON.ProceduralTexture);
  17945. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17946. })(BABYLON || (BABYLON = {}));
  17947. var BABYLON;
  17948. (function (BABYLON) {
  17949. var EffectFallbacks = (function () {
  17950. function EffectFallbacks() {
  17951. this._defines = {};
  17952. this._currentRank = 32;
  17953. this._maxRank = -1;
  17954. }
  17955. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17956. if (!this._defines[rank]) {
  17957. if (rank < this._currentRank) {
  17958. this._currentRank = rank;
  17959. }
  17960. if (rank > this._maxRank) {
  17961. this._maxRank = rank;
  17962. }
  17963. this._defines[rank] = new Array();
  17964. }
  17965. this._defines[rank].push(define);
  17966. };
  17967. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17968. this._meshRank = rank;
  17969. this._mesh = mesh;
  17970. if (rank > this._maxRank) {
  17971. this._maxRank = rank;
  17972. }
  17973. };
  17974. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17975. get: function () {
  17976. return this._currentRank <= this._maxRank;
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17982. var currentFallbacks = this._defines[this._currentRank];
  17983. for (var index = 0; index < currentFallbacks.length; index++) {
  17984. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17985. }
  17986. if (this._mesh && this._currentRank === this._meshRank) {
  17987. this._mesh.computeBonesUsingShaders = false;
  17988. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17989. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17990. }
  17991. this._currentRank++;
  17992. return currentDefines;
  17993. };
  17994. return EffectFallbacks;
  17995. })();
  17996. BABYLON.EffectFallbacks = EffectFallbacks;
  17997. var Effect = (function () {
  17998. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17999. var _this = this;
  18000. this._isReady = false;
  18001. this._compilationError = "";
  18002. this._valueCache = [];
  18003. this._engine = engine;
  18004. this.name = baseName;
  18005. this.defines = defines;
  18006. this._uniformsNames = uniformsNames.concat(samplers);
  18007. this._samplers = samplers;
  18008. this._attributesNames = attributesNames;
  18009. this.onError = onError;
  18010. this.onCompiled = onCompiled;
  18011. var vertexSource;
  18012. var fragmentSource;
  18013. if (baseName.vertexElement) {
  18014. vertexSource = document.getElementById(baseName.vertexElement);
  18015. if (!vertexSource) {
  18016. vertexSource = baseName.vertexElement;
  18017. }
  18018. }
  18019. else {
  18020. vertexSource = baseName.vertex || baseName;
  18021. }
  18022. if (baseName.fragmentElement) {
  18023. fragmentSource = document.getElementById(baseName.fragmentElement);
  18024. if (!fragmentSource) {
  18025. fragmentSource = baseName.fragmentElement;
  18026. }
  18027. }
  18028. else {
  18029. fragmentSource = baseName.fragment || baseName;
  18030. }
  18031. this._loadVertexShader(vertexSource, function (vertexCode) {
  18032. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18033. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18034. });
  18035. });
  18036. }
  18037. // Properties
  18038. Effect.prototype.isReady = function () {
  18039. return this._isReady;
  18040. };
  18041. Effect.prototype.getProgram = function () {
  18042. return this._program;
  18043. };
  18044. Effect.prototype.getAttributesNames = function () {
  18045. return this._attributesNames;
  18046. };
  18047. Effect.prototype.getAttributeLocation = function (index) {
  18048. return this._attributes[index];
  18049. };
  18050. Effect.prototype.getAttributeLocationByName = function (name) {
  18051. var index = this._attributesNames.indexOf(name);
  18052. return this._attributes[index];
  18053. };
  18054. Effect.prototype.getAttributesCount = function () {
  18055. return this._attributes.length;
  18056. };
  18057. Effect.prototype.getUniformIndex = function (uniformName) {
  18058. return this._uniformsNames.indexOf(uniformName);
  18059. };
  18060. Effect.prototype.getUniform = function (uniformName) {
  18061. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18062. };
  18063. Effect.prototype.getSamplers = function () {
  18064. return this._samplers;
  18065. };
  18066. Effect.prototype.getCompilationError = function () {
  18067. return this._compilationError;
  18068. };
  18069. // Methods
  18070. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18071. // DOM element ?
  18072. if (vertex instanceof HTMLElement) {
  18073. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18074. callback(vertexCode);
  18075. return;
  18076. }
  18077. // Is in local store ?
  18078. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18079. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18080. return;
  18081. }
  18082. var vertexShaderUrl;
  18083. if (vertex[0] === "." || vertex[0] === "/") {
  18084. vertexShaderUrl = vertex;
  18085. }
  18086. else {
  18087. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18088. }
  18089. // Vertex shader
  18090. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18091. };
  18092. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18093. // DOM element ?
  18094. if (fragment instanceof HTMLElement) {
  18095. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18096. callback(fragmentCode);
  18097. return;
  18098. }
  18099. // Is in local store ?
  18100. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18101. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18102. return;
  18103. }
  18104. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18105. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18106. return;
  18107. }
  18108. var fragmentShaderUrl;
  18109. if (fragment[0] === "." || fragment[0] === "/") {
  18110. fragmentShaderUrl = fragment;
  18111. }
  18112. else {
  18113. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18114. }
  18115. // Fragment shader
  18116. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18117. };
  18118. Effect.prototype._dumpShadersName = function () {
  18119. if (this.name.vertexElement) {
  18120. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18121. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18122. }
  18123. else if (this.name.vertex) {
  18124. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18125. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18126. }
  18127. else {
  18128. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18129. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18130. }
  18131. };
  18132. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18133. try {
  18134. var engine = this._engine;
  18135. if (!engine.getCaps().highPrecisionShaderSupported) {
  18136. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18137. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18138. }
  18139. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18140. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18141. this._attributes = engine.getAttributes(this._program, attributesNames);
  18142. for (var index = 0; index < this._samplers.length; index++) {
  18143. var sampler = this.getUniform(this._samplers[index]);
  18144. if (sampler == null) {
  18145. this._samplers.splice(index, 1);
  18146. index--;
  18147. }
  18148. }
  18149. engine.bindSamplers(this);
  18150. this._isReady = true;
  18151. if (this.onCompiled) {
  18152. this.onCompiled(this);
  18153. }
  18154. }
  18155. catch (e) {
  18156. // Is it a problem with precision?
  18157. if (e.message.indexOf("highp") !== -1) {
  18158. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18159. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18160. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18161. return;
  18162. }
  18163. // Let's go through fallbacks then
  18164. if (fallbacks && fallbacks.isMoreFallbacks) {
  18165. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18166. this._dumpShadersName();
  18167. defines = fallbacks.reduce(defines);
  18168. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18169. }
  18170. else {
  18171. BABYLON.Tools.Error("Unable to compile effect: ");
  18172. this._dumpShadersName();
  18173. BABYLON.Tools.Error("Defines: " + defines);
  18174. BABYLON.Tools.Error("Error: " + e.message);
  18175. this._compilationError = e.message;
  18176. if (this.onError) {
  18177. this.onError(this, this._compilationError);
  18178. }
  18179. }
  18180. }
  18181. };
  18182. Object.defineProperty(Effect.prototype, "isSupported", {
  18183. get: function () {
  18184. return this._compilationError === "";
  18185. },
  18186. enumerable: true,
  18187. configurable: true
  18188. });
  18189. Effect.prototype._bindTexture = function (channel, texture) {
  18190. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18191. };
  18192. Effect.prototype.setTexture = function (channel, texture) {
  18193. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18194. };
  18195. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18196. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18197. };
  18198. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18199. if (!this._valueCache[uniformName]) {
  18200. this._valueCache[uniformName] = new BABYLON.Matrix();
  18201. }
  18202. for (var index = 0; index < 16; index++) {
  18203. this._valueCache[uniformName].m[index] = matrix.m[index];
  18204. }
  18205. };
  18206. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18207. if (!this._valueCache[uniformName]) {
  18208. this._valueCache[uniformName] = [x, y];
  18209. return;
  18210. }
  18211. this._valueCache[uniformName][0] = x;
  18212. this._valueCache[uniformName][1] = y;
  18213. };
  18214. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18215. if (!this._valueCache[uniformName]) {
  18216. this._valueCache[uniformName] = [x, y, z];
  18217. return;
  18218. }
  18219. this._valueCache[uniformName][0] = x;
  18220. this._valueCache[uniformName][1] = y;
  18221. this._valueCache[uniformName][2] = z;
  18222. };
  18223. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18224. if (!this._valueCache[uniformName]) {
  18225. this._valueCache[uniformName] = [x, y, z, w];
  18226. return;
  18227. }
  18228. this._valueCache[uniformName][0] = x;
  18229. this._valueCache[uniformName][1] = y;
  18230. this._valueCache[uniformName][2] = z;
  18231. this._valueCache[uniformName][3] = w;
  18232. };
  18233. Effect.prototype.setArray = function (uniformName, array) {
  18234. this._engine.setArray(this.getUniform(uniformName), array);
  18235. return this;
  18236. };
  18237. Effect.prototype.setArray2 = function (uniformName, array) {
  18238. this._engine.setArray2(this.getUniform(uniformName), array);
  18239. return this;
  18240. };
  18241. Effect.prototype.setArray3 = function (uniformName, array) {
  18242. this._engine.setArray3(this.getUniform(uniformName), array);
  18243. return this;
  18244. };
  18245. Effect.prototype.setArray4 = function (uniformName, array) {
  18246. this._engine.setArray4(this.getUniform(uniformName), array);
  18247. return this;
  18248. };
  18249. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18250. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18251. return this;
  18252. };
  18253. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18254. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18255. return this;
  18256. this._cacheMatrix(uniformName, matrix);
  18257. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18258. return this;
  18259. };
  18260. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18261. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18262. return this;
  18263. };
  18264. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18265. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18266. return this;
  18267. };
  18268. Effect.prototype.setFloat = function (uniformName, value) {
  18269. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18270. return this;
  18271. this._valueCache[uniformName] = value;
  18272. this._engine.setFloat(this.getUniform(uniformName), value);
  18273. return this;
  18274. };
  18275. Effect.prototype.setBool = function (uniformName, bool) {
  18276. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18277. return this;
  18278. this._valueCache[uniformName] = bool;
  18279. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18280. return this;
  18281. };
  18282. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18283. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18284. return this;
  18285. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18286. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18287. return this;
  18288. };
  18289. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18290. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18291. return this;
  18292. this._cacheFloat2(uniformName, x, y);
  18293. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18294. return this;
  18295. };
  18296. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18297. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18298. return this;
  18299. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18300. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18301. return this;
  18302. };
  18303. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18304. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18305. return this;
  18306. this._cacheFloat3(uniformName, x, y, z);
  18307. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18308. return this;
  18309. };
  18310. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18311. 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)
  18312. return this;
  18313. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18314. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18315. return this;
  18316. };
  18317. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18318. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18319. return this;
  18320. this._cacheFloat4(uniformName, x, y, z, w);
  18321. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18322. return this;
  18323. };
  18324. Effect.prototype.setColor3 = function (uniformName, color3) {
  18325. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18326. return this;
  18327. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18328. this._engine.setColor3(this.getUniform(uniformName), color3);
  18329. return this;
  18330. };
  18331. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18332. 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)
  18333. return this;
  18334. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18335. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18336. return this;
  18337. };
  18338. // Statics
  18339. Effect.ShadersStore = {};
  18340. return Effect;
  18341. })();
  18342. BABYLON.Effect = Effect;
  18343. })(BABYLON || (BABYLON = {}));
  18344. var BABYLON;
  18345. (function (BABYLON) {
  18346. var MaterialDefines = (function () {
  18347. function MaterialDefines() {
  18348. }
  18349. MaterialDefines.prototype.isEqual = function (other) {
  18350. for (var index = 0; index < this._keys.length; index++) {
  18351. var prop = this._keys[index];
  18352. if (this[prop] !== other[prop]) {
  18353. return false;
  18354. }
  18355. }
  18356. return true;
  18357. };
  18358. MaterialDefines.prototype.cloneTo = function (other) {
  18359. for (var index = 0; index < this._keys.length; index++) {
  18360. var prop = this._keys[index];
  18361. other[prop] = this[prop];
  18362. }
  18363. };
  18364. MaterialDefines.prototype.reset = function () {
  18365. for (var index = 0; index < this._keys.length; index++) {
  18366. var prop = this._keys[index];
  18367. if (typeof (this[prop]) === "number") {
  18368. this[prop] = 0;
  18369. }
  18370. else {
  18371. this[prop] = false;
  18372. }
  18373. }
  18374. };
  18375. MaterialDefines.prototype.toString = function () {
  18376. var result = "";
  18377. for (var index = 0; index < this._keys.length; index++) {
  18378. var prop = this._keys[index];
  18379. if (typeof (this[prop]) === "number") {
  18380. result += "#define " + prop + " " + this[prop] + "\n";
  18381. }
  18382. else if (this[prop]) {
  18383. result += "#define " + prop + "\n";
  18384. }
  18385. }
  18386. return result;
  18387. };
  18388. return MaterialDefines;
  18389. })();
  18390. BABYLON.MaterialDefines = MaterialDefines;
  18391. var Material = (function () {
  18392. function Material(name, scene, doNotAdd) {
  18393. this.name = name;
  18394. this.checkReadyOnEveryCall = false;
  18395. this.checkReadyOnlyOnce = false;
  18396. this.state = "";
  18397. this.alpha = 1.0;
  18398. this.backFaceCulling = true;
  18399. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18400. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18401. this.disableDepthWrite = false;
  18402. this.fogEnabled = true;
  18403. this._wasPreviouslyReady = false;
  18404. this._fillMode = Material.TriangleFillMode;
  18405. this.pointSize = 1.0;
  18406. this.zOffset = 0;
  18407. this.id = name;
  18408. this._scene = scene;
  18409. if (!doNotAdd) {
  18410. scene.materials.push(this);
  18411. }
  18412. }
  18413. Object.defineProperty(Material, "TriangleFillMode", {
  18414. get: function () {
  18415. return Material._TriangleFillMode;
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Object.defineProperty(Material, "WireFrameFillMode", {
  18421. get: function () {
  18422. return Material._WireFrameFillMode;
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. Object.defineProperty(Material, "PointFillMode", {
  18428. get: function () {
  18429. return Material._PointFillMode;
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18435. get: function () {
  18436. return Material._ClockWiseSideOrientation;
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18442. get: function () {
  18443. return Material._CounterClockWiseSideOrientation;
  18444. },
  18445. enumerable: true,
  18446. configurable: true
  18447. });
  18448. Object.defineProperty(Material.prototype, "wireframe", {
  18449. get: function () {
  18450. return this._fillMode === Material.WireFrameFillMode;
  18451. },
  18452. set: function (value) {
  18453. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. Object.defineProperty(Material.prototype, "pointsCloud", {
  18459. get: function () {
  18460. return this._fillMode === Material.PointFillMode;
  18461. },
  18462. set: function (value) {
  18463. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(Material.prototype, "fillMode", {
  18469. get: function () {
  18470. return this._fillMode;
  18471. },
  18472. set: function (value) {
  18473. this._fillMode = value;
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Material.prototype.isReady = function (mesh, useInstances) {
  18479. return true;
  18480. };
  18481. Material.prototype.getEffect = function () {
  18482. return this._effect;
  18483. };
  18484. Material.prototype.getScene = function () {
  18485. return this._scene;
  18486. };
  18487. Material.prototype.needAlphaBlending = function () {
  18488. return (this.alpha < 1.0);
  18489. };
  18490. Material.prototype.needAlphaTesting = function () {
  18491. return false;
  18492. };
  18493. Material.prototype.getAlphaTestTexture = function () {
  18494. return null;
  18495. };
  18496. Material.prototype.trackCreation = function (onCompiled, onError) {
  18497. };
  18498. Material.prototype.markDirty = function () {
  18499. this._wasPreviouslyReady = false;
  18500. };
  18501. Material.prototype._preBind = function () {
  18502. var engine = this._scene.getEngine();
  18503. engine.enableEffect(this._effect);
  18504. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18505. };
  18506. Material.prototype.bind = function (world, mesh) {
  18507. this._scene._cachedMaterial = this;
  18508. if (this.onBind) {
  18509. this.onBind(this, mesh);
  18510. }
  18511. if (this.disableDepthWrite) {
  18512. var engine = this._scene.getEngine();
  18513. this._cachedDepthWriteState = engine.getDepthWrite();
  18514. engine.setDepthWrite(false);
  18515. }
  18516. };
  18517. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18518. };
  18519. Material.prototype.unbind = function () {
  18520. if (this.disableDepthWrite) {
  18521. var engine = this._scene.getEngine();
  18522. engine.setDepthWrite(this._cachedDepthWriteState);
  18523. }
  18524. };
  18525. Material.prototype.clone = function (name) {
  18526. return null;
  18527. };
  18528. Material.prototype.getBindedMeshes = function () {
  18529. var result = new Array();
  18530. for (var index = 0; index < this._scene.meshes.length; index++) {
  18531. var mesh = this._scene.meshes[index];
  18532. if (mesh.material === this) {
  18533. result.push(mesh);
  18534. }
  18535. }
  18536. return result;
  18537. };
  18538. Material.prototype.dispose = function (forceDisposeEffect) {
  18539. // Animations
  18540. this.getScene().stopAnimation(this);
  18541. // Remove from scene
  18542. var index = this._scene.materials.indexOf(this);
  18543. if (index >= 0) {
  18544. this._scene.materials.splice(index, 1);
  18545. }
  18546. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18547. if (forceDisposeEffect && this._effect) {
  18548. this._scene.getEngine()._releaseEffect(this._effect);
  18549. this._effect = null;
  18550. }
  18551. // Remove from meshes
  18552. for (index = 0; index < this._scene.meshes.length; index++) {
  18553. var mesh = this._scene.meshes[index];
  18554. if (mesh.material === this) {
  18555. mesh.material = null;
  18556. }
  18557. }
  18558. // Callback
  18559. if (this.onDispose) {
  18560. this.onDispose();
  18561. }
  18562. };
  18563. Material.prototype.copyTo = function (other) {
  18564. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18565. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18566. other.alpha = this.alpha;
  18567. other.fillMode = this.fillMode;
  18568. other.backFaceCulling = this.backFaceCulling;
  18569. other.fogEnabled = this.fogEnabled;
  18570. other.wireframe = this.wireframe;
  18571. other.zOffset = this.zOffset;
  18572. other.alphaMode = this.alphaMode;
  18573. other.sideOrientation = this.sideOrientation;
  18574. other.disableDepthWrite = this.disableDepthWrite;
  18575. other.pointSize = this.pointSize;
  18576. other.pointsCloud = this.pointsCloud;
  18577. };
  18578. Material.prototype.serialize = function () {
  18579. var serializationObject = {};
  18580. serializationObject.name = this.name;
  18581. serializationObject.alpha = this.alpha;
  18582. serializationObject.id = this.id;
  18583. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18584. serializationObject.backFaceCulling = this.backFaceCulling;
  18585. return serializationObject;
  18586. };
  18587. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18588. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18589. multiMaterial.id = parsedMultiMaterial.id;
  18590. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18591. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18592. var subMatId = parsedMultiMaterial.materials[matIndex];
  18593. if (subMatId) {
  18594. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18595. }
  18596. else {
  18597. multiMaterial.subMaterials.push(null);
  18598. }
  18599. }
  18600. return multiMaterial;
  18601. };
  18602. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18603. if (!parsedMaterial.customType) {
  18604. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18605. }
  18606. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18607. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18608. ;
  18609. };
  18610. Material._TriangleFillMode = 0;
  18611. Material._WireFrameFillMode = 1;
  18612. Material._PointFillMode = 2;
  18613. Material._ClockWiseSideOrientation = 0;
  18614. Material._CounterClockWiseSideOrientation = 1;
  18615. return Material;
  18616. })();
  18617. BABYLON.Material = Material;
  18618. })(BABYLON || (BABYLON = {}));
  18619. var BABYLON;
  18620. (function (BABYLON) {
  18621. var maxSimultaneousLights = 4;
  18622. var FresnelParameters = (function () {
  18623. function FresnelParameters() {
  18624. this.isEnabled = true;
  18625. this.leftColor = BABYLON.Color3.White();
  18626. this.rightColor = BABYLON.Color3.Black();
  18627. this.bias = 0;
  18628. this.power = 1;
  18629. }
  18630. FresnelParameters.prototype.clone = function () {
  18631. var newFresnelParameters = new FresnelParameters();
  18632. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18633. return new FresnelParameters;
  18634. };
  18635. FresnelParameters.prototype.serialize = function () {
  18636. var serializationObject = {};
  18637. serializationObject.isEnabled = this.isEnabled;
  18638. serializationObject.leftColor = this.leftColor;
  18639. serializationObject.rightColor = this.rightColor;
  18640. serializationObject.bias = this.bias;
  18641. serializationObject.power = this.power;
  18642. return serializationObject;
  18643. };
  18644. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18645. var fresnelParameters = new FresnelParameters();
  18646. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18647. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18648. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18649. fresnelParameters.bias = parsedFresnelParameters.bias;
  18650. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18651. return fresnelParameters;
  18652. };
  18653. return FresnelParameters;
  18654. })();
  18655. BABYLON.FresnelParameters = FresnelParameters;
  18656. var StandardMaterialDefines = (function (_super) {
  18657. __extends(StandardMaterialDefines, _super);
  18658. function StandardMaterialDefines() {
  18659. _super.call(this);
  18660. this.DIFFUSE = false;
  18661. this.AMBIENT = false;
  18662. this.OPACITY = false;
  18663. this.OPACITYRGB = false;
  18664. this.REFLECTION = false;
  18665. this.EMISSIVE = false;
  18666. this.SPECULAR = false;
  18667. this.BUMP = false;
  18668. this.SPECULAROVERALPHA = false;
  18669. this.CLIPPLANE = false;
  18670. this.ALPHATEST = false;
  18671. this.ALPHAFROMDIFFUSE = false;
  18672. this.POINTSIZE = false;
  18673. this.FOG = false;
  18674. this.LIGHT0 = false;
  18675. this.LIGHT1 = false;
  18676. this.LIGHT2 = false;
  18677. this.LIGHT3 = false;
  18678. this.SPOTLIGHT0 = false;
  18679. this.SPOTLIGHT1 = false;
  18680. this.SPOTLIGHT2 = false;
  18681. this.SPOTLIGHT3 = false;
  18682. this.HEMILIGHT0 = false;
  18683. this.HEMILIGHT1 = false;
  18684. this.HEMILIGHT2 = false;
  18685. this.HEMILIGHT3 = false;
  18686. this.POINTLIGHT0 = false;
  18687. this.POINTLIGHT1 = false;
  18688. this.POINTLIGHT2 = false;
  18689. this.POINTLIGHT3 = false;
  18690. this.DIRLIGHT0 = false;
  18691. this.DIRLIGHT1 = false;
  18692. this.DIRLIGHT2 = false;
  18693. this.DIRLIGHT3 = false;
  18694. this.SPECULARTERM = false;
  18695. this.SHADOW0 = false;
  18696. this.SHADOW1 = false;
  18697. this.SHADOW2 = false;
  18698. this.SHADOW3 = false;
  18699. this.SHADOWS = false;
  18700. this.SHADOWVSM0 = false;
  18701. this.SHADOWVSM1 = false;
  18702. this.SHADOWVSM2 = false;
  18703. this.SHADOWVSM3 = false;
  18704. this.SHADOWPCF0 = false;
  18705. this.SHADOWPCF1 = false;
  18706. this.SHADOWPCF2 = false;
  18707. this.SHADOWPCF3 = false;
  18708. this.DIFFUSEFRESNEL = false;
  18709. this.OPACITYFRESNEL = false;
  18710. this.REFLECTIONFRESNEL = false;
  18711. this.EMISSIVEFRESNEL = false;
  18712. this.FRESNEL = false;
  18713. this.NORMAL = false;
  18714. this.UV1 = false;
  18715. this.UV2 = false;
  18716. this.VERTEXCOLOR = false;
  18717. this.VERTEXALPHA = false;
  18718. this.NUM_BONE_INFLUENCERS = 0;
  18719. this.BonesPerMesh = 0;
  18720. this.INSTANCES = false;
  18721. this.GLOSSINESS = false;
  18722. this.ROUGHNESS = false;
  18723. this.EMISSIVEASILLUMINATION = false;
  18724. this.LINKEMISSIVEWITHDIFFUSE = false;
  18725. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18726. this.LIGHTMAP = false;
  18727. this.USELIGHTMAPASSHADOWMAP = false;
  18728. this.REFLECTIONMAP_3D = false;
  18729. this.REFLECTIONMAP_SPHERICAL = false;
  18730. this.REFLECTIONMAP_PLANAR = false;
  18731. this.REFLECTIONMAP_CUBIC = false;
  18732. this.REFLECTIONMAP_PROJECTION = false;
  18733. this.REFLECTIONMAP_SKYBOX = false;
  18734. this.REFLECTIONMAP_EXPLICIT = false;
  18735. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18736. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18737. this.INVERTCUBICMAP = false;
  18738. this.LOGARITHMICDEPTH = false;
  18739. this._keys = Object.keys(this);
  18740. }
  18741. return StandardMaterialDefines;
  18742. })(BABYLON.MaterialDefines);
  18743. var StandardMaterial = (function (_super) {
  18744. __extends(StandardMaterial, _super);
  18745. function StandardMaterial(name, scene) {
  18746. var _this = this;
  18747. _super.call(this, name, scene);
  18748. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18749. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18750. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18751. this.specularPower = 64;
  18752. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18753. this.useAlphaFromDiffuseTexture = false;
  18754. this.useEmissiveAsIllumination = false;
  18755. this.linkEmissiveWithDiffuse = false;
  18756. this.useReflectionFresnelFromSpecular = false;
  18757. this.useSpecularOverAlpha = true;
  18758. this.disableLighting = false;
  18759. this.roughness = 0;
  18760. this.useLightmapAsShadowmap = false;
  18761. this.useGlossinessFromSpecularMapAlpha = false;
  18762. this._renderTargets = new BABYLON.SmartArray(16);
  18763. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18764. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18765. this._defines = new StandardMaterialDefines();
  18766. this._cachedDefines = new StandardMaterialDefines();
  18767. this._cachedDefines.BonesPerMesh = -1;
  18768. this.getRenderTargetTextures = function () {
  18769. _this._renderTargets.reset();
  18770. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18771. _this._renderTargets.push(_this.reflectionTexture);
  18772. }
  18773. return _this._renderTargets;
  18774. };
  18775. }
  18776. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18777. get: function () {
  18778. return this._useLogarithmicDepth;
  18779. },
  18780. set: function (value) {
  18781. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. StandardMaterial.prototype.needAlphaBlending = function () {
  18787. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18788. };
  18789. StandardMaterial.prototype.needAlphaTesting = function () {
  18790. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18791. };
  18792. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18793. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18794. };
  18795. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18796. return this.diffuseTexture;
  18797. };
  18798. // Methods
  18799. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18800. if (!mesh) {
  18801. return true;
  18802. }
  18803. if (this._defines.INSTANCES !== useInstances) {
  18804. return false;
  18805. }
  18806. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18807. return true;
  18808. }
  18809. return false;
  18810. };
  18811. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18812. var lightIndex = 0;
  18813. var needNormals = false;
  18814. for (var index = 0; index < scene.lights.length; index++) {
  18815. var light = scene.lights[index];
  18816. if (!light.isEnabled()) {
  18817. continue;
  18818. }
  18819. // Excluded check
  18820. if (light._excludedMeshesIds.length > 0) {
  18821. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18822. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18823. if (excludedMesh) {
  18824. light.excludedMeshes.push(excludedMesh);
  18825. }
  18826. }
  18827. light._excludedMeshesIds = [];
  18828. }
  18829. // Included check
  18830. if (light._includedOnlyMeshesIds.length > 0) {
  18831. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18832. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18833. if (includedOnlyMesh) {
  18834. light.includedOnlyMeshes.push(includedOnlyMesh);
  18835. }
  18836. }
  18837. light._includedOnlyMeshesIds = [];
  18838. }
  18839. if (!light.canAffectMesh(mesh)) {
  18840. continue;
  18841. }
  18842. needNormals = true;
  18843. defines["LIGHT" + lightIndex] = true;
  18844. var type;
  18845. if (light instanceof BABYLON.SpotLight) {
  18846. type = "SPOTLIGHT" + lightIndex;
  18847. }
  18848. else if (light instanceof BABYLON.HemisphericLight) {
  18849. type = "HEMILIGHT" + lightIndex;
  18850. }
  18851. else if (light instanceof BABYLON.PointLight) {
  18852. type = "POINTLIGHT" + lightIndex;
  18853. }
  18854. else {
  18855. type = "DIRLIGHT" + lightIndex;
  18856. }
  18857. defines[type] = true;
  18858. // Specular
  18859. if (!light.specular.equalsFloats(0, 0, 0)) {
  18860. defines["SPECULARTERM"] = true;
  18861. }
  18862. // Shadows
  18863. if (scene.shadowsEnabled) {
  18864. var shadowGenerator = light.getShadowGenerator();
  18865. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18866. defines["SHADOW" + lightIndex] = true;
  18867. defines["SHADOWS"] = true;
  18868. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18869. defines["SHADOWVSM" + lightIndex] = true;
  18870. }
  18871. if (shadowGenerator.usePoissonSampling) {
  18872. defines["SHADOWPCF" + lightIndex] = true;
  18873. }
  18874. }
  18875. }
  18876. lightIndex++;
  18877. if (lightIndex === maxSimultaneousLights)
  18878. break;
  18879. }
  18880. return needNormals;
  18881. };
  18882. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18883. var lightIndex = 0;
  18884. for (var index = 0; index < scene.lights.length; index++) {
  18885. var light = scene.lights[index];
  18886. if (!light.isEnabled()) {
  18887. continue;
  18888. }
  18889. if (!light.canAffectMesh(mesh)) {
  18890. continue;
  18891. }
  18892. if (light instanceof BABYLON.PointLight) {
  18893. // Point Light
  18894. light.transferToEffect(effect, "vLightData" + lightIndex);
  18895. }
  18896. else if (light instanceof BABYLON.DirectionalLight) {
  18897. // Directional Light
  18898. light.transferToEffect(effect, "vLightData" + lightIndex);
  18899. }
  18900. else if (light instanceof BABYLON.SpotLight) {
  18901. // Spot Light
  18902. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18903. }
  18904. else if (light instanceof BABYLON.HemisphericLight) {
  18905. // Hemispheric Light
  18906. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18907. }
  18908. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18909. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18910. if (defines["SPECULARTERM"]) {
  18911. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18912. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18913. }
  18914. // Shadows
  18915. if (scene.shadowsEnabled) {
  18916. var shadowGenerator = light.getShadowGenerator();
  18917. if (mesh.receiveShadows && shadowGenerator) {
  18918. if (!light.needCube()) {
  18919. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18920. }
  18921. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18922. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18923. }
  18924. }
  18925. lightIndex++;
  18926. if (lightIndex === maxSimultaneousLights)
  18927. break;
  18928. }
  18929. };
  18930. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18931. if (this.checkReadyOnlyOnce) {
  18932. if (this._wasPreviouslyReady) {
  18933. return true;
  18934. }
  18935. }
  18936. var scene = this.getScene();
  18937. if (!this.checkReadyOnEveryCall) {
  18938. if (this._renderId === scene.getRenderId()) {
  18939. if (this._checkCache(scene, mesh, useInstances)) {
  18940. return true;
  18941. }
  18942. }
  18943. }
  18944. var engine = scene.getEngine();
  18945. var needNormals = false;
  18946. var needUVs = false;
  18947. this._defines.reset();
  18948. // Textures
  18949. if (scene.texturesEnabled) {
  18950. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18951. if (!this.diffuseTexture.isReady()) {
  18952. return false;
  18953. }
  18954. else {
  18955. needUVs = true;
  18956. this._defines.DIFFUSE = true;
  18957. }
  18958. }
  18959. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18960. if (!this.ambientTexture.isReady()) {
  18961. return false;
  18962. }
  18963. else {
  18964. needUVs = true;
  18965. this._defines.AMBIENT = true;
  18966. }
  18967. }
  18968. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18969. if (!this.opacityTexture.isReady()) {
  18970. return false;
  18971. }
  18972. else {
  18973. needUVs = true;
  18974. this._defines.OPACITY = true;
  18975. if (this.opacityTexture.getAlphaFromRGB) {
  18976. this._defines.OPACITYRGB = true;
  18977. }
  18978. }
  18979. }
  18980. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18981. if (!this.reflectionTexture.isReady()) {
  18982. return false;
  18983. }
  18984. else {
  18985. needNormals = true;
  18986. this._defines.REFLECTION = true;
  18987. if (this.roughness > 0) {
  18988. this._defines.ROUGHNESS = true;
  18989. }
  18990. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18991. this._defines.INVERTCUBICMAP = true;
  18992. }
  18993. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18994. switch (this.reflectionTexture.coordinatesMode) {
  18995. case BABYLON.Texture.CUBIC_MODE:
  18996. case BABYLON.Texture.INVCUBIC_MODE:
  18997. this._defines.REFLECTIONMAP_CUBIC = true;
  18998. break;
  18999. case BABYLON.Texture.EXPLICIT_MODE:
  19000. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19001. break;
  19002. case BABYLON.Texture.PLANAR_MODE:
  19003. this._defines.REFLECTIONMAP_PLANAR = true;
  19004. break;
  19005. case BABYLON.Texture.PROJECTION_MODE:
  19006. this._defines.REFLECTIONMAP_PROJECTION = true;
  19007. break;
  19008. case BABYLON.Texture.SKYBOX_MODE:
  19009. this._defines.REFLECTIONMAP_SKYBOX = true;
  19010. break;
  19011. case BABYLON.Texture.SPHERICAL_MODE:
  19012. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19013. break;
  19014. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19015. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19016. break;
  19017. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19018. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19019. break;
  19020. }
  19021. }
  19022. }
  19023. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19024. if (!this.emissiveTexture.isReady()) {
  19025. return false;
  19026. }
  19027. else {
  19028. needUVs = true;
  19029. this._defines.EMISSIVE = true;
  19030. }
  19031. }
  19032. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19033. if (!this.lightmapTexture.isReady()) {
  19034. return false;
  19035. }
  19036. else {
  19037. needUVs = true;
  19038. this._defines.LIGHTMAP = true;
  19039. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19040. }
  19041. }
  19042. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19043. if (!this.specularTexture.isReady()) {
  19044. return false;
  19045. }
  19046. else {
  19047. needUVs = true;
  19048. this._defines.SPECULAR = true;
  19049. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19050. }
  19051. }
  19052. }
  19053. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19054. if (!this.bumpTexture.isReady()) {
  19055. return false;
  19056. }
  19057. else {
  19058. needUVs = true;
  19059. this._defines.BUMP = true;
  19060. }
  19061. }
  19062. // Effect
  19063. if (scene.clipPlane) {
  19064. this._defines.CLIPPLANE = true;
  19065. }
  19066. if (engine.getAlphaTesting()) {
  19067. this._defines.ALPHATEST = true;
  19068. }
  19069. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19070. this._defines.ALPHAFROMDIFFUSE = true;
  19071. }
  19072. if (this.useEmissiveAsIllumination) {
  19073. this._defines.EMISSIVEASILLUMINATION = true;
  19074. }
  19075. if (this.linkEmissiveWithDiffuse) {
  19076. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19077. }
  19078. if (this.useReflectionFresnelFromSpecular) {
  19079. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19080. }
  19081. if (this.useLogarithmicDepth) {
  19082. this._defines.LOGARITHMICDEPTH = true;
  19083. }
  19084. // Point size
  19085. if (this.pointsCloud || scene.forcePointsCloud) {
  19086. this._defines.POINTSIZE = true;
  19087. }
  19088. // Fog
  19089. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19090. this._defines.FOG = true;
  19091. }
  19092. if (scene.lightsEnabled && !this.disableLighting) {
  19093. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19094. }
  19095. if (StandardMaterial.FresnelEnabled) {
  19096. // Fresnel
  19097. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19098. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19099. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19100. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19101. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19102. this._defines.DIFFUSEFRESNEL = true;
  19103. }
  19104. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19105. this._defines.OPACITYFRESNEL = true;
  19106. }
  19107. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19108. this._defines.REFLECTIONFRESNEL = true;
  19109. }
  19110. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19111. this._defines.EMISSIVEFRESNEL = true;
  19112. }
  19113. needNormals = true;
  19114. this._defines.FRESNEL = true;
  19115. }
  19116. }
  19117. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19118. this._defines.SPECULAROVERALPHA = true;
  19119. }
  19120. // Attribs
  19121. if (mesh) {
  19122. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19123. this._defines.NORMAL = true;
  19124. }
  19125. if (needUVs) {
  19126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19127. this._defines.UV1 = true;
  19128. }
  19129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19130. this._defines.UV2 = true;
  19131. }
  19132. }
  19133. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19134. this._defines.VERTEXCOLOR = true;
  19135. if (mesh.hasVertexAlpha) {
  19136. this._defines.VERTEXALPHA = true;
  19137. }
  19138. }
  19139. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19140. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19141. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19142. }
  19143. // Instances
  19144. if (useInstances) {
  19145. this._defines.INSTANCES = true;
  19146. }
  19147. }
  19148. // Get correct effect
  19149. if (!this._defines.isEqual(this._cachedDefines)) {
  19150. this._defines.cloneTo(this._cachedDefines);
  19151. scene.resetCachedMaterial();
  19152. // Fallbacks
  19153. var fallbacks = new BABYLON.EffectFallbacks();
  19154. if (this._defines.REFLECTION) {
  19155. fallbacks.addFallback(0, "REFLECTION");
  19156. }
  19157. if (this._defines.SPECULAR) {
  19158. fallbacks.addFallback(0, "SPECULAR");
  19159. }
  19160. if (this._defines.BUMP) {
  19161. fallbacks.addFallback(0, "BUMP");
  19162. }
  19163. if (this._defines.SPECULAROVERALPHA) {
  19164. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19165. }
  19166. if (this._defines.FOG) {
  19167. fallbacks.addFallback(1, "FOG");
  19168. }
  19169. if (this._defines.POINTSIZE) {
  19170. fallbacks.addFallback(0, "POINTSIZE");
  19171. }
  19172. if (this._defines.LOGARITHMICDEPTH) {
  19173. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19174. }
  19175. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19176. if (!this._defines["LIGHT" + lightIndex]) {
  19177. continue;
  19178. }
  19179. if (lightIndex > 0) {
  19180. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19181. }
  19182. if (this._defines["SHADOW" + lightIndex]) {
  19183. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19184. }
  19185. if (this._defines["SHADOWPCF" + lightIndex]) {
  19186. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19187. }
  19188. if (this._defines["SHADOWVSM" + lightIndex]) {
  19189. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19190. }
  19191. }
  19192. if (this._defines.SPECULARTERM) {
  19193. fallbacks.addFallback(0, "SPECULARTERM");
  19194. }
  19195. if (this._defines.DIFFUSEFRESNEL) {
  19196. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19197. }
  19198. if (this._defines.OPACITYFRESNEL) {
  19199. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19200. }
  19201. if (this._defines.REFLECTIONFRESNEL) {
  19202. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19203. }
  19204. if (this._defines.EMISSIVEFRESNEL) {
  19205. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19206. }
  19207. if (this._defines.FRESNEL) {
  19208. fallbacks.addFallback(4, "FRESNEL");
  19209. }
  19210. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19211. fallbacks.addCPUSkinningFallback(0, mesh);
  19212. }
  19213. //Attributes
  19214. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19215. if (this._defines.NORMAL) {
  19216. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19217. }
  19218. if (this._defines.UV1) {
  19219. attribs.push(BABYLON.VertexBuffer.UVKind);
  19220. }
  19221. if (this._defines.UV2) {
  19222. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19223. }
  19224. if (this._defines.VERTEXCOLOR) {
  19225. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19226. }
  19227. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19228. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19229. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19230. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19231. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19232. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19233. }
  19234. }
  19235. if (this._defines.INSTANCES) {
  19236. attribs.push("world0");
  19237. attribs.push("world1");
  19238. attribs.push("world2");
  19239. attribs.push("world3");
  19240. }
  19241. // Legacy browser patch
  19242. var shaderName = "default";
  19243. if (!scene.getEngine().getCaps().standardDerivatives) {
  19244. shaderName = "legacydefault";
  19245. }
  19246. var join = this._defines.toString();
  19247. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19248. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19249. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19250. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19251. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19252. "vFogInfos", "vFogColor", "pointSize",
  19253. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19254. "mBones",
  19255. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19256. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19257. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19258. "logarithmicDepthConstant"
  19259. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19260. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19261. ], join, fallbacks, this.onCompiled, this.onError);
  19262. }
  19263. if (!this._effect.isReady()) {
  19264. return false;
  19265. }
  19266. this._renderId = scene.getRenderId();
  19267. this._wasPreviouslyReady = true;
  19268. if (mesh) {
  19269. if (!mesh._materialDefines) {
  19270. mesh._materialDefines = new StandardMaterialDefines();
  19271. }
  19272. this._defines.cloneTo(mesh._materialDefines);
  19273. }
  19274. return true;
  19275. };
  19276. StandardMaterial.prototype.unbind = function () {
  19277. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19278. this._effect.setTexture("reflection2DSampler", null);
  19279. }
  19280. _super.prototype.unbind.call(this);
  19281. };
  19282. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19283. this._effect.setMatrix("world", world);
  19284. };
  19285. StandardMaterial.prototype.bind = function (world, mesh) {
  19286. var scene = this.getScene();
  19287. // Matrices
  19288. this.bindOnlyWorldMatrix(world);
  19289. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19290. // Bones
  19291. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19292. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19293. }
  19294. if (scene.getCachedMaterial() !== this) {
  19295. if (StandardMaterial.FresnelEnabled) {
  19296. // Fresnel
  19297. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19298. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19299. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19300. }
  19301. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19302. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19303. }
  19304. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19305. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19306. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19307. }
  19308. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19309. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19310. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19311. }
  19312. }
  19313. // Textures
  19314. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19315. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19316. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19317. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19318. }
  19319. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19320. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19321. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19322. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19323. }
  19324. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19325. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19326. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19327. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19328. }
  19329. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19330. if (this.reflectionTexture.isCube) {
  19331. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19332. }
  19333. else {
  19334. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19335. }
  19336. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19337. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19338. }
  19339. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19340. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19341. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19342. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19343. }
  19344. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19345. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19346. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19347. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19348. }
  19349. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19350. this._effect.setTexture("specularSampler", this.specularTexture);
  19351. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19352. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19353. }
  19354. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19355. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19356. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19357. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19358. }
  19359. // Clip plane
  19360. if (scene.clipPlane) {
  19361. var clipPlane = scene.clipPlane;
  19362. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19363. }
  19364. // Point size
  19365. if (this.pointsCloud) {
  19366. this._effect.setFloat("pointSize", this.pointSize);
  19367. }
  19368. // Colors
  19369. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19370. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19371. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19372. if (this._defines.SPECULARTERM) {
  19373. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19374. }
  19375. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19376. }
  19377. // Diffuse
  19378. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19379. // Lights
  19380. if (scene.lightsEnabled && !this.disableLighting) {
  19381. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19382. }
  19383. // View
  19384. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19385. this._effect.setMatrix("view", scene.getViewMatrix());
  19386. }
  19387. // Fog
  19388. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19389. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19390. this._effect.setColor3("vFogColor", scene.fogColor);
  19391. }
  19392. // Log. depth
  19393. if (this._defines.LOGARITHMICDEPTH) {
  19394. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19395. }
  19396. _super.prototype.bind.call(this, world, mesh);
  19397. };
  19398. StandardMaterial.prototype.getAnimatables = function () {
  19399. var results = [];
  19400. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19401. results.push(this.diffuseTexture);
  19402. }
  19403. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19404. results.push(this.ambientTexture);
  19405. }
  19406. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19407. results.push(this.opacityTexture);
  19408. }
  19409. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19410. results.push(this.reflectionTexture);
  19411. }
  19412. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19413. results.push(this.emissiveTexture);
  19414. }
  19415. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19416. results.push(this.specularTexture);
  19417. }
  19418. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19419. results.push(this.bumpTexture);
  19420. }
  19421. return results;
  19422. };
  19423. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19424. if (this.diffuseTexture) {
  19425. this.diffuseTexture.dispose();
  19426. }
  19427. if (this.ambientTexture) {
  19428. this.ambientTexture.dispose();
  19429. }
  19430. if (this.opacityTexture) {
  19431. this.opacityTexture.dispose();
  19432. }
  19433. if (this.reflectionTexture) {
  19434. this.reflectionTexture.dispose();
  19435. }
  19436. if (this.emissiveTexture) {
  19437. this.emissiveTexture.dispose();
  19438. }
  19439. if (this.specularTexture) {
  19440. this.specularTexture.dispose();
  19441. }
  19442. if (this.bumpTexture) {
  19443. this.bumpTexture.dispose();
  19444. }
  19445. _super.prototype.dispose.call(this, forceDisposeEffect);
  19446. };
  19447. StandardMaterial.prototype.clone = function (name) {
  19448. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19449. // Base material
  19450. this.copyTo(newStandardMaterial);
  19451. // Standard material
  19452. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19453. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19454. }
  19455. if (this.ambientTexture && this.ambientTexture.clone) {
  19456. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19457. }
  19458. if (this.opacityTexture && this.opacityTexture.clone) {
  19459. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19460. }
  19461. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19462. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19463. }
  19464. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19465. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19466. }
  19467. if (this.specularTexture && this.specularTexture.clone) {
  19468. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19469. }
  19470. if (this.bumpTexture && this.bumpTexture.clone) {
  19471. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19472. }
  19473. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19474. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19475. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19476. }
  19477. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19478. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19479. newStandardMaterial.specularColor = this.specularColor.clone();
  19480. newStandardMaterial.specularPower = this.specularPower;
  19481. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19482. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19483. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19484. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19485. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19486. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19487. newStandardMaterial.roughness = this.roughness;
  19488. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19489. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19490. }
  19491. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19492. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19493. }
  19494. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19495. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19496. }
  19497. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19498. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19499. }
  19500. return newStandardMaterial;
  19501. };
  19502. StandardMaterial.prototype.serialize = function () {
  19503. var serializationObject = _super.prototype.serialize.call(this);
  19504. serializationObject.ambient = this.ambientColor.asArray();
  19505. serializationObject.diffuse = this.diffuseColor.asArray();
  19506. serializationObject.specular = this.specularColor.asArray();
  19507. serializationObject.specularPower = this.specularPower;
  19508. serializationObject.emissive = this.emissiveColor.asArray();
  19509. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19510. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19511. if (this.diffuseTexture) {
  19512. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19513. }
  19514. if (this.diffuseFresnelParameters) {
  19515. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19516. }
  19517. if (this.ambientTexture) {
  19518. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19519. }
  19520. if (this.opacityTexture) {
  19521. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19522. }
  19523. if (this.opacityFresnelParameters) {
  19524. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19525. }
  19526. if (this.reflectionTexture) {
  19527. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19528. }
  19529. if (this.reflectionFresnelParameters) {
  19530. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19531. }
  19532. if (this.emissiveTexture) {
  19533. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19534. }
  19535. if (this.lightmapTexture) {
  19536. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19537. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19538. }
  19539. if (this.emissiveFresnelParameters) {
  19540. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19541. }
  19542. if (this.specularTexture) {
  19543. serializationObject.specularTexture = this.specularTexture.serialize();
  19544. }
  19545. if (this.bumpTexture) {
  19546. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19547. }
  19548. return serializationObject;
  19549. };
  19550. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19551. var material = new StandardMaterial(source.name, scene);
  19552. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19553. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19554. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19555. material.specularPower = source.specularPower;
  19556. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19557. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19558. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19559. material.alpha = source.alpha;
  19560. material.id = source.id;
  19561. if (source.disableDepthWrite) {
  19562. material.disableDepthWrite = source.disableDepthWrite;
  19563. }
  19564. BABYLON.Tags.AddTagsTo(material, source.tags);
  19565. material.backFaceCulling = source.backFaceCulling;
  19566. material.wireframe = source.wireframe;
  19567. if (source.diffuseTexture) {
  19568. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19569. }
  19570. if (source.diffuseFresnelParameters) {
  19571. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19572. }
  19573. if (source.ambientTexture) {
  19574. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19575. }
  19576. if (source.opacityTexture) {
  19577. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19578. }
  19579. if (source.opacityFresnelParameters) {
  19580. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19581. }
  19582. if (source.reflectionTexture) {
  19583. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19584. }
  19585. if (source.reflectionFresnelParameters) {
  19586. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19587. }
  19588. if (source.emissiveTexture) {
  19589. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19590. }
  19591. if (source.lightmapTexture) {
  19592. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19593. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19594. }
  19595. if (source.emissiveFresnelParameters) {
  19596. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19597. }
  19598. if (source.specularTexture) {
  19599. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19600. }
  19601. if (source.bumpTexture) {
  19602. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19603. }
  19604. if (source.checkReadyOnlyOnce) {
  19605. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19606. }
  19607. return material;
  19608. };
  19609. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19610. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19611. // Statics
  19612. // Flags used to enable or disable a type of texture for all Standard Materials
  19613. StandardMaterial.DiffuseTextureEnabled = true;
  19614. StandardMaterial.AmbientTextureEnabled = true;
  19615. StandardMaterial.OpacityTextureEnabled = true;
  19616. StandardMaterial.ReflectionTextureEnabled = true;
  19617. StandardMaterial.EmissiveTextureEnabled = true;
  19618. StandardMaterial.SpecularTextureEnabled = true;
  19619. StandardMaterial.BumpTextureEnabled = true;
  19620. StandardMaterial.FresnelEnabled = true;
  19621. StandardMaterial.LightmapEnabled = true;
  19622. return StandardMaterial;
  19623. })(BABYLON.Material);
  19624. BABYLON.StandardMaterial = StandardMaterial;
  19625. })(BABYLON || (BABYLON = {}));
  19626. var BABYLON;
  19627. (function (BABYLON) {
  19628. var MultiMaterial = (function (_super) {
  19629. __extends(MultiMaterial, _super);
  19630. function MultiMaterial(name, scene) {
  19631. _super.call(this, name, scene, true);
  19632. this.subMaterials = new Array();
  19633. scene.multiMaterials.push(this);
  19634. }
  19635. // Properties
  19636. MultiMaterial.prototype.getSubMaterial = function (index) {
  19637. if (index < 0 || index >= this.subMaterials.length) {
  19638. return this.getScene().defaultMaterial;
  19639. }
  19640. return this.subMaterials[index];
  19641. };
  19642. // Methods
  19643. MultiMaterial.prototype.isReady = function (mesh) {
  19644. for (var index = 0; index < this.subMaterials.length; index++) {
  19645. var subMaterial = this.subMaterials[index];
  19646. if (subMaterial) {
  19647. if (!this.subMaterials[index].isReady(mesh)) {
  19648. return false;
  19649. }
  19650. }
  19651. }
  19652. return true;
  19653. };
  19654. MultiMaterial.prototype.clone = function (name) {
  19655. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19656. for (var index = 0; index < this.subMaterials.length; index++) {
  19657. var subMaterial = this.subMaterials[index];
  19658. newMultiMaterial.subMaterials.push(subMaterial);
  19659. }
  19660. return newMultiMaterial;
  19661. };
  19662. MultiMaterial.prototype.serialize = function () {
  19663. var serializationObject = {};
  19664. serializationObject.name = this.name;
  19665. serializationObject.id = this.id;
  19666. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19667. serializationObject.materials = [];
  19668. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19669. var subMat = this.subMaterials[matIndex];
  19670. if (subMat) {
  19671. serializationObject.materials.push(subMat.id);
  19672. }
  19673. else {
  19674. serializationObject.materials.push(null);
  19675. }
  19676. }
  19677. return serializationObject;
  19678. };
  19679. return MultiMaterial;
  19680. })(BABYLON.Material);
  19681. BABYLON.MultiMaterial = MultiMaterial;
  19682. })(BABYLON || (BABYLON = {}));
  19683. var BABYLON;
  19684. (function (BABYLON) {
  19685. var SceneLoader = (function () {
  19686. function SceneLoader() {
  19687. }
  19688. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19689. get: function () {
  19690. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19691. },
  19692. set: function (value) {
  19693. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19699. get: function () {
  19700. return SceneLoader._ShowLoadingScreen;
  19701. },
  19702. set: function (value) {
  19703. SceneLoader._ShowLoadingScreen = value;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19709. var dotPosition = sceneFilename.lastIndexOf(".");
  19710. var queryStringPosition = sceneFilename.indexOf("?");
  19711. if (queryStringPosition === -1) {
  19712. queryStringPosition = sceneFilename.length;
  19713. }
  19714. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19715. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19716. var plugin = this._registeredPlugins[index];
  19717. if (plugin.extensions.indexOf(extension) !== -1) {
  19718. return plugin;
  19719. }
  19720. }
  19721. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19722. };
  19723. // Public functions
  19724. SceneLoader.RegisterPlugin = function (plugin) {
  19725. plugin.extensions = plugin.extensions.toLowerCase();
  19726. SceneLoader._registeredPlugins.push(plugin);
  19727. };
  19728. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19729. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19730. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19731. return;
  19732. }
  19733. var loadingToken = {};
  19734. scene._addPendingData(loadingToken);
  19735. var manifestChecked = function (success) {
  19736. scene.database = database;
  19737. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19738. var importMeshFromData = function (data) {
  19739. var meshes = [];
  19740. var particleSystems = [];
  19741. var skeletons = [];
  19742. try {
  19743. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19744. if (onerror) {
  19745. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19746. }
  19747. scene._removePendingData(loadingToken);
  19748. return;
  19749. }
  19750. }
  19751. catch (e) {
  19752. if (onerror) {
  19753. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19754. }
  19755. scene._removePendingData(loadingToken);
  19756. return;
  19757. }
  19758. if (onsuccess) {
  19759. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19760. onsuccess(meshes, particleSystems, skeletons);
  19761. scene._removePendingData(loadingToken);
  19762. }
  19763. };
  19764. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19765. // Direct load
  19766. importMeshFromData(sceneFilename.substr(5));
  19767. return;
  19768. }
  19769. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19770. importMeshFromData(data);
  19771. }, progressCallBack, database);
  19772. };
  19773. if (scene.getEngine().enableOfflineSupport) {
  19774. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19775. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19776. }
  19777. else {
  19778. manifestChecked(true);
  19779. }
  19780. };
  19781. /**
  19782. * Load a scene
  19783. * @param rootUrl a string that defines the root url for scene and resources
  19784. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19785. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19786. */
  19787. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19788. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19789. };
  19790. /**
  19791. * Append a scene
  19792. * @param rootUrl a string that defines the root url for scene and resources
  19793. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19794. * @param scene is the instance of BABYLON.Scene to append to
  19795. */
  19796. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19797. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19798. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19799. return;
  19800. }
  19801. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19802. var database;
  19803. var loadingToken = {};
  19804. scene._addPendingData(loadingToken);
  19805. if (SceneLoader.ShowLoadingScreen) {
  19806. scene.getEngine().displayLoadingUI();
  19807. }
  19808. var loadSceneFromData = function (data) {
  19809. scene.database = database;
  19810. if (!plugin.load(scene, data, rootUrl)) {
  19811. if (onerror) {
  19812. onerror(scene);
  19813. }
  19814. scene._removePendingData(loadingToken);
  19815. scene.getEngine().hideLoadingUI();
  19816. return;
  19817. }
  19818. if (onsuccess) {
  19819. onsuccess(scene);
  19820. }
  19821. scene._removePendingData(loadingToken);
  19822. if (SceneLoader.ShowLoadingScreen) {
  19823. scene.executeWhenReady(function () {
  19824. scene.getEngine().hideLoadingUI();
  19825. });
  19826. }
  19827. };
  19828. var manifestChecked = function (success) {
  19829. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19830. };
  19831. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19832. // Direct load
  19833. loadSceneFromData(sceneFilename.substr(5));
  19834. return;
  19835. }
  19836. if (rootUrl.indexOf("file:") === -1) {
  19837. if (scene.getEngine().enableOfflineSupport) {
  19838. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19839. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19840. }
  19841. else {
  19842. manifestChecked(true);
  19843. }
  19844. }
  19845. else {
  19846. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19847. }
  19848. };
  19849. // Flags
  19850. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19851. SceneLoader._ShowLoadingScreen = true;
  19852. // Members
  19853. SceneLoader._registeredPlugins = new Array();
  19854. return SceneLoader;
  19855. })();
  19856. BABYLON.SceneLoader = SceneLoader;
  19857. ;
  19858. })(BABYLON || (BABYLON = {}));
  19859. var BABYLON;
  19860. (function (BABYLON) {
  19861. var Internals;
  19862. (function (Internals) {
  19863. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19864. for (var index = 0; index < parsedData.materials.length; index++) {
  19865. var parsedMaterial = parsedData.materials[index];
  19866. if (parsedMaterial.id === id) {
  19867. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  19868. }
  19869. }
  19870. return null;
  19871. };
  19872. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19873. names = (names instanceof Array) ? names : [names];
  19874. for (var i in names) {
  19875. if (mesh.name === names[i]) {
  19876. hierarchyIds.push(mesh.id);
  19877. return true;
  19878. }
  19879. }
  19880. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19881. hierarchyIds.push(mesh.id);
  19882. return true;
  19883. }
  19884. return false;
  19885. };
  19886. BABYLON.SceneLoader.RegisterPlugin({
  19887. extensions: ".babylon",
  19888. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19889. var parsedData = JSON.parse(data);
  19890. var loadedSkeletonsIds = [];
  19891. var loadedMaterialsIds = [];
  19892. var hierarchyIds = [];
  19893. var index;
  19894. for (index = 0; index < parsedData.meshes.length; index++) {
  19895. var parsedMesh = parsedData.meshes[index];
  19896. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19897. if (meshesNames instanceof Array) {
  19898. // Remove found mesh name from list.
  19899. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19900. }
  19901. //Geometry?
  19902. if (parsedMesh.geometryId) {
  19903. //does the file contain geometries?
  19904. if (parsedData.geometries) {
  19905. //find the correct geometry and add it to the scene
  19906. var found = false;
  19907. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19908. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19909. return;
  19910. }
  19911. else {
  19912. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19913. if (parsedGeometryData.id === parsedMesh.geometryId) {
  19914. switch (geometryType) {
  19915. case "boxes":
  19916. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  19917. break;
  19918. case "spheres":
  19919. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  19920. break;
  19921. case "cylinders":
  19922. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  19923. break;
  19924. case "toruses":
  19925. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  19926. break;
  19927. case "grounds":
  19928. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  19929. break;
  19930. case "planes":
  19931. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  19932. break;
  19933. case "torusKnots":
  19934. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  19935. break;
  19936. case "vertexData":
  19937. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  19938. break;
  19939. }
  19940. found = true;
  19941. }
  19942. });
  19943. }
  19944. });
  19945. if (!found) {
  19946. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  19947. }
  19948. }
  19949. }
  19950. // Material ?
  19951. if (parsedMesh.materialId) {
  19952. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19953. if (!materialFound && parsedData.multiMaterials) {
  19954. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19955. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19956. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  19957. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19958. var subMatId = parsedMultiMaterial.materials[matIndex];
  19959. loadedMaterialsIds.push(subMatId);
  19960. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19961. }
  19962. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19963. parsedMultiMaterial.Parse(parsedMultiMaterial, scene);
  19964. materialFound = true;
  19965. break;
  19966. }
  19967. }
  19968. }
  19969. if (!materialFound) {
  19970. loadedMaterialsIds.push(parsedMesh.materialId);
  19971. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  19972. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  19973. }
  19974. }
  19975. }
  19976. // Skeleton ?
  19977. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19978. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19979. if (!skeletonAlreadyLoaded) {
  19980. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19981. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19982. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19983. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  19984. loadedSkeletonsIds.push(parsedSkeleton.id);
  19985. }
  19986. }
  19987. }
  19988. }
  19989. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  19990. meshes.push(mesh);
  19991. }
  19992. }
  19993. // Connecting parents
  19994. var currentMesh;
  19995. for (index = 0; index < scene.meshes.length; index++) {
  19996. currentMesh = scene.meshes[index];
  19997. if (currentMesh._waitingParentId) {
  19998. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19999. currentMesh._waitingParentId = undefined;
  20000. }
  20001. }
  20002. // freeze world matrix application
  20003. for (index = 0; index < scene.meshes.length; index++) {
  20004. currentMesh = scene.meshes[index];
  20005. if (currentMesh._waitingFreezeWorldMatrix) {
  20006. currentMesh.freezeWorldMatrix();
  20007. currentMesh._waitingFreezeWorldMatrix = undefined;
  20008. }
  20009. }
  20010. // Particles
  20011. if (parsedData.particleSystems) {
  20012. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20013. var parsedParticleSystem = parsedData.particleSystems[index];
  20014. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20015. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20016. }
  20017. }
  20018. }
  20019. return true;
  20020. },
  20021. load: function (scene, data, rootUrl) {
  20022. var parsedData = JSON.parse(data);
  20023. // Scene
  20024. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20025. scene.autoClear = parsedData.autoClear;
  20026. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20027. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20028. if (parsedData.gravity) {
  20029. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20030. }
  20031. // Fog
  20032. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20033. scene.fogMode = parsedData.fogMode;
  20034. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20035. scene.fogStart = parsedData.fogStart;
  20036. scene.fogEnd = parsedData.fogEnd;
  20037. scene.fogDensity = parsedData.fogDensity;
  20038. }
  20039. //Physics
  20040. if (parsedData.physicsEnabled) {
  20041. var physicsPlugin;
  20042. if (parsedData.physicsEngine === "cannon") {
  20043. physicsPlugin = new BABYLON.CannonJSPlugin();
  20044. }
  20045. else if (parsedData.physicsEngine === "oimo") {
  20046. physicsPlugin = new BABYLON.OimoJSPlugin();
  20047. }
  20048. //else - default engine, which is currently oimo
  20049. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20050. scene.enablePhysics(physicsGravity, physicsPlugin);
  20051. }
  20052. //collisions, if defined. otherwise, default is true
  20053. if (parsedData.collisionsEnabled != undefined) {
  20054. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20055. }
  20056. scene.workerCollisions = !!parsedData.workerCollisions;
  20057. // Lights
  20058. var index;
  20059. for (index = 0; index < parsedData.lights.length; index++) {
  20060. var parsedLight = parsedData.lights[index];
  20061. BABYLON.Light.Parse(parsedLight, scene);
  20062. }
  20063. // Materials
  20064. if (parsedData.materials) {
  20065. for (index = 0; index < parsedData.materials.length; index++) {
  20066. var parsedMaterial = parsedData.materials[index];
  20067. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20068. }
  20069. }
  20070. if (parsedData.multiMaterials) {
  20071. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20072. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20073. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20074. }
  20075. }
  20076. // Skeletons
  20077. if (parsedData.skeletons) {
  20078. for (index = 0; index < parsedData.skeletons.length; index++) {
  20079. var parsedSkeleton = parsedData.skeletons[index];
  20080. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20081. }
  20082. }
  20083. // Geometries
  20084. var geometries = parsedData.geometries;
  20085. if (geometries) {
  20086. // Boxes
  20087. var boxes = geometries.boxes;
  20088. if (boxes) {
  20089. for (index = 0; index < boxes.length; index++) {
  20090. var parsedBox = boxes[index];
  20091. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20092. }
  20093. }
  20094. // Spheres
  20095. var spheres = geometries.spheres;
  20096. if (spheres) {
  20097. for (index = 0; index < spheres.length; index++) {
  20098. var parsedSphere = spheres[index];
  20099. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20100. }
  20101. }
  20102. // Cylinders
  20103. var cylinders = geometries.cylinders;
  20104. if (cylinders) {
  20105. for (index = 0; index < cylinders.length; index++) {
  20106. var parsedCylinder = cylinders[index];
  20107. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20108. }
  20109. }
  20110. // Toruses
  20111. var toruses = geometries.toruses;
  20112. if (toruses) {
  20113. for (index = 0; index < toruses.length; index++) {
  20114. var parsedTorus = toruses[index];
  20115. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20116. }
  20117. }
  20118. // Grounds
  20119. var grounds = geometries.grounds;
  20120. if (grounds) {
  20121. for (index = 0; index < grounds.length; index++) {
  20122. var parsedGround = grounds[index];
  20123. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20124. }
  20125. }
  20126. // Planes
  20127. var planes = geometries.planes;
  20128. if (planes) {
  20129. for (index = 0; index < planes.length; index++) {
  20130. var parsedPlane = planes[index];
  20131. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20132. }
  20133. }
  20134. // TorusKnots
  20135. var torusKnots = geometries.torusKnots;
  20136. if (torusKnots) {
  20137. for (index = 0; index < torusKnots.length; index++) {
  20138. var parsedTorusKnot = torusKnots[index];
  20139. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20140. }
  20141. }
  20142. // VertexData
  20143. var vertexData = geometries.vertexData;
  20144. if (vertexData) {
  20145. for (index = 0; index < vertexData.length; index++) {
  20146. var parsedVertexData = vertexData[index];
  20147. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20148. }
  20149. }
  20150. }
  20151. // Meshes
  20152. for (index = 0; index < parsedData.meshes.length; index++) {
  20153. var parsedMesh = parsedData.meshes[index];
  20154. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20155. }
  20156. // Cameras
  20157. for (index = 0; index < parsedData.cameras.length; index++) {
  20158. var parsedCamera = parsedData.cameras[index];
  20159. BABYLON.Camera.Parse(parsedCamera, scene);
  20160. }
  20161. if (parsedData.activeCameraID) {
  20162. scene.setActiveCameraByID(parsedData.activeCameraID);
  20163. }
  20164. // Browsing all the graph to connect the dots
  20165. for (index = 0; index < scene.cameras.length; index++) {
  20166. var camera = scene.cameras[index];
  20167. if (camera._waitingParentId) {
  20168. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20169. camera._waitingParentId = undefined;
  20170. }
  20171. }
  20172. for (index = 0; index < scene.lights.length; index++) {
  20173. var light = scene.lights[index];
  20174. if (light._waitingParentId) {
  20175. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20176. light._waitingParentId = undefined;
  20177. }
  20178. }
  20179. // Sounds
  20180. if (BABYLON.AudioEngine && parsedData.sounds) {
  20181. for (index = 0; index < parsedData.sounds.length; index++) {
  20182. var parsedSound = parsedData.sounds[index];
  20183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20184. BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20185. }
  20186. else {
  20187. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20188. }
  20189. }
  20190. }
  20191. // Connect parents & children and parse actions
  20192. for (index = 0; index < scene.meshes.length; index++) {
  20193. var mesh = scene.meshes[index];
  20194. if (mesh._waitingParentId) {
  20195. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20196. mesh._waitingParentId = undefined;
  20197. }
  20198. if (mesh._waitingActions) {
  20199. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20200. mesh._waitingActions = undefined;
  20201. }
  20202. }
  20203. // freeze world matrix application
  20204. for (index = 0; index < scene.meshes.length; index++) {
  20205. var currentMesh = scene.meshes[index];
  20206. if (currentMesh._waitingFreezeWorldMatrix) {
  20207. currentMesh.freezeWorldMatrix();
  20208. currentMesh._waitingFreezeWorldMatrix = undefined;
  20209. }
  20210. }
  20211. // Particles Systems
  20212. if (parsedData.particleSystems) {
  20213. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20214. var parsedParticleSystem = parsedData.particleSystems[index];
  20215. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20216. }
  20217. }
  20218. // Lens flares
  20219. if (parsedData.lensFlareSystems) {
  20220. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20221. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20222. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20223. }
  20224. }
  20225. // Shadows
  20226. if (parsedData.shadowGenerators) {
  20227. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20228. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20229. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20230. }
  20231. }
  20232. // Actions (scene)
  20233. if (parsedData.actions) {
  20234. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20235. }
  20236. // Finish
  20237. return true;
  20238. }
  20239. });
  20240. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20241. })(BABYLON || (BABYLON = {}));
  20242. var BABYLON;
  20243. (function (BABYLON) {
  20244. var SpriteManager = (function () {
  20245. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20247. this.name = name;
  20248. this.cellSize = cellSize;
  20249. this.sprites = new Array();
  20250. this.renderingGroupId = 0;
  20251. this.layerMask = 0x0FFFFFFF;
  20252. this.fogEnabled = true;
  20253. this.isPickable = false;
  20254. this._vertexDeclaration = [4, 4, 4, 4];
  20255. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20256. this._capacity = capacity;
  20257. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20258. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20259. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20260. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20261. this._scene = scene;
  20262. this._scene.spriteManagers.push(this);
  20263. // VBO
  20264. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20265. var indices = [];
  20266. var index = 0;
  20267. for (var count = 0; count < capacity; count++) {
  20268. indices.push(index);
  20269. indices.push(index + 1);
  20270. indices.push(index + 2);
  20271. indices.push(index);
  20272. indices.push(index + 2);
  20273. indices.push(index + 3);
  20274. index += 4;
  20275. }
  20276. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20277. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20278. // Effects
  20279. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20280. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20281. }
  20282. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20283. var arrayOffset = index * 16;
  20284. if (offsetX === 0)
  20285. offsetX = this._epsilon;
  20286. else if (offsetX === 1)
  20287. offsetX = 1 - this._epsilon;
  20288. if (offsetY === 0)
  20289. offsetY = this._epsilon;
  20290. else if (offsetY === 1)
  20291. offsetY = 1 - this._epsilon;
  20292. this._vertices[arrayOffset] = sprite.position.x;
  20293. this._vertices[arrayOffset + 1] = sprite.position.y;
  20294. this._vertices[arrayOffset + 2] = sprite.position.z;
  20295. this._vertices[arrayOffset + 3] = sprite.angle;
  20296. this._vertices[arrayOffset + 4] = sprite.width;
  20297. this._vertices[arrayOffset + 5] = sprite.height;
  20298. this._vertices[arrayOffset + 6] = offsetX;
  20299. this._vertices[arrayOffset + 7] = offsetY;
  20300. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20301. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20302. var offset = (sprite.cellIndex / rowSize) >> 0;
  20303. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20304. this._vertices[arrayOffset + 11] = offset;
  20305. // Color
  20306. this._vertices[arrayOffset + 12] = sprite.color.r;
  20307. this._vertices[arrayOffset + 13] = sprite.color.g;
  20308. this._vertices[arrayOffset + 14] = sprite.color.b;
  20309. this._vertices[arrayOffset + 15] = sprite.color.a;
  20310. };
  20311. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20312. var count = Math.min(this._capacity, this.sprites.length);
  20313. var min = BABYLON.Vector3.Zero();
  20314. var max = BABYLON.Vector3.Zero();
  20315. var distance = Number.MAX_VALUE;
  20316. var currentSprite;
  20317. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20318. var cameraView = camera.getViewMatrix();
  20319. for (var index = 0; index < count; index++) {
  20320. var sprite = this.sprites[index];
  20321. if (!sprite) {
  20322. continue;
  20323. }
  20324. if (predicate) {
  20325. if (!predicate(sprite)) {
  20326. continue;
  20327. }
  20328. }
  20329. else if (!sprite.isPickable) {
  20330. continue;
  20331. }
  20332. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20333. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20334. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20335. if (ray.intersectsBoxMinMax(min, max)) {
  20336. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20337. if (distance > currentDistance) {
  20338. distance = currentDistance;
  20339. currentSprite = sprite;
  20340. if (fastCheck) {
  20341. break;
  20342. }
  20343. }
  20344. }
  20345. }
  20346. if (currentSprite) {
  20347. var result = new BABYLON.PickingInfo();
  20348. result.hit = true;
  20349. result.pickedSprite = currentSprite;
  20350. result.distance = distance;
  20351. return result;
  20352. }
  20353. return null;
  20354. };
  20355. SpriteManager.prototype.render = function () {
  20356. // Check
  20357. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20358. return;
  20359. var engine = this._scene.getEngine();
  20360. var baseSize = this._spriteTexture.getBaseSize();
  20361. // Sprites
  20362. var deltaTime = engine.getDeltaTime();
  20363. var max = Math.min(this._capacity, this.sprites.length);
  20364. var rowSize = baseSize.width / this.cellSize;
  20365. var offset = 0;
  20366. for (var index = 0; index < max; index++) {
  20367. var sprite = this.sprites[index];
  20368. if (!sprite) {
  20369. continue;
  20370. }
  20371. sprite._animate(deltaTime);
  20372. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20373. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20374. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20375. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20376. }
  20377. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20378. // Render
  20379. var effect = this._effectBase;
  20380. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20381. effect = this._effectFog;
  20382. }
  20383. engine.enableEffect(effect);
  20384. var viewMatrix = this._scene.getViewMatrix();
  20385. effect.setTexture("diffuseSampler", this._spriteTexture);
  20386. effect.setMatrix("view", viewMatrix);
  20387. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20388. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20389. // Fog
  20390. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20391. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20392. effect.setColor3("vFogColor", this._scene.fogColor);
  20393. }
  20394. // VBOs
  20395. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20396. // Draw order
  20397. engine.setDepthFunctionToLessOrEqual();
  20398. effect.setBool("alphaTest", true);
  20399. engine.setColorWrite(false);
  20400. engine.draw(true, 0, max * 6);
  20401. engine.setColorWrite(true);
  20402. effect.setBool("alphaTest", false);
  20403. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20404. engine.draw(true, 0, max * 6);
  20405. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20406. };
  20407. SpriteManager.prototype.dispose = function () {
  20408. if (this._vertexBuffer) {
  20409. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20410. this._vertexBuffer = null;
  20411. }
  20412. if (this._indexBuffer) {
  20413. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20414. this._indexBuffer = null;
  20415. }
  20416. if (this._spriteTexture) {
  20417. this._spriteTexture.dispose();
  20418. this._spriteTexture = null;
  20419. }
  20420. // Remove from scene
  20421. var index = this._scene.spriteManagers.indexOf(this);
  20422. this._scene.spriteManagers.splice(index, 1);
  20423. // Callback
  20424. if (this.onDispose) {
  20425. this.onDispose();
  20426. }
  20427. };
  20428. return SpriteManager;
  20429. })();
  20430. BABYLON.SpriteManager = SpriteManager;
  20431. })(BABYLON || (BABYLON = {}));
  20432. var BABYLON;
  20433. (function (BABYLON) {
  20434. var Sprite = (function () {
  20435. function Sprite(name, manager) {
  20436. this.name = name;
  20437. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20438. this.width = 1.0;
  20439. this.height = 1.0;
  20440. this.angle = 0;
  20441. this.cellIndex = 0;
  20442. this.invertU = 0;
  20443. this.invertV = 0;
  20444. this.animations = new Array();
  20445. this.isPickable = false;
  20446. this._animationStarted = false;
  20447. this._loopAnimation = false;
  20448. this._fromIndex = 0;
  20449. this._toIndex = 0;
  20450. this._delay = 0;
  20451. this._direction = 1;
  20452. this._frameCount = 0;
  20453. this._time = 0;
  20454. this._manager = manager;
  20455. this._manager.sprites.push(this);
  20456. this.position = BABYLON.Vector3.Zero();
  20457. }
  20458. Object.defineProperty(Sprite.prototype, "size", {
  20459. get: function () {
  20460. return this.width;
  20461. },
  20462. set: function (value) {
  20463. this.width = value;
  20464. this.height = value;
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20470. this._fromIndex = from;
  20471. this._toIndex = to;
  20472. this._loopAnimation = loop;
  20473. this._delay = delay;
  20474. this._animationStarted = true;
  20475. this._direction = from < to ? 1 : -1;
  20476. this.cellIndex = from;
  20477. this._time = 0;
  20478. };
  20479. Sprite.prototype.stopAnimation = function () {
  20480. this._animationStarted = false;
  20481. };
  20482. Sprite.prototype._animate = function (deltaTime) {
  20483. if (!this._animationStarted)
  20484. return;
  20485. this._time += deltaTime;
  20486. if (this._time > this._delay) {
  20487. this._time = this._time % this._delay;
  20488. this.cellIndex += this._direction;
  20489. if (this.cellIndex == this._toIndex) {
  20490. if (this._loopAnimation) {
  20491. this.cellIndex = this._fromIndex;
  20492. }
  20493. else {
  20494. this._animationStarted = false;
  20495. if (this.disposeWhenFinishedAnimating) {
  20496. this.dispose();
  20497. }
  20498. }
  20499. }
  20500. }
  20501. };
  20502. Sprite.prototype.dispose = function () {
  20503. for (var i = 0; i < this._manager.sprites.length; i++) {
  20504. if (this._manager.sprites[i] == this) {
  20505. this._manager.sprites.splice(i, 1);
  20506. }
  20507. }
  20508. };
  20509. return Sprite;
  20510. })();
  20511. BABYLON.Sprite = Sprite;
  20512. })(BABYLON || (BABYLON = {}));
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. var Layer = (function () {
  20516. function Layer(name, imgUrl, scene, isBackground, color) {
  20517. this.name = name;
  20518. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20519. this._vertexDeclaration = [2];
  20520. this._vertexStrideSize = 2 * 4;
  20521. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20522. this.isBackground = isBackground === undefined ? true : isBackground;
  20523. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20524. this._scene = scene;
  20525. this._scene.layers.push(this);
  20526. // VBO
  20527. var vertices = [];
  20528. vertices.push(1, 1);
  20529. vertices.push(-1, 1);
  20530. vertices.push(-1, -1);
  20531. vertices.push(1, -1);
  20532. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20533. // Indices
  20534. var indices = [];
  20535. indices.push(0);
  20536. indices.push(1);
  20537. indices.push(2);
  20538. indices.push(0);
  20539. indices.push(2);
  20540. indices.push(3);
  20541. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20542. // Effects
  20543. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20544. }
  20545. Layer.prototype.render = function () {
  20546. // Check
  20547. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20548. return;
  20549. var engine = this._scene.getEngine();
  20550. // Render
  20551. engine.enableEffect(this._effect);
  20552. engine.setState(false);
  20553. // Texture
  20554. this._effect.setTexture("textureSampler", this.texture);
  20555. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20556. // Color
  20557. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20558. // VBOs
  20559. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20560. // Draw order
  20561. engine.setAlphaMode(this.alphaBlendingMode);
  20562. engine.draw(true, 0, 6);
  20563. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20564. };
  20565. Layer.prototype.dispose = function () {
  20566. if (this._vertexBuffer) {
  20567. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20568. this._vertexBuffer = null;
  20569. }
  20570. if (this._indexBuffer) {
  20571. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20572. this._indexBuffer = null;
  20573. }
  20574. if (this.texture) {
  20575. this.texture.dispose();
  20576. this.texture = null;
  20577. }
  20578. // Remove from scene
  20579. var index = this._scene.layers.indexOf(this);
  20580. this._scene.layers.splice(index, 1);
  20581. // Callback
  20582. if (this.onDispose) {
  20583. this.onDispose();
  20584. }
  20585. };
  20586. return Layer;
  20587. })();
  20588. BABYLON.Layer = Layer;
  20589. })(BABYLON || (BABYLON = {}));
  20590. var BABYLON;
  20591. (function (BABYLON) {
  20592. var Particle = (function () {
  20593. function Particle() {
  20594. this.position = BABYLON.Vector3.Zero();
  20595. this.direction = BABYLON.Vector3.Zero();
  20596. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20597. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20598. this.lifeTime = 1.0;
  20599. this.age = 0;
  20600. this.size = 0;
  20601. this.angle = 0;
  20602. this.angularSpeed = 0;
  20603. }
  20604. Particle.prototype.copyTo = function (other) {
  20605. other.position.copyFrom(this.position);
  20606. other.direction.copyFrom(this.direction);
  20607. other.color.copyFrom(this.color);
  20608. other.colorStep.copyFrom(this.colorStep);
  20609. other.lifeTime = this.lifeTime;
  20610. other.age = this.age;
  20611. other.size = this.size;
  20612. other.angle = this.angle;
  20613. other.angularSpeed = this.angularSpeed;
  20614. };
  20615. return Particle;
  20616. })();
  20617. BABYLON.Particle = Particle;
  20618. })(BABYLON || (BABYLON = {}));
  20619. var BABYLON;
  20620. (function (BABYLON) {
  20621. var randomNumber = function (min, max) {
  20622. if (min === max) {
  20623. return (min);
  20624. }
  20625. var random = Math.random();
  20626. return ((random * (max - min)) + min);
  20627. };
  20628. var ParticleSystem = (function () {
  20629. function ParticleSystem(name, capacity, scene, customEffect) {
  20630. var _this = this;
  20631. this.name = name;
  20632. this.renderingGroupId = 0;
  20633. this.emitter = null;
  20634. this.emitRate = 10;
  20635. this.manualEmitCount = -1;
  20636. this.updateSpeed = 0.01;
  20637. this.targetStopDuration = 0;
  20638. this.disposeOnStop = false;
  20639. this.minEmitPower = 1;
  20640. this.maxEmitPower = 1;
  20641. this.minLifeTime = 1;
  20642. this.maxLifeTime = 1;
  20643. this.minSize = 1;
  20644. this.maxSize = 1;
  20645. this.minAngularSpeed = 0;
  20646. this.maxAngularSpeed = 0;
  20647. this.layerMask = 0x0FFFFFFF;
  20648. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20649. this.forceDepthWrite = false;
  20650. this.gravity = BABYLON.Vector3.Zero();
  20651. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20652. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20653. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20654. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20655. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20656. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20657. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20658. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20659. this.particles = new Array();
  20660. this._vertexDeclaration = [3, 4, 4];
  20661. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20662. this._stockParticles = new Array();
  20663. this._newPartsExcess = 0;
  20664. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20665. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20666. this._scaledDirection = BABYLON.Vector3.Zero();
  20667. this._scaledGravity = BABYLON.Vector3.Zero();
  20668. this._currentRenderId = -1;
  20669. this._started = false;
  20670. this._stopped = false;
  20671. this._actualFrame = 0;
  20672. this.id = name;
  20673. this._capacity = capacity;
  20674. this._scene = scene;
  20675. this._customEffect = customEffect;
  20676. scene.particleSystems.push(this);
  20677. // VBO
  20678. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20679. var indices = [];
  20680. var index = 0;
  20681. for (var count = 0; count < capacity; count++) {
  20682. indices.push(index);
  20683. indices.push(index + 1);
  20684. indices.push(index + 2);
  20685. indices.push(index);
  20686. indices.push(index + 2);
  20687. indices.push(index + 3);
  20688. index += 4;
  20689. }
  20690. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20691. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20692. // Default behaviors
  20693. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20694. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20695. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20696. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20697. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20698. };
  20699. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20700. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20701. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20702. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20704. };
  20705. this.updateFunction = function (particles) {
  20706. for (var index = 0; index < particles.length; index++) {
  20707. var particle = particles[index];
  20708. particle.age += _this._scaledUpdateSpeed;
  20709. if (particle.age >= particle.lifeTime) {
  20710. _this.recycleParticle(particle);
  20711. index--;
  20712. continue;
  20713. }
  20714. else {
  20715. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20716. particle.color.addInPlace(_this._scaledColorStep);
  20717. if (particle.color.a < 0)
  20718. particle.color.a = 0;
  20719. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20720. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20721. particle.position.addInPlace(_this._scaledDirection);
  20722. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20723. particle.direction.addInPlace(_this._scaledGravity);
  20724. }
  20725. }
  20726. };
  20727. }
  20728. ParticleSystem.prototype.recycleParticle = function (particle) {
  20729. var lastParticle = this.particles.pop();
  20730. if (lastParticle !== particle) {
  20731. lastParticle.copyTo(particle);
  20732. this._stockParticles.push(lastParticle);
  20733. }
  20734. };
  20735. ParticleSystem.prototype.getCapacity = function () {
  20736. return this._capacity;
  20737. };
  20738. ParticleSystem.prototype.isAlive = function () {
  20739. return this._alive;
  20740. };
  20741. ParticleSystem.prototype.isStarted = function () {
  20742. return this._started;
  20743. };
  20744. ParticleSystem.prototype.start = function () {
  20745. this._started = true;
  20746. this._stopped = false;
  20747. this._actualFrame = 0;
  20748. };
  20749. ParticleSystem.prototype.stop = function () {
  20750. this._stopped = true;
  20751. };
  20752. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20753. var offset = index * 11;
  20754. this._vertices[offset] = particle.position.x;
  20755. this._vertices[offset + 1] = particle.position.y;
  20756. this._vertices[offset + 2] = particle.position.z;
  20757. this._vertices[offset + 3] = particle.color.r;
  20758. this._vertices[offset + 4] = particle.color.g;
  20759. this._vertices[offset + 5] = particle.color.b;
  20760. this._vertices[offset + 6] = particle.color.a;
  20761. this._vertices[offset + 7] = particle.angle;
  20762. this._vertices[offset + 8] = particle.size;
  20763. this._vertices[offset + 9] = offsetX;
  20764. this._vertices[offset + 10] = offsetY;
  20765. };
  20766. ParticleSystem.prototype._update = function (newParticles) {
  20767. // Update current
  20768. this._alive = this.particles.length > 0;
  20769. this.updateFunction(this.particles);
  20770. // Add new ones
  20771. var worldMatrix;
  20772. if (this.emitter.position) {
  20773. worldMatrix = this.emitter.getWorldMatrix();
  20774. }
  20775. else {
  20776. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20777. }
  20778. var particle;
  20779. for (var index = 0; index < newParticles; index++) {
  20780. if (this.particles.length === this._capacity) {
  20781. break;
  20782. }
  20783. if (this._stockParticles.length !== 0) {
  20784. particle = this._stockParticles.pop();
  20785. particle.age = 0;
  20786. }
  20787. else {
  20788. particle = new BABYLON.Particle();
  20789. }
  20790. this.particles.push(particle);
  20791. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20792. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  20793. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20794. particle.size = randomNumber(this.minSize, this.maxSize);
  20795. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20796. this.startPositionFunction(worldMatrix, particle.position, particle);
  20797. var step = randomNumber(0, 1.0);
  20798. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20799. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20800. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20801. }
  20802. };
  20803. ParticleSystem.prototype._getEffect = function () {
  20804. if (this._customEffect) {
  20805. return this._customEffect;
  20806. }
  20807. ;
  20808. var defines = [];
  20809. if (this._scene.clipPlane) {
  20810. defines.push("#define CLIPPLANE");
  20811. }
  20812. // Effect
  20813. var join = defines.join("\n");
  20814. if (this._cachedDefines !== join) {
  20815. this._cachedDefines = join;
  20816. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20817. }
  20818. return this._effect;
  20819. };
  20820. ParticleSystem.prototype.animate = function () {
  20821. if (!this._started)
  20822. return;
  20823. var effect = this._getEffect();
  20824. // Check
  20825. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20826. return;
  20827. if (this._currentRenderId === this._scene.getRenderId()) {
  20828. return;
  20829. }
  20830. this._currentRenderId = this._scene.getRenderId();
  20831. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20832. // determine the number of particles we need to create
  20833. var emitCout;
  20834. if (this.manualEmitCount > -1) {
  20835. emitCout = this.manualEmitCount;
  20836. this.manualEmitCount = 0;
  20837. }
  20838. else {
  20839. emitCout = this.emitRate;
  20840. }
  20841. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20842. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20843. if (this._newPartsExcess > 1.0) {
  20844. newParticles += this._newPartsExcess >> 0;
  20845. this._newPartsExcess -= this._newPartsExcess >> 0;
  20846. }
  20847. this._alive = false;
  20848. if (!this._stopped) {
  20849. this._actualFrame += this._scaledUpdateSpeed;
  20850. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20851. this.stop();
  20852. }
  20853. else {
  20854. newParticles = 0;
  20855. }
  20856. this._update(newParticles);
  20857. // Stopped?
  20858. if (this._stopped) {
  20859. if (!this._alive) {
  20860. this._started = false;
  20861. if (this.disposeOnStop) {
  20862. this._scene._toBeDisposed.push(this);
  20863. }
  20864. }
  20865. }
  20866. // Update VBO
  20867. var offset = 0;
  20868. for (var index = 0; index < this.particles.length; index++) {
  20869. var particle = this.particles[index];
  20870. this._appendParticleVertex(offset++, particle, 0, 0);
  20871. this._appendParticleVertex(offset++, particle, 1, 0);
  20872. this._appendParticleVertex(offset++, particle, 1, 1);
  20873. this._appendParticleVertex(offset++, particle, 0, 1);
  20874. }
  20875. var engine = this._scene.getEngine();
  20876. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20877. };
  20878. ParticleSystem.prototype.render = function () {
  20879. var effect = this._getEffect();
  20880. // Check
  20881. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20882. return 0;
  20883. var engine = this._scene.getEngine();
  20884. // Render
  20885. engine.enableEffect(effect);
  20886. engine.setState(false);
  20887. var viewMatrix = this._scene.getViewMatrix();
  20888. effect.setTexture("diffuseSampler", this.particleTexture);
  20889. effect.setMatrix("view", viewMatrix);
  20890. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20891. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20892. if (this._scene.clipPlane) {
  20893. var clipPlane = this._scene.clipPlane;
  20894. var invView = viewMatrix.clone();
  20895. invView.invert();
  20896. effect.setMatrix("invView", invView);
  20897. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20898. }
  20899. // VBOs
  20900. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20901. // Draw order
  20902. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20903. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  20904. }
  20905. else {
  20906. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20907. }
  20908. if (this.forceDepthWrite) {
  20909. engine.setDepthWrite(true);
  20910. }
  20911. engine.draw(true, 0, this.particles.length * 6);
  20912. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20913. return this.particles.length;
  20914. };
  20915. ParticleSystem.prototype.dispose = function () {
  20916. if (this._vertexBuffer) {
  20917. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20918. this._vertexBuffer = null;
  20919. }
  20920. if (this._indexBuffer) {
  20921. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20922. this._indexBuffer = null;
  20923. }
  20924. if (this.particleTexture) {
  20925. this.particleTexture.dispose();
  20926. this.particleTexture = null;
  20927. }
  20928. // Remove from scene
  20929. var index = this._scene.particleSystems.indexOf(this);
  20930. this._scene.particleSystems.splice(index, 1);
  20931. // Callback
  20932. if (this.onDispose) {
  20933. this.onDispose();
  20934. }
  20935. };
  20936. // Clone
  20937. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20938. var result = new ParticleSystem(name, this._capacity, this._scene);
  20939. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20940. if (newEmitter === undefined) {
  20941. newEmitter = this.emitter;
  20942. }
  20943. result.emitter = newEmitter;
  20944. if (this.particleTexture) {
  20945. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20946. }
  20947. result.start();
  20948. return result;
  20949. };
  20950. ParticleSystem.prototype.serialize = function () {
  20951. var serializationObject = {};
  20952. serializationObject.emitterId = this.emitter.id;
  20953. serializationObject.capacity = this.getCapacity();
  20954. if (this.particleTexture) {
  20955. serializationObject.textureName = this.particleTexture.name;
  20956. }
  20957. serializationObject.minAngularSpeed = this.minAngularSpeed;
  20958. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  20959. serializationObject.minSize = this.minSize;
  20960. serializationObject.maxSize = this.maxSize;
  20961. serializationObject.minLifeTime = this.minLifeTime;
  20962. serializationObject.maxLifeTime = this.maxLifeTime;
  20963. serializationObject.emitRate = this.emitRate;
  20964. serializationObject.minEmitBox = this.minEmitBox.asArray();
  20965. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  20966. serializationObject.gravity = this.gravity.asArray();
  20967. serializationObject.direction1 = this.direction1.asArray();
  20968. serializationObject.direction2 = this.direction2.asArray();
  20969. serializationObject.color1 = this.color1.asArray();
  20970. serializationObject.color2 = this.color2.asArray();
  20971. serializationObject.colorDead = this.colorDead.asArray();
  20972. serializationObject.updateSpeed = this.updateSpeed;
  20973. serializationObject.targetStopDuration = this.targetStopDuration;
  20974. serializationObject.textureMask = this.textureMask.asArray();
  20975. serializationObject.blendMode = this.blendMode;
  20976. return serializationObject;
  20977. };
  20978. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  20979. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  20980. var particleSystem = new ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  20981. if (parsedParticleSystem.textureName) {
  20982. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  20983. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  20984. }
  20985. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  20986. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  20987. particleSystem.minSize = parsedParticleSystem.minSize;
  20988. particleSystem.maxSize = parsedParticleSystem.maxSize;
  20989. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  20990. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  20991. particleSystem.emitter = emitter;
  20992. particleSystem.emitRate = parsedParticleSystem.emitRate;
  20993. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  20994. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  20995. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  20996. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  20997. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  20998. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  20999. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21000. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21001. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21002. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  21003. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21004. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21005. particleSystem.start();
  21006. return particleSystem;
  21007. };
  21008. // Statics
  21009. ParticleSystem.BLENDMODE_ONEONE = 0;
  21010. ParticleSystem.BLENDMODE_STANDARD = 1;
  21011. return ParticleSystem;
  21012. })();
  21013. BABYLON.ParticleSystem = ParticleSystem;
  21014. })(BABYLON || (BABYLON = {}));
  21015. var BABYLON;
  21016. (function (BABYLON) {
  21017. var AnimationRange = (function () {
  21018. function AnimationRange(name, from, to) {
  21019. this.name = name;
  21020. this.from = from;
  21021. this.to = to;
  21022. }
  21023. return AnimationRange;
  21024. })();
  21025. BABYLON.AnimationRange = AnimationRange;
  21026. /**
  21027. * Composed of a frame, and an action function
  21028. */
  21029. var AnimationEvent = (function () {
  21030. function AnimationEvent(frame, action, onlyOnce) {
  21031. this.frame = frame;
  21032. this.action = action;
  21033. this.onlyOnce = onlyOnce;
  21034. this.isDone = false;
  21035. }
  21036. return AnimationEvent;
  21037. })();
  21038. BABYLON.AnimationEvent = AnimationEvent;
  21039. var Animation = (function () {
  21040. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21041. this.name = name;
  21042. this.targetProperty = targetProperty;
  21043. this.framePerSecond = framePerSecond;
  21044. this.dataType = dataType;
  21045. this.loopMode = loopMode;
  21046. this._offsetsCache = {};
  21047. this._highLimitsCache = {};
  21048. this._stopped = false;
  21049. // The set of event that will be linked to this animation
  21050. this._events = new Array();
  21051. this.allowMatricesInterpolation = false;
  21052. this._ranges = new Array();
  21053. this.targetPropertyPath = targetProperty.split(".");
  21054. this.dataType = dataType;
  21055. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21056. }
  21057. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21058. var dataType = undefined;
  21059. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21060. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21061. }
  21062. else if (from instanceof BABYLON.Quaternion) {
  21063. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21064. }
  21065. else if (from instanceof BABYLON.Vector3) {
  21066. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21067. }
  21068. else if (from instanceof BABYLON.Vector2) {
  21069. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21070. }
  21071. else if (from instanceof BABYLON.Color3) {
  21072. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21073. }
  21074. if (dataType == undefined) {
  21075. return null;
  21076. }
  21077. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21078. var keys = [];
  21079. keys.push({ frame: 0, value: from });
  21080. keys.push({ frame: totalFrame, value: to });
  21081. animation.setKeys(keys);
  21082. if (easingFunction !== undefined) {
  21083. animation.setEasingFunction(easingFunction);
  21084. }
  21085. return animation;
  21086. };
  21087. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21088. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21089. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21090. };
  21091. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21092. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21093. node.animations.push(animation);
  21094. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21095. };
  21096. // Methods
  21097. /**
  21098. * Add an event to this animation.
  21099. */
  21100. Animation.prototype.addEvent = function (event) {
  21101. this._events.push(event);
  21102. };
  21103. /**
  21104. * Remove all events found at the given frame
  21105. * @param frame
  21106. */
  21107. Animation.prototype.removeEvents = function (frame) {
  21108. for (var index = 0; index < this._events.length; index++) {
  21109. if (this._events[index].frame === frame) {
  21110. this._events.splice(index, 1);
  21111. index--;
  21112. }
  21113. }
  21114. };
  21115. Animation.prototype.createRange = function (name, from, to) {
  21116. this._ranges.push(new AnimationRange(name, from, to));
  21117. };
  21118. Animation.prototype.deleteRange = function (name) {
  21119. for (var index = 0; index < this._ranges.length; index++) {
  21120. if (this._ranges[index].name === name) {
  21121. this._ranges.splice(index, 1);
  21122. return;
  21123. }
  21124. }
  21125. };
  21126. Animation.prototype.getRange = function (name) {
  21127. for (var index = 0; index < this._ranges.length; index++) {
  21128. if (this._ranges[index].name === name) {
  21129. return this._ranges[index];
  21130. }
  21131. }
  21132. return null;
  21133. };
  21134. Animation.prototype.reset = function () {
  21135. this._offsetsCache = {};
  21136. this._highLimitsCache = {};
  21137. this.currentFrame = 0;
  21138. };
  21139. Animation.prototype.isStopped = function () {
  21140. return this._stopped;
  21141. };
  21142. Animation.prototype.getKeys = function () {
  21143. return this._keys;
  21144. };
  21145. Animation.prototype.getEasingFunction = function () {
  21146. return this._easingFunction;
  21147. };
  21148. Animation.prototype.setEasingFunction = function (easingFunction) {
  21149. this._easingFunction = easingFunction;
  21150. };
  21151. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21152. return startValue + (endValue - startValue) * gradient;
  21153. };
  21154. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21155. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21156. };
  21157. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21158. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21159. };
  21160. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21161. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21162. };
  21163. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21164. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21165. };
  21166. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21167. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21168. };
  21169. Animation.prototype.clone = function () {
  21170. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21171. if (this._keys) {
  21172. clone.setKeys(this._keys);
  21173. }
  21174. return clone;
  21175. };
  21176. Animation.prototype.setKeys = function (values) {
  21177. this._keys = values.slice(0);
  21178. this._offsetsCache = {};
  21179. this._highLimitsCache = {};
  21180. };
  21181. Animation.prototype._getKeyValue = function (value) {
  21182. if (typeof value === "function") {
  21183. return value();
  21184. }
  21185. return value;
  21186. };
  21187. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21188. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21189. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21190. }
  21191. this.currentFrame = currentFrame;
  21192. // Try to get a hash to find the right key
  21193. 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));
  21194. if (this._keys[startKey].frame >= currentFrame) {
  21195. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21196. startKey--;
  21197. }
  21198. }
  21199. for (var key = startKey; key < this._keys.length; key++) {
  21200. if (this._keys[key + 1].frame >= currentFrame) {
  21201. var startValue = this._getKeyValue(this._keys[key].value);
  21202. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21203. // gradient : percent of currentFrame between the frame inf and the frame sup
  21204. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21205. // check for easingFunction and correction of gradient
  21206. if (this._easingFunction != null) {
  21207. gradient = this._easingFunction.ease(gradient);
  21208. }
  21209. switch (this.dataType) {
  21210. // Float
  21211. case Animation.ANIMATIONTYPE_FLOAT:
  21212. switch (loopMode) {
  21213. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21214. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21215. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21216. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21217. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21218. }
  21219. break;
  21220. // Quaternion
  21221. case Animation.ANIMATIONTYPE_QUATERNION:
  21222. var quaternion = null;
  21223. switch (loopMode) {
  21224. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21225. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21226. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21227. break;
  21228. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21229. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21230. break;
  21231. }
  21232. return quaternion;
  21233. // Vector3
  21234. case Animation.ANIMATIONTYPE_VECTOR3:
  21235. switch (loopMode) {
  21236. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21237. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21238. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21239. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21240. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21241. }
  21242. // Vector2
  21243. case Animation.ANIMATIONTYPE_VECTOR2:
  21244. switch (loopMode) {
  21245. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21246. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21247. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21248. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21249. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21250. }
  21251. // Color3
  21252. case Animation.ANIMATIONTYPE_COLOR3:
  21253. switch (loopMode) {
  21254. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21255. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21256. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21257. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21258. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21259. }
  21260. // Matrix
  21261. case Animation.ANIMATIONTYPE_MATRIX:
  21262. switch (loopMode) {
  21263. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21264. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21265. if (this.allowMatricesInterpolation) {
  21266. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21267. }
  21268. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21269. return startValue;
  21270. }
  21271. default:
  21272. break;
  21273. }
  21274. break;
  21275. }
  21276. }
  21277. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21278. };
  21279. Animation.prototype.setValue = function (currentValue) {
  21280. // Set value
  21281. if (this.targetPropertyPath.length > 1) {
  21282. var property = this._target[this.targetPropertyPath[0]];
  21283. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21284. property = property[this.targetPropertyPath[index]];
  21285. }
  21286. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21287. }
  21288. else {
  21289. this._target[this.targetPropertyPath[0]] = currentValue;
  21290. }
  21291. if (this._target.markAsDirty) {
  21292. this._target.markAsDirty(this.targetProperty);
  21293. }
  21294. };
  21295. Animation.prototype.goToFrame = function (frame) {
  21296. if (frame < this._keys[0].frame) {
  21297. frame = this._keys[0].frame;
  21298. }
  21299. else if (frame > this._keys[this._keys.length - 1].frame) {
  21300. frame = this._keys[this._keys.length - 1].frame;
  21301. }
  21302. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21303. this.setValue(currentValue);
  21304. };
  21305. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21306. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21307. this._stopped = true;
  21308. return false;
  21309. }
  21310. var returnValue = true;
  21311. // Adding a start key at frame 0 if missing
  21312. if (this._keys[0].frame !== 0) {
  21313. var newKey = { frame: 0, value: this._keys[0].value };
  21314. this._keys.splice(0, 0, newKey);
  21315. }
  21316. // Check limits
  21317. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21318. from = this._keys[0].frame;
  21319. }
  21320. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21321. to = this._keys[this._keys.length - 1].frame;
  21322. }
  21323. // Compute ratio
  21324. var range = to - from;
  21325. var offsetValue;
  21326. // ratio represents the frame delta between from and to
  21327. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21328. var highLimitValue = 0;
  21329. if (ratio > range && !loop) {
  21330. returnValue = false;
  21331. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21332. }
  21333. else {
  21334. // Get max value if required
  21335. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21336. var keyOffset = to.toString() + from.toString();
  21337. if (!this._offsetsCache[keyOffset]) {
  21338. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21339. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21340. switch (this.dataType) {
  21341. // Float
  21342. case Animation.ANIMATIONTYPE_FLOAT:
  21343. this._offsetsCache[keyOffset] = toValue - fromValue;
  21344. break;
  21345. // Quaternion
  21346. case Animation.ANIMATIONTYPE_QUATERNION:
  21347. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21348. break;
  21349. // Vector3
  21350. case Animation.ANIMATIONTYPE_VECTOR3:
  21351. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21352. // Vector2
  21353. case Animation.ANIMATIONTYPE_VECTOR2:
  21354. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21355. // Color3
  21356. case Animation.ANIMATIONTYPE_COLOR3:
  21357. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21358. default:
  21359. break;
  21360. }
  21361. this._highLimitsCache[keyOffset] = toValue;
  21362. }
  21363. highLimitValue = this._highLimitsCache[keyOffset];
  21364. offsetValue = this._offsetsCache[keyOffset];
  21365. }
  21366. }
  21367. if (offsetValue === undefined) {
  21368. switch (this.dataType) {
  21369. // Float
  21370. case Animation.ANIMATIONTYPE_FLOAT:
  21371. offsetValue = 0;
  21372. break;
  21373. // Quaternion
  21374. case Animation.ANIMATIONTYPE_QUATERNION:
  21375. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21376. break;
  21377. // Vector3
  21378. case Animation.ANIMATIONTYPE_VECTOR3:
  21379. offsetValue = BABYLON.Vector3.Zero();
  21380. break;
  21381. // Vector2
  21382. case Animation.ANIMATIONTYPE_VECTOR2:
  21383. offsetValue = BABYLON.Vector2.Zero();
  21384. break;
  21385. // Color3
  21386. case Animation.ANIMATIONTYPE_COLOR3:
  21387. offsetValue = BABYLON.Color3.Black();
  21388. }
  21389. }
  21390. // Compute value
  21391. var repeatCount = (ratio / range) >> 0;
  21392. var currentFrame = returnValue ? from + ratio % range : to;
  21393. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21394. // Check events
  21395. for (var index = 0; index < this._events.length; index++) {
  21396. if (currentFrame >= this._events[index].frame) {
  21397. var event = this._events[index];
  21398. if (!event.isDone) {
  21399. // If event should be done only once, remove it.
  21400. if (event.onlyOnce) {
  21401. this._events.splice(index, 1);
  21402. index--;
  21403. }
  21404. event.isDone = true;
  21405. event.action();
  21406. } // Don't do anything if the event has already be done.
  21407. }
  21408. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21409. // reset event, the animation is looping
  21410. this._events[index].isDone = false;
  21411. }
  21412. }
  21413. // Set value
  21414. this.setValue(currentValue);
  21415. if (!returnValue) {
  21416. this._stopped = true;
  21417. }
  21418. return returnValue;
  21419. };
  21420. Animation.prototype.serialize = function () {
  21421. var serializationObject = {};
  21422. serializationObject.name = this.name;
  21423. serializationObject.property = this.targetProperty;
  21424. serializationObject.framePerSecond = this.framePerSecond;
  21425. serializationObject.dataType = this.dataType;
  21426. serializationObject.loopBehavior = this.loopMode;
  21427. var dataType = this.dataType;
  21428. serializationObject.keys = [];
  21429. var keys = this.getKeys();
  21430. for (var index = 0; index < keys.length; index++) {
  21431. var animationKey = keys[index];
  21432. var key = {};
  21433. key.frame = animationKey.frame;
  21434. switch (dataType) {
  21435. case Animation.ANIMATIONTYPE_FLOAT:
  21436. key.values = [animationKey.value];
  21437. break;
  21438. case Animation.ANIMATIONTYPE_QUATERNION:
  21439. case Animation.ANIMATIONTYPE_MATRIX:
  21440. case Animation.ANIMATIONTYPE_VECTOR3:
  21441. key.values = animationKey.value.asArray();
  21442. break;
  21443. }
  21444. serializationObject.keys.push(key);
  21445. }
  21446. return serializationObject;
  21447. };
  21448. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21449. get: function () {
  21450. return Animation._ANIMATIONTYPE_FLOAT;
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21456. get: function () {
  21457. return Animation._ANIMATIONTYPE_VECTOR3;
  21458. },
  21459. enumerable: true,
  21460. configurable: true
  21461. });
  21462. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21463. get: function () {
  21464. return Animation._ANIMATIONTYPE_VECTOR2;
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21470. get: function () {
  21471. return Animation._ANIMATIONTYPE_QUATERNION;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21477. get: function () {
  21478. return Animation._ANIMATIONTYPE_MATRIX;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21484. get: function () {
  21485. return Animation._ANIMATIONTYPE_COLOR3;
  21486. },
  21487. enumerable: true,
  21488. configurable: true
  21489. });
  21490. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21491. get: function () {
  21492. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21498. get: function () {
  21499. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21500. },
  21501. enumerable: true,
  21502. configurable: true
  21503. });
  21504. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21505. get: function () {
  21506. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Animation.Parse = function (parsedAnimation) {
  21512. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21513. var dataType = parsedAnimation.dataType;
  21514. var keys = [];
  21515. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21516. var key = parsedAnimation.keys[index];
  21517. var data;
  21518. switch (dataType) {
  21519. case Animation.ANIMATIONTYPE_FLOAT:
  21520. data = key.values[0];
  21521. break;
  21522. case Animation.ANIMATIONTYPE_QUATERNION:
  21523. data = BABYLON.Quaternion.FromArray(key.values);
  21524. break;
  21525. case Animation.ANIMATIONTYPE_MATRIX:
  21526. data = BABYLON.Matrix.FromArray(key.values);
  21527. break;
  21528. case Animation.ANIMATIONTYPE_VECTOR3:
  21529. default:
  21530. data = BABYLON.Vector3.FromArray(key.values);
  21531. break;
  21532. }
  21533. keys.push({
  21534. frame: key.frame,
  21535. value: data
  21536. });
  21537. }
  21538. animation.setKeys(keys);
  21539. return animation;
  21540. };
  21541. Animation.AppendSerializedAnimations = function (source, destination) {
  21542. if (source.animations) {
  21543. destination.animations = [];
  21544. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21545. var animation = source.animations[animationIndex];
  21546. destination.animations.push(animation.serialize());
  21547. }
  21548. }
  21549. };
  21550. // Statics
  21551. Animation._ANIMATIONTYPE_FLOAT = 0;
  21552. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21553. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21554. Animation._ANIMATIONTYPE_MATRIX = 3;
  21555. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21556. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21557. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21558. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21559. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21560. return Animation;
  21561. })();
  21562. BABYLON.Animation = Animation;
  21563. })(BABYLON || (BABYLON = {}));
  21564. var BABYLON;
  21565. (function (BABYLON) {
  21566. var Animatable = (function () {
  21567. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21568. if (fromFrame === void 0) { fromFrame = 0; }
  21569. if (toFrame === void 0) { toFrame = 100; }
  21570. if (loopAnimation === void 0) { loopAnimation = false; }
  21571. if (speedRatio === void 0) { speedRatio = 1.0; }
  21572. this.target = target;
  21573. this.fromFrame = fromFrame;
  21574. this.toFrame = toFrame;
  21575. this.loopAnimation = loopAnimation;
  21576. this.speedRatio = speedRatio;
  21577. this.onAnimationEnd = onAnimationEnd;
  21578. this._animations = new Array();
  21579. this._paused = false;
  21580. this.animationStarted = false;
  21581. if (animations) {
  21582. this.appendAnimations(target, animations);
  21583. }
  21584. this._scene = scene;
  21585. scene._activeAnimatables.push(this);
  21586. }
  21587. // Methods
  21588. Animatable.prototype.getAnimations = function () {
  21589. return this._animations;
  21590. };
  21591. Animatable.prototype.appendAnimations = function (target, animations) {
  21592. for (var index = 0; index < animations.length; index++) {
  21593. var animation = animations[index];
  21594. animation._target = target;
  21595. this._animations.push(animation);
  21596. }
  21597. };
  21598. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21599. var animations = this._animations;
  21600. for (var index = 0; index < animations.length; index++) {
  21601. if (animations[index].targetProperty === property) {
  21602. return animations[index];
  21603. }
  21604. }
  21605. return null;
  21606. };
  21607. Animatable.prototype.reset = function () {
  21608. var animations = this._animations;
  21609. for (var index = 0; index < animations.length; index++) {
  21610. animations[index].reset();
  21611. }
  21612. this._localDelayOffset = null;
  21613. this._pausedDelay = null;
  21614. };
  21615. Animatable.prototype.goToFrame = function (frame) {
  21616. var animations = this._animations;
  21617. for (var index = 0; index < animations.length; index++) {
  21618. animations[index].goToFrame(frame);
  21619. }
  21620. };
  21621. Animatable.prototype.pause = function () {
  21622. if (this._paused) {
  21623. return;
  21624. }
  21625. this._paused = true;
  21626. };
  21627. Animatable.prototype.restart = function () {
  21628. this._paused = false;
  21629. };
  21630. Animatable.prototype.stop = function () {
  21631. var index = this._scene._activeAnimatables.indexOf(this);
  21632. if (index > -1) {
  21633. this._scene._activeAnimatables.splice(index, 1);
  21634. }
  21635. if (this.onAnimationEnd) {
  21636. this.onAnimationEnd();
  21637. }
  21638. };
  21639. Animatable.prototype._animate = function (delay) {
  21640. if (this._paused) {
  21641. this.animationStarted = false;
  21642. if (!this._pausedDelay) {
  21643. this._pausedDelay = delay;
  21644. }
  21645. return true;
  21646. }
  21647. if (!this._localDelayOffset) {
  21648. this._localDelayOffset = delay;
  21649. }
  21650. else if (this._pausedDelay) {
  21651. this._localDelayOffset += delay - this._pausedDelay;
  21652. this._pausedDelay = null;
  21653. }
  21654. // Animating
  21655. var running = false;
  21656. var animations = this._animations;
  21657. var index;
  21658. for (index = 0; index < animations.length; index++) {
  21659. var animation = animations[index];
  21660. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21661. running = running || isRunning;
  21662. }
  21663. this.animationStarted = running;
  21664. if (!running) {
  21665. // Remove from active animatables
  21666. index = this._scene._activeAnimatables.indexOf(this);
  21667. this._scene._activeAnimatables.splice(index, 1);
  21668. }
  21669. if (!running && this.onAnimationEnd) {
  21670. this.onAnimationEnd();
  21671. }
  21672. return running;
  21673. };
  21674. return Animatable;
  21675. })();
  21676. BABYLON.Animatable = Animatable;
  21677. })(BABYLON || (BABYLON = {}));
  21678. var BABYLON;
  21679. (function (BABYLON) {
  21680. var EasingFunction = (function () {
  21681. function EasingFunction() {
  21682. // Properties
  21683. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21684. }
  21685. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21686. get: function () {
  21687. return EasingFunction._EASINGMODE_EASEIN;
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21693. get: function () {
  21694. return EasingFunction._EASINGMODE_EASEOUT;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21700. get: function () {
  21701. return EasingFunction._EASINGMODE_EASEINOUT;
  21702. },
  21703. enumerable: true,
  21704. configurable: true
  21705. });
  21706. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21707. var n = Math.min(Math.max(easingMode, 0), 2);
  21708. this._easingMode = n;
  21709. };
  21710. EasingFunction.prototype.getEasingMode = function () {
  21711. return this._easingMode;
  21712. };
  21713. EasingFunction.prototype.easeInCore = function (gradient) {
  21714. throw new Error('You must implement this method');
  21715. };
  21716. EasingFunction.prototype.ease = function (gradient) {
  21717. switch (this._easingMode) {
  21718. case EasingFunction.EASINGMODE_EASEIN:
  21719. return this.easeInCore(gradient);
  21720. case EasingFunction.EASINGMODE_EASEOUT:
  21721. return (1 - this.easeInCore(1 - gradient));
  21722. }
  21723. if (gradient >= 0.5) {
  21724. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21725. }
  21726. return (this.easeInCore(gradient * 2) * 0.5);
  21727. };
  21728. //Statics
  21729. EasingFunction._EASINGMODE_EASEIN = 0;
  21730. EasingFunction._EASINGMODE_EASEOUT = 1;
  21731. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21732. return EasingFunction;
  21733. })();
  21734. BABYLON.EasingFunction = EasingFunction;
  21735. var CircleEase = (function (_super) {
  21736. __extends(CircleEase, _super);
  21737. function CircleEase() {
  21738. _super.apply(this, arguments);
  21739. }
  21740. CircleEase.prototype.easeInCore = function (gradient) {
  21741. gradient = Math.max(0, Math.min(1, gradient));
  21742. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21743. };
  21744. return CircleEase;
  21745. })(EasingFunction);
  21746. BABYLON.CircleEase = CircleEase;
  21747. var BackEase = (function (_super) {
  21748. __extends(BackEase, _super);
  21749. function BackEase(amplitude) {
  21750. if (amplitude === void 0) { amplitude = 1; }
  21751. _super.call(this);
  21752. this.amplitude = amplitude;
  21753. }
  21754. BackEase.prototype.easeInCore = function (gradient) {
  21755. var num = Math.max(0, this.amplitude);
  21756. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21757. };
  21758. return BackEase;
  21759. })(EasingFunction);
  21760. BABYLON.BackEase = BackEase;
  21761. var BounceEase = (function (_super) {
  21762. __extends(BounceEase, _super);
  21763. function BounceEase(bounces, bounciness) {
  21764. if (bounces === void 0) { bounces = 3; }
  21765. if (bounciness === void 0) { bounciness = 2; }
  21766. _super.call(this);
  21767. this.bounces = bounces;
  21768. this.bounciness = bounciness;
  21769. }
  21770. BounceEase.prototype.easeInCore = function (gradient) {
  21771. var y = Math.max(0.0, this.bounces);
  21772. var bounciness = this.bounciness;
  21773. if (bounciness <= 1.0) {
  21774. bounciness = 1.001;
  21775. }
  21776. var num9 = Math.pow(bounciness, y);
  21777. var num5 = 1.0 - bounciness;
  21778. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21779. var num15 = gradient * num4;
  21780. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21781. var num3 = Math.floor(num65);
  21782. var num13 = num3 + 1.0;
  21783. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21784. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21785. var num7 = (num8 + num12) * 0.5;
  21786. var num6 = gradient - num7;
  21787. var num2 = num7 - num8;
  21788. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21789. };
  21790. return BounceEase;
  21791. })(EasingFunction);
  21792. BABYLON.BounceEase = BounceEase;
  21793. var CubicEase = (function (_super) {
  21794. __extends(CubicEase, _super);
  21795. function CubicEase() {
  21796. _super.apply(this, arguments);
  21797. }
  21798. CubicEase.prototype.easeInCore = function (gradient) {
  21799. return (gradient * gradient * gradient);
  21800. };
  21801. return CubicEase;
  21802. })(EasingFunction);
  21803. BABYLON.CubicEase = CubicEase;
  21804. var ElasticEase = (function (_super) {
  21805. __extends(ElasticEase, _super);
  21806. function ElasticEase(oscillations, springiness) {
  21807. if (oscillations === void 0) { oscillations = 3; }
  21808. if (springiness === void 0) { springiness = 3; }
  21809. _super.call(this);
  21810. this.oscillations = oscillations;
  21811. this.springiness = springiness;
  21812. }
  21813. ElasticEase.prototype.easeInCore = function (gradient) {
  21814. var num2;
  21815. var num3 = Math.max(0.0, this.oscillations);
  21816. var num = Math.max(0.0, this.springiness);
  21817. if (num == 0) {
  21818. num2 = gradient;
  21819. }
  21820. else {
  21821. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21822. }
  21823. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21824. };
  21825. return ElasticEase;
  21826. })(EasingFunction);
  21827. BABYLON.ElasticEase = ElasticEase;
  21828. var ExponentialEase = (function (_super) {
  21829. __extends(ExponentialEase, _super);
  21830. function ExponentialEase(exponent) {
  21831. if (exponent === void 0) { exponent = 2; }
  21832. _super.call(this);
  21833. this.exponent = exponent;
  21834. }
  21835. ExponentialEase.prototype.easeInCore = function (gradient) {
  21836. if (this.exponent <= 0) {
  21837. return gradient;
  21838. }
  21839. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21840. };
  21841. return ExponentialEase;
  21842. })(EasingFunction);
  21843. BABYLON.ExponentialEase = ExponentialEase;
  21844. var PowerEase = (function (_super) {
  21845. __extends(PowerEase, _super);
  21846. function PowerEase(power) {
  21847. if (power === void 0) { power = 2; }
  21848. _super.call(this);
  21849. this.power = power;
  21850. }
  21851. PowerEase.prototype.easeInCore = function (gradient) {
  21852. var y = Math.max(0.0, this.power);
  21853. return Math.pow(gradient, y);
  21854. };
  21855. return PowerEase;
  21856. })(EasingFunction);
  21857. BABYLON.PowerEase = PowerEase;
  21858. var QuadraticEase = (function (_super) {
  21859. __extends(QuadraticEase, _super);
  21860. function QuadraticEase() {
  21861. _super.apply(this, arguments);
  21862. }
  21863. QuadraticEase.prototype.easeInCore = function (gradient) {
  21864. return (gradient * gradient);
  21865. };
  21866. return QuadraticEase;
  21867. })(EasingFunction);
  21868. BABYLON.QuadraticEase = QuadraticEase;
  21869. var QuarticEase = (function (_super) {
  21870. __extends(QuarticEase, _super);
  21871. function QuarticEase() {
  21872. _super.apply(this, arguments);
  21873. }
  21874. QuarticEase.prototype.easeInCore = function (gradient) {
  21875. return (gradient * gradient * gradient * gradient);
  21876. };
  21877. return QuarticEase;
  21878. })(EasingFunction);
  21879. BABYLON.QuarticEase = QuarticEase;
  21880. var QuinticEase = (function (_super) {
  21881. __extends(QuinticEase, _super);
  21882. function QuinticEase() {
  21883. _super.apply(this, arguments);
  21884. }
  21885. QuinticEase.prototype.easeInCore = function (gradient) {
  21886. return (gradient * gradient * gradient * gradient * gradient);
  21887. };
  21888. return QuinticEase;
  21889. })(EasingFunction);
  21890. BABYLON.QuinticEase = QuinticEase;
  21891. var SineEase = (function (_super) {
  21892. __extends(SineEase, _super);
  21893. function SineEase() {
  21894. _super.apply(this, arguments);
  21895. }
  21896. SineEase.prototype.easeInCore = function (gradient) {
  21897. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21898. };
  21899. return SineEase;
  21900. })(EasingFunction);
  21901. BABYLON.SineEase = SineEase;
  21902. var BezierCurveEase = (function (_super) {
  21903. __extends(BezierCurveEase, _super);
  21904. function BezierCurveEase(x1, y1, x2, y2) {
  21905. if (x1 === void 0) { x1 = 0; }
  21906. if (y1 === void 0) { y1 = 0; }
  21907. if (x2 === void 0) { x2 = 1; }
  21908. if (y2 === void 0) { y2 = 1; }
  21909. _super.call(this);
  21910. this.x1 = x1;
  21911. this.y1 = y1;
  21912. this.x2 = x2;
  21913. this.y2 = y2;
  21914. }
  21915. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21916. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21917. };
  21918. return BezierCurveEase;
  21919. })(EasingFunction);
  21920. BABYLON.BezierCurveEase = BezierCurveEase;
  21921. })(BABYLON || (BABYLON = {}));
  21922. var BABYLON;
  21923. (function (BABYLON) {
  21924. var Bone = (function (_super) {
  21925. __extends(Bone, _super);
  21926. function Bone(name, skeleton, parentBone, matrix) {
  21927. _super.call(this, name, skeleton.getScene());
  21928. this.name = name;
  21929. this.children = new Array();
  21930. this.animations = new Array();
  21931. this._worldTransform = new BABYLON.Matrix();
  21932. this._absoluteTransform = new BABYLON.Matrix();
  21933. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21934. this._skeleton = skeleton;
  21935. this._matrix = matrix;
  21936. this._baseMatrix = matrix;
  21937. skeleton.bones.push(this);
  21938. if (parentBone) {
  21939. this._parent = parentBone;
  21940. parentBone.children.push(this);
  21941. }
  21942. else {
  21943. this._parent = null;
  21944. }
  21945. this._updateDifferenceMatrix();
  21946. }
  21947. // Members
  21948. Bone.prototype.getParent = function () {
  21949. return this._parent;
  21950. };
  21951. Bone.prototype.getLocalMatrix = function () {
  21952. return this._matrix;
  21953. };
  21954. Bone.prototype.getBaseMatrix = function () {
  21955. return this._baseMatrix;
  21956. };
  21957. Bone.prototype.getWorldMatrix = function () {
  21958. return this._worldTransform;
  21959. };
  21960. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21961. return this._invertedAbsoluteTransform;
  21962. };
  21963. Bone.prototype.getAbsoluteMatrix = function () {
  21964. var matrix = this._matrix.clone();
  21965. var parent = this._parent;
  21966. while (parent) {
  21967. matrix = matrix.multiply(parent.getLocalMatrix());
  21968. parent = parent.getParent();
  21969. }
  21970. return matrix;
  21971. };
  21972. // Methods
  21973. Bone.prototype.updateMatrix = function (matrix) {
  21974. this._matrix = matrix;
  21975. this._skeleton._markAsDirty();
  21976. this._updateDifferenceMatrix();
  21977. };
  21978. Bone.prototype._updateDifferenceMatrix = function () {
  21979. if (this._parent) {
  21980. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21981. }
  21982. else {
  21983. this._absoluteTransform.copyFrom(this._matrix);
  21984. }
  21985. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21986. for (var index = 0; index < this.children.length; index++) {
  21987. this.children[index]._updateDifferenceMatrix();
  21988. }
  21989. };
  21990. Bone.prototype.markAsDirty = function () {
  21991. this._currentRenderId++;
  21992. this._skeleton._markAsDirty();
  21993. };
  21994. return Bone;
  21995. })(BABYLON.Node);
  21996. BABYLON.Bone = Bone;
  21997. })(BABYLON || (BABYLON = {}));
  21998. var BABYLON;
  21999. (function (BABYLON) {
  22000. var Skeleton = (function () {
  22001. function Skeleton(name, id, scene) {
  22002. this.name = name;
  22003. this.id = id;
  22004. this.bones = new Array();
  22005. this._isDirty = true;
  22006. this._identity = BABYLON.Matrix.Identity();
  22007. this._ranges = new Array();
  22008. this.bones = [];
  22009. this._scene = scene;
  22010. scene.skeletons.push(this);
  22011. this.prepare();
  22012. //make sure it will recalculate the matrix next time prepare is called.
  22013. this._isDirty = true;
  22014. }
  22015. // Members
  22016. Skeleton.prototype.getTransformMatrices = function () {
  22017. return this._transformMatrices;
  22018. };
  22019. Skeleton.prototype.getScene = function () {
  22020. return this._scene;
  22021. };
  22022. // Methods
  22023. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22024. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22025. };
  22026. Skeleton.prototype.deleteAnimationRange = function (name) {
  22027. for (var index = 0; index < this._ranges.length; index++) {
  22028. if (this._ranges[index].name === name) {
  22029. this._ranges.splice(index, 1);
  22030. return;
  22031. }
  22032. }
  22033. };
  22034. Skeleton.prototype.getAnimationRange = function (name) {
  22035. for (var index = 0; index < this._ranges.length; index++) {
  22036. if (this._ranges[index].name === name) {
  22037. return this._ranges[index];
  22038. }
  22039. }
  22040. return null;
  22041. };
  22042. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22043. var range = this.getAnimationRange(name);
  22044. if (!range) {
  22045. return null;
  22046. }
  22047. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22048. };
  22049. Skeleton.prototype._markAsDirty = function () {
  22050. this._isDirty = true;
  22051. };
  22052. Skeleton.prototype.prepare = function () {
  22053. if (!this._isDirty) {
  22054. return;
  22055. }
  22056. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22057. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22058. }
  22059. for (var index = 0; index < this.bones.length; index++) {
  22060. var bone = this.bones[index];
  22061. var parentBone = bone.getParent();
  22062. if (parentBone) {
  22063. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22064. }
  22065. else {
  22066. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22067. }
  22068. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22069. }
  22070. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22071. this._isDirty = false;
  22072. this._scene._activeBones += this.bones.length;
  22073. };
  22074. Skeleton.prototype.getAnimatables = function () {
  22075. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22076. this._animatables = [];
  22077. for (var index = 0; index < this.bones.length; index++) {
  22078. this._animatables.push(this.bones[index]);
  22079. }
  22080. }
  22081. return this._animatables;
  22082. };
  22083. Skeleton.prototype.clone = function (name, id) {
  22084. var result = new Skeleton(name, id || name, this._scene);
  22085. for (var index = 0; index < this.bones.length; index++) {
  22086. var source = this.bones[index];
  22087. var parentBone = null;
  22088. if (source.getParent()) {
  22089. var parentIndex = this.bones.indexOf(source.getParent());
  22090. parentBone = result.bones[parentIndex];
  22091. }
  22092. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22093. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22094. }
  22095. return result;
  22096. };
  22097. Skeleton.prototype.dispose = function () {
  22098. // Animations
  22099. this.getScene().stopAnimation(this);
  22100. // Remove from scene
  22101. this.getScene().removeSkeleton(this);
  22102. };
  22103. Skeleton.prototype.serialize = function () {
  22104. var serializationObject = {};
  22105. serializationObject.name = this.name;
  22106. serializationObject.id = this.id;
  22107. serializationObject.bones = [];
  22108. for (var index = 0; index < this.bones.length; index++) {
  22109. var bone = this.bones[index];
  22110. var serializedBone = {
  22111. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22112. name: bone.name,
  22113. matrix: bone.getLocalMatrix().toArray()
  22114. };
  22115. serializationObject.bones.push(serializedBone);
  22116. if (bone.animations && bone.animations.length > 0) {
  22117. serializedBone.animation = bone.animations[0].serialize();
  22118. }
  22119. }
  22120. return serializationObject;
  22121. };
  22122. Skeleton.Parse = function (parsedSkeleton, scene) {
  22123. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22124. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22125. var parsedBone = parsedSkeleton.bones[index];
  22126. var parentBone = null;
  22127. if (parsedBone.parentBoneIndex > -1) {
  22128. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22129. }
  22130. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22131. if (parsedBone.animation) {
  22132. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22133. }
  22134. }
  22135. return skeleton;
  22136. };
  22137. return Skeleton;
  22138. })();
  22139. BABYLON.Skeleton = Skeleton;
  22140. })(BABYLON || (BABYLON = {}));
  22141. var BABYLON;
  22142. (function (BABYLON) {
  22143. var PostProcess = (function () {
  22144. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22147. this.name = name;
  22148. this.width = -1;
  22149. this.height = -1;
  22150. this._reusable = false;
  22151. this._textures = new BABYLON.SmartArray(2);
  22152. this._currentRenderTextureInd = 0;
  22153. if (camera != null) {
  22154. this._camera = camera;
  22155. this._scene = camera.getScene();
  22156. camera.attachPostProcess(this);
  22157. this._engine = this._scene.getEngine();
  22158. }
  22159. else {
  22160. this._engine = engine;
  22161. }
  22162. this._renderRatio = ratio;
  22163. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22164. this._reusable = reusable || false;
  22165. this._textureType = textureType;
  22166. this._samplers = samplers || [];
  22167. this._samplers.push("textureSampler");
  22168. this._fragmentUrl = fragmentUrl;
  22169. this._parameters = parameters || [];
  22170. this.updateEffect(defines);
  22171. }
  22172. PostProcess.prototype.updateEffect = function (defines) {
  22173. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22174. };
  22175. PostProcess.prototype.isReusable = function () {
  22176. return this._reusable;
  22177. };
  22178. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22179. camera = camera || this._camera;
  22180. var scene = camera.getScene();
  22181. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22182. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22183. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22184. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22185. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22186. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22187. if (this._textures.length > 0) {
  22188. for (var i = 0; i < this._textures.length; i++) {
  22189. this._engine._releaseTexture(this._textures.data[i]);
  22190. }
  22191. this._textures.reset();
  22192. }
  22193. this.width = desiredWidth;
  22194. this.height = desiredHeight;
  22195. 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 }));
  22196. if (this._reusable) {
  22197. 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 }));
  22198. }
  22199. if (this.onSizeChanged) {
  22200. this.onSizeChanged();
  22201. }
  22202. }
  22203. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22204. if (this.onActivate) {
  22205. this.onActivate(camera);
  22206. }
  22207. // Clear
  22208. if (this.clearColor) {
  22209. this._engine.clear(this.clearColor, true, true);
  22210. }
  22211. else {
  22212. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22213. }
  22214. if (this._reusable) {
  22215. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22216. }
  22217. };
  22218. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22219. get: function () {
  22220. return this._effect.isSupported;
  22221. },
  22222. enumerable: true,
  22223. configurable: true
  22224. });
  22225. PostProcess.prototype.apply = function () {
  22226. // Check
  22227. if (!this._effect.isReady())
  22228. return null;
  22229. // States
  22230. this._engine.enableEffect(this._effect);
  22231. this._engine.setState(false);
  22232. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22233. this._engine.setDepthBuffer(false);
  22234. this._engine.setDepthWrite(false);
  22235. // Texture
  22236. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22237. // Parameters
  22238. if (this.onApply) {
  22239. this.onApply(this._effect);
  22240. }
  22241. return this._effect;
  22242. };
  22243. PostProcess.prototype.dispose = function (camera) {
  22244. camera = camera || this._camera;
  22245. if (this._textures.length > 0) {
  22246. for (var i = 0; i < this._textures.length; i++) {
  22247. this._engine._releaseTexture(this._textures.data[i]);
  22248. }
  22249. this._textures.reset();
  22250. }
  22251. if (!camera) {
  22252. return;
  22253. }
  22254. camera.detachPostProcess(this);
  22255. var index = camera._postProcesses.indexOf(this);
  22256. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22257. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22258. }
  22259. };
  22260. return PostProcess;
  22261. })();
  22262. BABYLON.PostProcess = PostProcess;
  22263. })(BABYLON || (BABYLON = {}));
  22264. var BABYLON;
  22265. (function (BABYLON) {
  22266. var PostProcessManager = (function () {
  22267. function PostProcessManager(scene) {
  22268. this._vertexDeclaration = [2];
  22269. this._vertexStrideSize = 2 * 4;
  22270. this._scene = scene;
  22271. }
  22272. PostProcessManager.prototype._prepareBuffers = function () {
  22273. if (this._vertexBuffer) {
  22274. return;
  22275. }
  22276. // VBO
  22277. var vertices = [];
  22278. vertices.push(1, 1);
  22279. vertices.push(-1, 1);
  22280. vertices.push(-1, -1);
  22281. vertices.push(1, -1);
  22282. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22283. // Indices
  22284. var indices = [];
  22285. indices.push(0);
  22286. indices.push(1);
  22287. indices.push(2);
  22288. indices.push(0);
  22289. indices.push(2);
  22290. indices.push(3);
  22291. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22292. };
  22293. // Methods
  22294. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22295. var postProcesses = this._scene.activeCamera._postProcesses;
  22296. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22297. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22298. return false;
  22299. }
  22300. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22301. return true;
  22302. };
  22303. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22304. var engine = this._scene.getEngine();
  22305. for (var index = 0; index < postProcesses.length; index++) {
  22306. if (index < postProcesses.length - 1) {
  22307. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22308. }
  22309. else {
  22310. if (targetTexture) {
  22311. engine.bindFramebuffer(targetTexture);
  22312. }
  22313. else {
  22314. engine.restoreDefaultFramebuffer();
  22315. }
  22316. }
  22317. var pp = postProcesses[index];
  22318. var effect = pp.apply();
  22319. if (effect) {
  22320. if (pp.onBeforeRender) {
  22321. pp.onBeforeRender(effect);
  22322. }
  22323. // VBOs
  22324. this._prepareBuffers();
  22325. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22326. // Draw order
  22327. engine.draw(true, 0, 6);
  22328. if (pp.onAfterRender) {
  22329. pp.onAfterRender(effect);
  22330. }
  22331. }
  22332. }
  22333. // Restore depth buffer
  22334. engine.setDepthBuffer(true);
  22335. engine.setDepthWrite(true);
  22336. };
  22337. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22338. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22339. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22340. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22341. return;
  22342. }
  22343. var engine = this._scene.getEngine();
  22344. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22345. if (index < postProcessesTakenIndices.length - 1) {
  22346. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22347. }
  22348. else {
  22349. if (targetTexture) {
  22350. engine.bindFramebuffer(targetTexture, faceIndex);
  22351. }
  22352. else {
  22353. engine.restoreDefaultFramebuffer();
  22354. }
  22355. }
  22356. if (doNotPresent) {
  22357. break;
  22358. }
  22359. var pp = postProcesses[postProcessesTakenIndices[index]];
  22360. var effect = pp.apply();
  22361. if (effect) {
  22362. if (pp.onBeforeRender) {
  22363. pp.onBeforeRender(effect);
  22364. }
  22365. // VBOs
  22366. this._prepareBuffers();
  22367. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22368. // Draw order
  22369. engine.draw(true, 0, 6);
  22370. if (pp.onAfterRender) {
  22371. pp.onAfterRender(effect);
  22372. }
  22373. }
  22374. }
  22375. // Restore depth buffer
  22376. engine.setDepthBuffer(true);
  22377. engine.setDepthWrite(true);
  22378. };
  22379. PostProcessManager.prototype.dispose = function () {
  22380. if (this._vertexBuffer) {
  22381. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22382. this._vertexBuffer = null;
  22383. }
  22384. if (this._indexBuffer) {
  22385. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22386. this._indexBuffer = null;
  22387. }
  22388. };
  22389. return PostProcessManager;
  22390. })();
  22391. BABYLON.PostProcessManager = PostProcessManager;
  22392. })(BABYLON || (BABYLON = {}));
  22393. var BABYLON;
  22394. (function (BABYLON) {
  22395. var PassPostProcess = (function (_super) {
  22396. __extends(PassPostProcess, _super);
  22397. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22398. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22399. }
  22400. return PassPostProcess;
  22401. })(BABYLON.PostProcess);
  22402. BABYLON.PassPostProcess = PassPostProcess;
  22403. })(BABYLON || (BABYLON = {}));
  22404. var BABYLON;
  22405. (function (BABYLON) {
  22406. var PhysicsEngine = (function () {
  22407. function PhysicsEngine(plugin) {
  22408. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22409. }
  22410. PhysicsEngine.prototype._initialize = function (gravity) {
  22411. this._currentPlugin.initialize();
  22412. this._setGravity(gravity);
  22413. };
  22414. PhysicsEngine.prototype._runOneStep = function (delta) {
  22415. if (delta > 0.1) {
  22416. delta = 0.1;
  22417. }
  22418. else if (delta <= 0) {
  22419. delta = 1.0 / 60.0;
  22420. }
  22421. this._currentPlugin.runOneStep(delta);
  22422. };
  22423. PhysicsEngine.prototype._setGravity = function (gravity) {
  22424. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22425. this._currentPlugin.setGravity(this.gravity);
  22426. };
  22427. PhysicsEngine.prototype._getGravity = function () {
  22428. return this._currentPlugin.getGravity();
  22429. };
  22430. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22431. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22432. };
  22433. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22434. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22435. };
  22436. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22437. this._currentPlugin.unregisterMesh(mesh);
  22438. };
  22439. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22440. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22441. };
  22442. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22443. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22444. };
  22445. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22446. this._currentPlugin.updateBodyPosition(mesh);
  22447. };
  22448. PhysicsEngine.prototype.dispose = function () {
  22449. this._currentPlugin.dispose();
  22450. };
  22451. PhysicsEngine.prototype.isSupported = function () {
  22452. return this._currentPlugin.isSupported();
  22453. };
  22454. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22455. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22456. };
  22457. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22458. return this._currentPlugin.name;
  22459. };
  22460. // Statics
  22461. PhysicsEngine.NoImpostor = 0;
  22462. PhysicsEngine.SphereImpostor = 1;
  22463. PhysicsEngine.BoxImpostor = 2;
  22464. PhysicsEngine.PlaneImpostor = 3;
  22465. PhysicsEngine.MeshImpostor = 4;
  22466. PhysicsEngine.CapsuleImpostor = 5;
  22467. PhysicsEngine.ConeImpostor = 6;
  22468. PhysicsEngine.CylinderImpostor = 7;
  22469. PhysicsEngine.ConvexHullImpostor = 8;
  22470. PhysicsEngine.HeightmapImpostor = 9;
  22471. PhysicsEngine.Epsilon = 0.001;
  22472. return PhysicsEngine;
  22473. })();
  22474. BABYLON.PhysicsEngine = PhysicsEngine;
  22475. })(BABYLON || (BABYLON = {}));
  22476. var BABYLON;
  22477. (function (BABYLON) {
  22478. var VertexData = (function () {
  22479. function VertexData() {
  22480. }
  22481. VertexData.prototype.set = function (data, kind) {
  22482. switch (kind) {
  22483. case BABYLON.VertexBuffer.PositionKind:
  22484. this.positions = data;
  22485. break;
  22486. case BABYLON.VertexBuffer.NormalKind:
  22487. this.normals = data;
  22488. break;
  22489. case BABYLON.VertexBuffer.UVKind:
  22490. this.uvs = data;
  22491. break;
  22492. case BABYLON.VertexBuffer.UV2Kind:
  22493. this.uvs2 = data;
  22494. break;
  22495. case BABYLON.VertexBuffer.UV3Kind:
  22496. this.uvs3 = data;
  22497. break;
  22498. case BABYLON.VertexBuffer.UV4Kind:
  22499. this.uvs4 = data;
  22500. break;
  22501. case BABYLON.VertexBuffer.UV5Kind:
  22502. this.uvs5 = data;
  22503. break;
  22504. case BABYLON.VertexBuffer.UV6Kind:
  22505. this.uvs6 = data;
  22506. break;
  22507. case BABYLON.VertexBuffer.ColorKind:
  22508. this.colors = data;
  22509. break;
  22510. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22511. this.matricesIndices = data;
  22512. break;
  22513. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22514. this.matricesWeights = data;
  22515. break;
  22516. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22517. this.matricesIndicesExtra = data;
  22518. break;
  22519. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22520. this.matricesWeightsExtra = data;
  22521. break;
  22522. }
  22523. };
  22524. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22525. this._applyTo(mesh, updatable);
  22526. };
  22527. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22528. this._applyTo(geometry, updatable);
  22529. };
  22530. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22531. this._update(mesh);
  22532. };
  22533. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22534. this._update(geometry);
  22535. };
  22536. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22537. if (this.positions) {
  22538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22539. }
  22540. if (this.normals) {
  22541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22542. }
  22543. if (this.uvs) {
  22544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22545. }
  22546. if (this.uvs2) {
  22547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22548. }
  22549. if (this.uvs3) {
  22550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22551. }
  22552. if (this.uvs4) {
  22553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22554. }
  22555. if (this.uvs5) {
  22556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22557. }
  22558. if (this.uvs6) {
  22559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22560. }
  22561. if (this.colors) {
  22562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22563. }
  22564. if (this.matricesIndices) {
  22565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22566. }
  22567. if (this.matricesWeights) {
  22568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22569. }
  22570. if (this.matricesIndicesExtra) {
  22571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22572. }
  22573. if (this.matricesWeightsExtra) {
  22574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22575. }
  22576. if (this.indices) {
  22577. meshOrGeometry.setIndices(this.indices);
  22578. }
  22579. };
  22580. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22581. if (this.positions) {
  22582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22583. }
  22584. if (this.normals) {
  22585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22586. }
  22587. if (this.uvs) {
  22588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22589. }
  22590. if (this.uvs2) {
  22591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22592. }
  22593. if (this.uvs3) {
  22594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22595. }
  22596. if (this.uvs4) {
  22597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22598. }
  22599. if (this.uvs5) {
  22600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22601. }
  22602. if (this.uvs6) {
  22603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22604. }
  22605. if (this.colors) {
  22606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22607. }
  22608. if (this.matricesIndices) {
  22609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22610. }
  22611. if (this.matricesWeights) {
  22612. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22613. }
  22614. if (this.matricesIndicesExtra) {
  22615. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22616. }
  22617. if (this.matricesWeightsExtra) {
  22618. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22619. }
  22620. if (this.indices) {
  22621. meshOrGeometry.setIndices(this.indices);
  22622. }
  22623. };
  22624. VertexData.prototype.transform = function (matrix) {
  22625. var transformed = BABYLON.Vector3.Zero();
  22626. var index;
  22627. if (this.positions) {
  22628. var position = BABYLON.Vector3.Zero();
  22629. for (index = 0; index < this.positions.length; index += 3) {
  22630. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22631. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22632. this.positions[index] = transformed.x;
  22633. this.positions[index + 1] = transformed.y;
  22634. this.positions[index + 2] = transformed.z;
  22635. }
  22636. }
  22637. if (this.normals) {
  22638. var normal = BABYLON.Vector3.Zero();
  22639. for (index = 0; index < this.normals.length; index += 3) {
  22640. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22641. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22642. this.normals[index] = transformed.x;
  22643. this.normals[index + 1] = transformed.y;
  22644. this.normals[index + 2] = transformed.z;
  22645. }
  22646. }
  22647. };
  22648. VertexData.prototype.merge = function (other) {
  22649. var index;
  22650. if (other.indices) {
  22651. if (!this.indices) {
  22652. this.indices = [];
  22653. }
  22654. var offset = this.positions ? this.positions.length / 3 : 0;
  22655. for (index = 0; index < other.indices.length; index++) {
  22656. //TODO check type - if Int32Array!
  22657. this.indices.push(other.indices[index] + offset);
  22658. }
  22659. }
  22660. if (other.positions) {
  22661. if (!this.positions) {
  22662. this.positions = [];
  22663. }
  22664. for (index = 0; index < other.positions.length; index++) {
  22665. this.positions.push(other.positions[index]);
  22666. }
  22667. }
  22668. if (other.normals) {
  22669. if (!this.normals) {
  22670. this.normals = [];
  22671. }
  22672. for (index = 0; index < other.normals.length; index++) {
  22673. this.normals.push(other.normals[index]);
  22674. }
  22675. }
  22676. if (other.uvs) {
  22677. if (!this.uvs) {
  22678. this.uvs = [];
  22679. }
  22680. for (index = 0; index < other.uvs.length; index++) {
  22681. this.uvs.push(other.uvs[index]);
  22682. }
  22683. }
  22684. if (other.uvs2) {
  22685. if (!this.uvs2) {
  22686. this.uvs2 = [];
  22687. }
  22688. for (index = 0; index < other.uvs2.length; index++) {
  22689. this.uvs2.push(other.uvs2[index]);
  22690. }
  22691. }
  22692. if (other.uvs3) {
  22693. if (!this.uvs3) {
  22694. this.uvs3 = [];
  22695. }
  22696. for (index = 0; index < other.uvs3.length; index++) {
  22697. this.uvs3.push(other.uvs3[index]);
  22698. }
  22699. }
  22700. if (other.uvs4) {
  22701. if (!this.uvs4) {
  22702. this.uvs4 = [];
  22703. }
  22704. for (index = 0; index < other.uvs4.length; index++) {
  22705. this.uvs4.push(other.uvs4[index]);
  22706. }
  22707. }
  22708. if (other.uvs5) {
  22709. if (!this.uvs5) {
  22710. this.uvs5 = [];
  22711. }
  22712. for (index = 0; index < other.uvs5.length; index++) {
  22713. this.uvs5.push(other.uvs5[index]);
  22714. }
  22715. }
  22716. if (other.uvs6) {
  22717. if (!this.uvs6) {
  22718. this.uvs6 = [];
  22719. }
  22720. for (index = 0; index < other.uvs6.length; index++) {
  22721. this.uvs6.push(other.uvs6[index]);
  22722. }
  22723. }
  22724. if (other.matricesIndices) {
  22725. if (!this.matricesIndices) {
  22726. this.matricesIndices = [];
  22727. }
  22728. for (index = 0; index < other.matricesIndices.length; index++) {
  22729. this.matricesIndices.push(other.matricesIndices[index]);
  22730. }
  22731. }
  22732. if (other.matricesWeights) {
  22733. if (!this.matricesWeights) {
  22734. this.matricesWeights = [];
  22735. }
  22736. for (index = 0; index < other.matricesWeights.length; index++) {
  22737. this.matricesWeights.push(other.matricesWeights[index]);
  22738. }
  22739. }
  22740. if (other.matricesIndicesExtra) {
  22741. if (!this.matricesIndicesExtra) {
  22742. this.matricesIndicesExtra = [];
  22743. }
  22744. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  22745. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  22746. }
  22747. }
  22748. if (other.matricesWeightsExtra) {
  22749. if (!this.matricesWeightsExtra) {
  22750. this.matricesWeightsExtra = [];
  22751. }
  22752. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  22753. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  22754. }
  22755. }
  22756. if (other.colors) {
  22757. if (!this.colors) {
  22758. this.colors = [];
  22759. }
  22760. for (index = 0; index < other.colors.length; index++) {
  22761. this.colors.push(other.colors[index]);
  22762. }
  22763. }
  22764. };
  22765. VertexData.prototype.serialize = function () {
  22766. var serializationObject = this.serialize();
  22767. if (this.positions) {
  22768. serializationObject.positions = this.positions;
  22769. }
  22770. if (this.normals) {
  22771. serializationObject.normals = this.normals;
  22772. }
  22773. if (this.uvs) {
  22774. serializationObject.uvs = this.uvs;
  22775. }
  22776. if (this.uvs2) {
  22777. serializationObject.uvs2 = this.uvs2;
  22778. }
  22779. if (this.uvs3) {
  22780. serializationObject.uvs3 = this.uvs3;
  22781. }
  22782. if (this.uvs4) {
  22783. serializationObject.uvs4 = this.uvs4;
  22784. }
  22785. if (this.uvs5) {
  22786. serializationObject.uvs5 = this.uvs5;
  22787. }
  22788. if (this.uvs6) {
  22789. serializationObject.uvs6 = this.uvs6;
  22790. }
  22791. if (this.colors) {
  22792. serializationObject.colors = this.colors;
  22793. }
  22794. if (this.matricesIndices) {
  22795. serializationObject.matricesIndices = this.matricesIndices;
  22796. serializationObject.matricesIndices._isExpanded = true;
  22797. }
  22798. if (this.matricesWeights) {
  22799. serializationObject.matricesWeights = this.matricesWeights;
  22800. }
  22801. serializationObject.indices = this.indices;
  22802. return serializationObject;
  22803. };
  22804. // Statics
  22805. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22806. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22807. };
  22808. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22809. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22810. };
  22811. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22812. var result = new VertexData();
  22813. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22814. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22815. }
  22816. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22817. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22818. }
  22819. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22820. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22821. }
  22822. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22823. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22824. }
  22825. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22826. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22827. }
  22828. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22829. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22830. }
  22831. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22832. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22833. }
  22834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22835. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22836. }
  22837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22838. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22839. }
  22840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22841. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22842. }
  22843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22844. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22845. }
  22846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22847. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22848. }
  22849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22850. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22851. }
  22852. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22853. return result;
  22854. };
  22855. VertexData.CreateRibbon = function (options) {
  22856. var pathArray = options.pathArray;
  22857. var closeArray = options.closeArray || false;
  22858. var closePath = options.closePath || false;
  22859. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22860. var offset = options.offset || defaultOffset;
  22861. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22863. var positions = [];
  22864. var indices = [];
  22865. var normals = [];
  22866. var uvs = [];
  22867. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22868. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22869. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22870. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22871. var minlg; // minimal length among all paths from pathArray
  22872. var lg = []; // array of path lengths : nb of vertex per path
  22873. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22874. var p; // path iterator
  22875. var i; // point iterator
  22876. var j; // point iterator
  22877. // if single path in pathArray
  22878. if (pathArray.length < 2) {
  22879. var ar1 = [];
  22880. var ar2 = [];
  22881. for (i = 0; i < pathArray[0].length - offset; i++) {
  22882. ar1.push(pathArray[0][i]);
  22883. ar2.push(pathArray[0][i + offset]);
  22884. }
  22885. pathArray = [ar1, ar2];
  22886. }
  22887. // positions and horizontal distances (u)
  22888. var idc = 0;
  22889. var closePathCorr = (closePath) ? 1 : 0;
  22890. var path;
  22891. var l;
  22892. minlg = pathArray[0].length;
  22893. var vectlg;
  22894. var dist;
  22895. for (p = 0; p < pathArray.length; p++) {
  22896. uTotalDistance[p] = 0;
  22897. us[p] = [0];
  22898. path = pathArray[p];
  22899. l = path.length;
  22900. minlg = (minlg < l) ? minlg : l;
  22901. j = 0;
  22902. while (j < l) {
  22903. positions.push(path[j].x, path[j].y, path[j].z);
  22904. if (j > 0) {
  22905. vectlg = path[j].subtract(path[j - 1]).length();
  22906. dist = vectlg + uTotalDistance[p];
  22907. us[p].push(dist);
  22908. uTotalDistance[p] = dist;
  22909. }
  22910. j++;
  22911. }
  22912. if (closePath) {
  22913. j--;
  22914. positions.push(path[0].x, path[0].y, path[0].z);
  22915. vectlg = path[j].subtract(path[0]).length();
  22916. dist = vectlg + uTotalDistance[p];
  22917. us[p].push(dist);
  22918. uTotalDistance[p] = dist;
  22919. }
  22920. lg[p] = l + closePathCorr;
  22921. idx[p] = idc;
  22922. idc += (l + closePathCorr);
  22923. }
  22924. // vertical distances (v)
  22925. var path1;
  22926. var path2;
  22927. var vertex1;
  22928. var vertex2;
  22929. for (i = 0; i < minlg + closePathCorr; i++) {
  22930. vTotalDistance[i] = 0;
  22931. vs[i] = [0];
  22932. for (p = 0; p < pathArray.length - 1; p++) {
  22933. path1 = pathArray[p];
  22934. path2 = pathArray[p + 1];
  22935. if (i === minlg) {
  22936. vertex1 = path1[0];
  22937. vertex2 = path2[0];
  22938. }
  22939. else {
  22940. vertex1 = path1[i];
  22941. vertex2 = path2[i];
  22942. }
  22943. vectlg = vertex2.subtract(vertex1).length();
  22944. dist = vectlg + vTotalDistance[i];
  22945. vs[i].push(dist);
  22946. vTotalDistance[i] = dist;
  22947. }
  22948. if (closeArray) {
  22949. path1 = pathArray[p];
  22950. path2 = pathArray[0];
  22951. if (i === minlg) {
  22952. vertex2 = path2[0];
  22953. }
  22954. vectlg = vertex2.subtract(vertex1).length();
  22955. dist = vectlg + vTotalDistance[i];
  22956. vTotalDistance[i] = dist;
  22957. }
  22958. }
  22959. // uvs
  22960. var u;
  22961. var v;
  22962. for (p = 0; p < pathArray.length; p++) {
  22963. for (i = 0; i < minlg + closePathCorr; i++) {
  22964. u = us[p][i] / uTotalDistance[p];
  22965. v = vs[i][p] / vTotalDistance[i];
  22966. uvs.push(u, v);
  22967. }
  22968. }
  22969. // indices
  22970. p = 0; // path index
  22971. var pi = 0; // positions array index
  22972. var l1 = lg[p] - 1; // path1 length
  22973. var l2 = lg[p + 1] - 1; // path2 length
  22974. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22975. var shft = idx[1] - idx[0]; // shift
  22976. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  22977. while (pi <= min && p < path1nb) {
  22978. // 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
  22979. indices.push(pi, pi + shft, pi + 1);
  22980. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22981. pi += 1;
  22982. if (pi === min) {
  22983. p++;
  22984. if (p === lg.length - 1) {
  22985. shft = idx[0] - idx[p];
  22986. l1 = lg[p] - 1;
  22987. l2 = lg[0] - 1;
  22988. }
  22989. else {
  22990. shft = idx[p + 1] - idx[p];
  22991. l1 = lg[p] - 1;
  22992. l2 = lg[p + 1] - 1;
  22993. }
  22994. pi = idx[p];
  22995. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22996. }
  22997. }
  22998. // normals
  22999. VertexData.ComputeNormals(positions, indices, normals);
  23000. if (closePath) {
  23001. var indexFirst = 0;
  23002. var indexLast = 0;
  23003. for (p = 0; p < pathArray.length; p++) {
  23004. indexFirst = idx[p] * 3;
  23005. if (p + 1 < pathArray.length) {
  23006. indexLast = (idx[p + 1] - 1) * 3;
  23007. }
  23008. else {
  23009. indexLast = normals.length - 3;
  23010. }
  23011. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23012. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23013. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23014. normals[indexLast] = normals[indexFirst];
  23015. normals[indexLast + 1] = normals[indexFirst + 1];
  23016. normals[indexLast + 2] = normals[indexFirst + 2];
  23017. }
  23018. }
  23019. // sides
  23020. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23021. // Result
  23022. var vertexData = new VertexData();
  23023. vertexData.indices = indices;
  23024. vertexData.positions = positions;
  23025. vertexData.normals = normals;
  23026. vertexData.uvs = uvs;
  23027. if (closePath) {
  23028. vertexData._idx = idx;
  23029. }
  23030. return vertexData;
  23031. };
  23032. VertexData.CreateBox = function (options) {
  23033. var normalsSource = [
  23034. new BABYLON.Vector3(0, 0, 1),
  23035. new BABYLON.Vector3(0, 0, -1),
  23036. new BABYLON.Vector3(1, 0, 0),
  23037. new BABYLON.Vector3(-1, 0, 0),
  23038. new BABYLON.Vector3(0, 1, 0),
  23039. new BABYLON.Vector3(0, -1, 0)
  23040. ];
  23041. var indices = [];
  23042. var positions = [];
  23043. var normals = [];
  23044. var uvs = [];
  23045. var width = options.width || options.size || 1;
  23046. var height = options.height || options.size || 1;
  23047. var depth = options.depth || options.size || 1;
  23048. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23049. var faceUV = options.faceUV || new Array(6);
  23050. var faceColors = options.faceColors;
  23051. var colors = [];
  23052. // default face colors and UV if undefined
  23053. for (var f = 0; f < 6; f++) {
  23054. if (faceUV[f] === undefined) {
  23055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23056. }
  23057. if (faceColors && faceColors[f] === undefined) {
  23058. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23059. }
  23060. }
  23061. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23062. // Create each face in turn.
  23063. for (var index = 0; index < normalsSource.length; index++) {
  23064. var normal = normalsSource[index];
  23065. // Get two vectors perpendicular to the face normal and to each other.
  23066. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23067. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23068. // Six indices (two triangles) per face.
  23069. var verticesLength = positions.length / 3;
  23070. indices.push(verticesLength);
  23071. indices.push(verticesLength + 1);
  23072. indices.push(verticesLength + 2);
  23073. indices.push(verticesLength);
  23074. indices.push(verticesLength + 2);
  23075. indices.push(verticesLength + 3);
  23076. // Four vertices per face.
  23077. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23078. positions.push(vertex.x, vertex.y, vertex.z);
  23079. normals.push(normal.x, normal.y, normal.z);
  23080. uvs.push(faceUV[index].z, faceUV[index].w);
  23081. if (faceColors) {
  23082. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23083. }
  23084. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23085. positions.push(vertex.x, vertex.y, vertex.z);
  23086. normals.push(normal.x, normal.y, normal.z);
  23087. uvs.push(faceUV[index].x, faceUV[index].w);
  23088. if (faceColors) {
  23089. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23090. }
  23091. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23092. positions.push(vertex.x, vertex.y, vertex.z);
  23093. normals.push(normal.x, normal.y, normal.z);
  23094. uvs.push(faceUV[index].x, faceUV[index].y);
  23095. if (faceColors) {
  23096. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23097. }
  23098. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23099. positions.push(vertex.x, vertex.y, vertex.z);
  23100. normals.push(normal.x, normal.y, normal.z);
  23101. uvs.push(faceUV[index].z, faceUV[index].y);
  23102. if (faceColors) {
  23103. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23104. }
  23105. }
  23106. // sides
  23107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23108. // Result
  23109. var vertexData = new VertexData();
  23110. vertexData.indices = indices;
  23111. vertexData.positions = positions;
  23112. vertexData.normals = normals;
  23113. vertexData.uvs = uvs;
  23114. if (faceColors) {
  23115. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23116. vertexData.colors = totalColors;
  23117. }
  23118. return vertexData;
  23119. };
  23120. VertexData.CreateSphere = function (options) {
  23121. var segments = options.segments || 32;
  23122. var diameterX = options.diameterX || options.diameter || 1;
  23123. var diameterY = options.diameterY || options.diameter || 1;
  23124. var diameterZ = options.diameterZ || options.diameter || 1;
  23125. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23126. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23128. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23129. var totalZRotationSteps = 2 + segments;
  23130. var totalYRotationSteps = 2 * totalZRotationSteps;
  23131. var indices = [];
  23132. var positions = [];
  23133. var normals = [];
  23134. var uvs = [];
  23135. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23136. var normalizedZ = zRotationStep / totalZRotationSteps;
  23137. var angleZ = normalizedZ * Math.PI * slice;
  23138. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23139. var normalizedY = yRotationStep / totalYRotationSteps;
  23140. var angleY = normalizedY * Math.PI * 2 * arc;
  23141. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23142. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23143. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23144. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23145. var vertex = complete.multiply(radius);
  23146. var normal = complete.divide(radius).normalize();
  23147. positions.push(vertex.x, vertex.y, vertex.z);
  23148. normals.push(normal.x, normal.y, normal.z);
  23149. uvs.push(normalizedY, normalizedZ);
  23150. }
  23151. if (zRotationStep > 0) {
  23152. var verticesCount = positions.length / 3;
  23153. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23154. indices.push((firstIndex));
  23155. indices.push((firstIndex + 1));
  23156. indices.push(firstIndex + totalYRotationSteps + 1);
  23157. indices.push((firstIndex + totalYRotationSteps + 1));
  23158. indices.push((firstIndex + 1));
  23159. indices.push((firstIndex + totalYRotationSteps + 2));
  23160. }
  23161. }
  23162. }
  23163. // Sides
  23164. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23165. // Result
  23166. var vertexData = new VertexData();
  23167. vertexData.indices = indices;
  23168. vertexData.positions = positions;
  23169. vertexData.normals = normals;
  23170. vertexData.uvs = uvs;
  23171. return vertexData;
  23172. };
  23173. // Cylinder and cone
  23174. VertexData.CreateCylinder = function (options) {
  23175. var height = options.height || 2;
  23176. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23177. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23178. var tessellation = options.tessellation || 24;
  23179. var subdivisions = options.subdivisions || 1;
  23180. var hasRings = options.hasRings;
  23181. var enclose = options.enclose;
  23182. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23183. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23184. var faceUV = options.faceUV || new Array(3);
  23185. var faceColors = options.faceColors;
  23186. // default face colors and UV if undefined
  23187. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23188. var ringNb = (hasRings) ? subdivisions : 1;
  23189. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23190. var f;
  23191. for (f = 0; f < surfaceNb; f++) {
  23192. if (faceColors && faceColors[f] === undefined) {
  23193. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23194. }
  23195. }
  23196. for (f = 0; f < surfaceNb; f++) {
  23197. if (faceUV && faceUV[f] === undefined) {
  23198. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23199. }
  23200. }
  23201. var indices = [];
  23202. var positions = [];
  23203. var normals = [];
  23204. var uvs = [];
  23205. var colors = [];
  23206. var angle_step = Math.PI * 2 * arc / tessellation;
  23207. var angle;
  23208. var h;
  23209. var radius;
  23210. var tan = (diameterBottom - diameterTop) / 2 / height;
  23211. var ringVertex = BABYLON.Vector3.Zero();
  23212. var ringNormal = BABYLON.Vector3.Zero();
  23213. var ringFirstVertex = BABYLON.Vector3.Zero();
  23214. var ringFirstNormal = BABYLON.Vector3.Zero();
  23215. var quadNormal = BABYLON.Vector3.Zero();
  23216. var Y = BABYLON.Axis.Y;
  23217. // positions, normals, uvs
  23218. var i;
  23219. var j;
  23220. var r;
  23221. var ringIdx = 1;
  23222. var s = 1; // surface index
  23223. var cs = 0;
  23224. var v = 0;
  23225. for (i = 0; i <= subdivisions; i++) {
  23226. h = i / subdivisions;
  23227. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23228. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23229. for (r = 0; r < ringIdx; r++) {
  23230. if (hasRings) {
  23231. s += r;
  23232. }
  23233. if (enclose) {
  23234. s += 2 * r;
  23235. }
  23236. for (j = 0; j <= tessellation; j++) {
  23237. angle = j * angle_step;
  23238. // position
  23239. ringVertex.x = Math.cos(-angle) * radius;
  23240. ringVertex.y = -height / 2 + h * height;
  23241. ringVertex.z = Math.sin(-angle) * radius;
  23242. // normal
  23243. if (diameterTop === 0 && i === subdivisions) {
  23244. // if no top cap, reuse former normals
  23245. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23246. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23247. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23248. }
  23249. else {
  23250. ringNormal.x = ringVertex.x;
  23251. ringNormal.z = ringVertex.z;
  23252. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23253. ringNormal.normalize();
  23254. }
  23255. // keep first ring vertex values for enclose
  23256. if (j === 0) {
  23257. ringFirstVertex.copyFrom(ringVertex);
  23258. ringFirstNormal.copyFrom(ringNormal);
  23259. }
  23260. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23261. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23262. if (hasRings) {
  23263. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23264. }
  23265. else {
  23266. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23267. }
  23268. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23269. if (faceColors) {
  23270. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23271. }
  23272. }
  23273. // if enclose, add four vertices and their dedicated normals
  23274. if (arc !== 1 && enclose) {
  23275. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23276. positions.push(0, ringVertex.y, 0);
  23277. positions.push(0, ringVertex.y, 0);
  23278. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23279. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23280. quadNormal.normalize();
  23281. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23282. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23283. quadNormal.normalize();
  23284. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23285. if (hasRings) {
  23286. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23287. }
  23288. else {
  23289. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23290. }
  23291. uvs.push(faceUV[s + 1].x, v);
  23292. uvs.push(faceUV[s + 1].z, v);
  23293. if (hasRings) {
  23294. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23295. }
  23296. else {
  23297. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23298. }
  23299. uvs.push(faceUV[s + 2].x, v);
  23300. uvs.push(faceUV[s + 2].z, v);
  23301. if (faceColors) {
  23302. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23303. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23304. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23305. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23306. }
  23307. }
  23308. if (cs !== s) {
  23309. cs = s;
  23310. }
  23311. }
  23312. }
  23313. // indices
  23314. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23315. var s;
  23316. i = 0;
  23317. for (s = 0; s < subdivisions; s++) {
  23318. for (j = 0; j < tessellation; j++) {
  23319. var i0 = i * (e + 1) + j;
  23320. var i1 = (i + 1) * (e + 1) + j;
  23321. var i2 = i * (e + 1) + (j + 1);
  23322. var i3 = (i + 1) * (e + 1) + (j + 1);
  23323. indices.push(i0, i1, i2);
  23324. indices.push(i3, i2, i1);
  23325. }
  23326. if (arc !== 1 && enclose) {
  23327. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23328. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23329. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23330. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23331. }
  23332. i = (hasRings) ? (i + 2) : (i + 1);
  23333. }
  23334. // Caps
  23335. var createCylinderCap = function (isTop) {
  23336. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23337. if (radius === 0) {
  23338. return;
  23339. }
  23340. // Cap positions, normals & uvs
  23341. var angle;
  23342. var circleVector;
  23343. var i;
  23344. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23345. var c;
  23346. if (faceColors) {
  23347. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23348. }
  23349. // cap center
  23350. var vbase = positions.length / 3;
  23351. var offset = isTop ? height / 2 : -height / 2;
  23352. var center = new BABYLON.Vector3(0, offset, 0);
  23353. positions.push(center.x, center.y, center.z);
  23354. normals.push(0, isTop ? 1 : -1, 0);
  23355. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23356. if (faceColors) {
  23357. colors.push(c.r, c.g, c.b, c.a);
  23358. }
  23359. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23360. for (i = 0; i <= tessellation; i++) {
  23361. angle = Math.PI * 2 * i * arc / tessellation;
  23362. var cos = Math.cos(-angle);
  23363. var sin = Math.sin(-angle);
  23364. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23365. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23366. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23367. normals.push(0, isTop ? 1 : -1, 0);
  23368. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23369. if (faceColors) {
  23370. colors.push(c.r, c.g, c.b, c.a);
  23371. }
  23372. }
  23373. // Cap indices
  23374. for (i = 0; i < tessellation; i++) {
  23375. if (!isTop) {
  23376. indices.push(vbase);
  23377. indices.push(vbase + (i + 1));
  23378. indices.push(vbase + (i + 2));
  23379. }
  23380. else {
  23381. indices.push(vbase);
  23382. indices.push(vbase + (i + 2));
  23383. indices.push(vbase + (i + 1));
  23384. }
  23385. }
  23386. };
  23387. // add caps to geometry
  23388. createCylinderCap(false);
  23389. createCylinderCap(true);
  23390. // Sides
  23391. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23392. var vertexData = new VertexData();
  23393. vertexData.indices = indices;
  23394. vertexData.positions = positions;
  23395. vertexData.normals = normals;
  23396. vertexData.uvs = uvs;
  23397. if (faceColors) {
  23398. vertexData.colors = colors;
  23399. }
  23400. return vertexData;
  23401. };
  23402. VertexData.CreateTorus = function (options) {
  23403. var indices = [];
  23404. var positions = [];
  23405. var normals = [];
  23406. var uvs = [];
  23407. var diameter = options.diameter || 1;
  23408. var thickness = options.thickness || 0.5;
  23409. var tessellation = options.tessellation || 16;
  23410. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23411. var stride = tessellation + 1;
  23412. for (var i = 0; i <= tessellation; i++) {
  23413. var u = i / tessellation;
  23414. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23415. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23416. for (var j = 0; j <= tessellation; j++) {
  23417. var v = 1 - j / tessellation;
  23418. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23419. var dx = Math.cos(innerAngle);
  23420. var dy = Math.sin(innerAngle);
  23421. // Create a vertex.
  23422. var normal = new BABYLON.Vector3(dx, dy, 0);
  23423. var position = normal.scale(thickness / 2);
  23424. var textureCoordinate = new BABYLON.Vector2(u, v);
  23425. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23426. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23427. positions.push(position.x, position.y, position.z);
  23428. normals.push(normal.x, normal.y, normal.z);
  23429. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23430. // And create indices for two triangles.
  23431. var nextI = (i + 1) % stride;
  23432. var nextJ = (j + 1) % stride;
  23433. indices.push(i * stride + j);
  23434. indices.push(i * stride + nextJ);
  23435. indices.push(nextI * stride + j);
  23436. indices.push(i * stride + nextJ);
  23437. indices.push(nextI * stride + nextJ);
  23438. indices.push(nextI * stride + j);
  23439. }
  23440. }
  23441. // Sides
  23442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23443. // Result
  23444. var vertexData = new VertexData();
  23445. vertexData.indices = indices;
  23446. vertexData.positions = positions;
  23447. vertexData.normals = normals;
  23448. vertexData.uvs = uvs;
  23449. return vertexData;
  23450. };
  23451. VertexData.CreateLines = function (options) {
  23452. var indices = [];
  23453. var positions = [];
  23454. var points = options.points;
  23455. for (var index = 0; index < points.length; index++) {
  23456. positions.push(points[index].x, points[index].y, points[index].z);
  23457. if (index > 0) {
  23458. indices.push(index - 1);
  23459. indices.push(index);
  23460. }
  23461. }
  23462. // Result
  23463. var vertexData = new VertexData();
  23464. vertexData.indices = indices;
  23465. vertexData.positions = positions;
  23466. return vertexData;
  23467. };
  23468. VertexData.CreateDashedLines = function (options) {
  23469. var dashSize = options.dashSize || 3;
  23470. var gapSize = options.gapSize || 1;
  23471. var dashNb = options.dashNb || 200;
  23472. var points = options.points;
  23473. var positions = new Array();
  23474. var indices = new Array();
  23475. var curvect = BABYLON.Vector3.Zero();
  23476. var lg = 0;
  23477. var nb = 0;
  23478. var shft = 0;
  23479. var dashshft = 0;
  23480. var curshft = 0;
  23481. var idx = 0;
  23482. var i = 0;
  23483. for (i = 0; i < points.length - 1; i++) {
  23484. points[i + 1].subtractToRef(points[i], curvect);
  23485. lg += curvect.length();
  23486. }
  23487. shft = lg / dashNb;
  23488. dashshft = dashSize * shft / (dashSize + gapSize);
  23489. for (i = 0; i < points.length - 1; i++) {
  23490. points[i + 1].subtractToRef(points[i], curvect);
  23491. nb = Math.floor(curvect.length() / shft);
  23492. curvect.normalize();
  23493. for (var j = 0; j < nb; j++) {
  23494. curshft = shft * j;
  23495. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23496. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23497. indices.push(idx, idx + 1);
  23498. idx += 2;
  23499. }
  23500. }
  23501. // Result
  23502. var vertexData = new VertexData();
  23503. vertexData.positions = positions;
  23504. vertexData.indices = indices;
  23505. return vertexData;
  23506. };
  23507. VertexData.CreateGround = function (options) {
  23508. var indices = [];
  23509. var positions = [];
  23510. var normals = [];
  23511. var uvs = [];
  23512. var row, col;
  23513. var width = options.width || 1;
  23514. var height = options.height || 1;
  23515. var subdivisions = options.subdivisions || 1;
  23516. for (row = 0; row <= subdivisions; row++) {
  23517. for (col = 0; col <= subdivisions; col++) {
  23518. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23519. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23520. positions.push(position.x, position.y, position.z);
  23521. normals.push(normal.x, normal.y, normal.z);
  23522. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23523. }
  23524. }
  23525. for (row = 0; row < subdivisions; row++) {
  23526. for (col = 0; col < subdivisions; col++) {
  23527. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23528. indices.push(col + 1 + row * (subdivisions + 1));
  23529. indices.push(col + row * (subdivisions + 1));
  23530. indices.push(col + (row + 1) * (subdivisions + 1));
  23531. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23532. indices.push(col + row * (subdivisions + 1));
  23533. }
  23534. }
  23535. // Result
  23536. var vertexData = new VertexData();
  23537. vertexData.indices = indices;
  23538. vertexData.positions = positions;
  23539. vertexData.normals = normals;
  23540. vertexData.uvs = uvs;
  23541. return vertexData;
  23542. };
  23543. VertexData.CreateTiledGround = function (options) {
  23544. var xmin = options.xmin;
  23545. var zmin = options.zmin;
  23546. var xmax = options.xmax;
  23547. var zmax = options.zmax;
  23548. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23549. var precision = options.precision || { w: 1, h: 1 };
  23550. var indices = [];
  23551. var positions = [];
  23552. var normals = [];
  23553. var uvs = [];
  23554. var row, col, tileRow, tileCol;
  23555. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23556. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23557. precision.w = (precision.w < 1) ? 1 : precision.w;
  23558. precision.h = (precision.h < 1) ? 1 : precision.h;
  23559. var tileSize = {
  23560. 'w': (xmax - xmin) / subdivisions.w,
  23561. 'h': (zmax - zmin) / subdivisions.h
  23562. };
  23563. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23564. // Indices
  23565. var base = positions.length / 3;
  23566. var rowLength = precision.w + 1;
  23567. for (row = 0; row < precision.h; row++) {
  23568. for (col = 0; col < precision.w; col++) {
  23569. var square = [
  23570. base + col + row * rowLength,
  23571. base + (col + 1) + row * rowLength,
  23572. base + (col + 1) + (row + 1) * rowLength,
  23573. base + col + (row + 1) * rowLength
  23574. ];
  23575. indices.push(square[1]);
  23576. indices.push(square[2]);
  23577. indices.push(square[3]);
  23578. indices.push(square[0]);
  23579. indices.push(square[1]);
  23580. indices.push(square[3]);
  23581. }
  23582. }
  23583. // Position, normals and uvs
  23584. var position = BABYLON.Vector3.Zero();
  23585. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23586. for (row = 0; row <= precision.h; row++) {
  23587. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23588. for (col = 0; col <= precision.w; col++) {
  23589. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23590. position.y = 0;
  23591. positions.push(position.x, position.y, position.z);
  23592. normals.push(normal.x, normal.y, normal.z);
  23593. uvs.push(col / precision.w, row / precision.h);
  23594. }
  23595. }
  23596. }
  23597. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23598. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23599. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23600. }
  23601. }
  23602. // Result
  23603. var vertexData = new VertexData();
  23604. vertexData.indices = indices;
  23605. vertexData.positions = positions;
  23606. vertexData.normals = normals;
  23607. vertexData.uvs = uvs;
  23608. return vertexData;
  23609. };
  23610. VertexData.CreateGroundFromHeightMap = function (options) {
  23611. var indices = [];
  23612. var positions = [];
  23613. var normals = [];
  23614. var uvs = [];
  23615. var row, col;
  23616. // Vertices
  23617. for (row = 0; row <= options.subdivisions; row++) {
  23618. for (col = 0; col <= options.subdivisions; col++) {
  23619. 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));
  23620. // Compute height
  23621. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23622. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23623. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23624. var r = options.buffer[pos] / 255.0;
  23625. var g = options.buffer[pos + 1] / 255.0;
  23626. var b = options.buffer[pos + 2] / 255.0;
  23627. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23628. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23629. // Add vertex
  23630. positions.push(position.x, position.y, position.z);
  23631. normals.push(0, 0, 0);
  23632. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23633. }
  23634. }
  23635. // Indices
  23636. for (row = 0; row < options.subdivisions; row++) {
  23637. for (col = 0; col < options.subdivisions; col++) {
  23638. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23639. indices.push(col + 1 + row * (options.subdivisions + 1));
  23640. indices.push(col + row * (options.subdivisions + 1));
  23641. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23642. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23643. indices.push(col + row * (options.subdivisions + 1));
  23644. }
  23645. }
  23646. // Normals
  23647. VertexData.ComputeNormals(positions, indices, normals);
  23648. // Result
  23649. var vertexData = new VertexData();
  23650. vertexData.indices = indices;
  23651. vertexData.positions = positions;
  23652. vertexData.normals = normals;
  23653. vertexData.uvs = uvs;
  23654. return vertexData;
  23655. };
  23656. VertexData.CreatePlane = function (options) {
  23657. var indices = [];
  23658. var positions = [];
  23659. var normals = [];
  23660. var uvs = [];
  23661. var width = options.width || options.size || 1;
  23662. var height = options.height || options.size || 1;
  23663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23664. // Vertices
  23665. var halfWidth = width / 2.0;
  23666. var halfHeight = height / 2.0;
  23667. positions.push(-halfWidth, -halfHeight, 0);
  23668. normals.push(0, 0, -1.0);
  23669. uvs.push(0.0, 0.0);
  23670. positions.push(halfWidth, -halfHeight, 0);
  23671. normals.push(0, 0, -1.0);
  23672. uvs.push(1.0, 0.0);
  23673. positions.push(halfWidth, halfHeight, 0);
  23674. normals.push(0, 0, -1.0);
  23675. uvs.push(1.0, 1.0);
  23676. positions.push(-halfWidth, halfHeight, 0);
  23677. normals.push(0, 0, -1.0);
  23678. uvs.push(0.0, 1.0);
  23679. // Indices
  23680. indices.push(0);
  23681. indices.push(1);
  23682. indices.push(2);
  23683. indices.push(0);
  23684. indices.push(2);
  23685. indices.push(3);
  23686. // Sides
  23687. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23688. // Result
  23689. var vertexData = new VertexData();
  23690. vertexData.indices = indices;
  23691. vertexData.positions = positions;
  23692. vertexData.normals = normals;
  23693. vertexData.uvs = uvs;
  23694. return vertexData;
  23695. };
  23696. VertexData.CreateDisc = function (options) {
  23697. var positions = [];
  23698. var indices = [];
  23699. var normals = [];
  23700. var uvs = [];
  23701. var radius = options.radius || 0.5;
  23702. var tessellation = options.tessellation || 64;
  23703. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23705. // positions and uvs
  23706. positions.push(0, 0, 0); // disc center first
  23707. uvs.push(0.5, 0.5);
  23708. var theta = Math.PI * 2 * arc;
  23709. var step = theta / tessellation;
  23710. for (var a = 0; a < theta; a += step) {
  23711. var x = Math.cos(a);
  23712. var y = Math.sin(a);
  23713. var u = (x + 1) / 2;
  23714. var v = (1 - y) / 2;
  23715. positions.push(radius * x, radius * y, 0);
  23716. uvs.push(u, v);
  23717. }
  23718. if (arc === 1) {
  23719. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23720. uvs.push(uvs[2], uvs[3]);
  23721. }
  23722. //indices
  23723. var vertexNb = positions.length / 3;
  23724. for (var i = 1; i < vertexNb - 1; i++) {
  23725. indices.push(i + 1, 0, i);
  23726. }
  23727. // result
  23728. VertexData.ComputeNormals(positions, indices, normals);
  23729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23730. var vertexData = new VertexData();
  23731. vertexData.indices = indices;
  23732. vertexData.positions = positions;
  23733. vertexData.normals = normals;
  23734. vertexData.uvs = uvs;
  23735. return vertexData;
  23736. };
  23737. VertexData.CreateIcoSphere = function (options) {
  23738. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23739. var radius = options.radius || 1;
  23740. var flat = (options.flat === undefined) ? true : options.flat;
  23741. var subdivisions = options.subdivisions || 4;
  23742. var radiusX = options.radiusX || radius;
  23743. var radiusY = options.radiusY || radius;
  23744. var radiusZ = options.radiusZ || radius;
  23745. var t = (1 + Math.sqrt(5)) / 2;
  23746. // 12 vertex x,y,z
  23747. var ico_vertices = [
  23748. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23749. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23750. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23751. ];
  23752. // index of 3 vertex makes a face of icopshere
  23753. var ico_indices = [
  23754. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23755. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23756. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23757. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23758. ];
  23759. // vertex for uv have aliased position, not for UV
  23760. var vertices_unalias_id = [
  23761. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23762. // vertex alias
  23763. 0,
  23764. 2,
  23765. 3,
  23766. 3,
  23767. 3,
  23768. 4,
  23769. 7,
  23770. 8,
  23771. 9,
  23772. 9,
  23773. 10,
  23774. 11 // 23: B + 12
  23775. ];
  23776. // uv as integer step (not pixels !)
  23777. var ico_vertexuv = [
  23778. 5, 1, 3, 1, 6, 4, 0, 0,
  23779. 5, 3, 4, 2, 2, 2, 4, 0,
  23780. 2, 0, 1, 1, 6, 0, 6, 2,
  23781. // vertex alias (for same vertex on different faces)
  23782. 0, 4,
  23783. 3, 3,
  23784. 4, 4,
  23785. 3, 1,
  23786. 4, 2,
  23787. 4, 4,
  23788. 0, 2,
  23789. 1, 1,
  23790. 2, 2,
  23791. 3, 3,
  23792. 1, 3,
  23793. 2, 4 // 23: B + 12
  23794. ];
  23795. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23796. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23797. // First island of uv mapping
  23798. // v = 4h 3+ 2
  23799. // v = 3h 9+ 4
  23800. // v = 2h 9+ 5 B
  23801. // v = 1h 9 1 0
  23802. // v = 0h 3 8 7 A
  23803. // u = 0 1 2 3 4 5 6 *a
  23804. // Second island of uv mapping
  23805. // v = 4h 0+ B+ 4+
  23806. // v = 3h A+ 2+
  23807. // v = 2h 7+ 6 3+
  23808. // v = 1h 8+ 3+
  23809. // v = 0h
  23810. // u = 0 1 2 3 4 5 6 *a
  23811. // Face layout on texture UV mapping
  23812. // ============
  23813. // \ 4 /\ 16 / ======
  23814. // \ / \ / /\ 11 /
  23815. // \/ 7 \/ / \ /
  23816. // ======= / 10 \/
  23817. // /\ 17 /\ =======
  23818. // / \ / \ \ 15 /\
  23819. // / 8 \/ 12 \ \ / \
  23820. // ============ \/ 6 \
  23821. // \ 18 /\ ============
  23822. // \ / \ \ 5 /\ 0 /
  23823. // \/ 13 \ \ / \ /
  23824. // ======= \/ 1 \/
  23825. // =============
  23826. // /\ 19 /\ 2 /\
  23827. // / \ / \ / \
  23828. // / 14 \/ 9 \/ 3 \
  23829. // ===================
  23830. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23831. var ustep = 138 / 1024;
  23832. var vstep = 239 / 1024;
  23833. var uoffset = 60 / 1024;
  23834. var voffset = 26 / 1024;
  23835. // Second island should have margin, not to touch the first island
  23836. // avoid any borderline artefact in pixel rounding
  23837. var island_u_offset = -40 / 1024;
  23838. var island_v_offset = +20 / 1024;
  23839. // face is either island 0 or 1 :
  23840. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23841. var island = [
  23842. 0, 0, 0, 0, 1,
  23843. 0, 0, 1, 1, 0,
  23844. 0, 0, 1, 1, 0,
  23845. 0, 1, 1, 1, 0 // 15 - 19
  23846. ];
  23847. var indices = [];
  23848. var positions = [];
  23849. var normals = [];
  23850. var uvs = [];
  23851. var current_indice = 0;
  23852. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23853. var face_vertex_pos = new Array(3);
  23854. var face_vertex_uv = new Array(3);
  23855. var v012;
  23856. for (v012 = 0; v012 < 3; v012++) {
  23857. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23858. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23859. }
  23860. // create all with normals
  23861. for (var face = 0; face < 20; face++) {
  23862. // 3 vertex per face
  23863. for (v012 = 0; v012 < 3; v012++) {
  23864. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23865. var v_id = ico_indices[3 * face + v012];
  23866. // vertex have 3D position (x,y,z)
  23867. 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]);
  23868. // Normalize to get normal, then scale to radius
  23869. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23870. // uv Coordinates from vertex ID
  23871. 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);
  23872. }
  23873. // Subdivide the face (interpolate pos, norm, uv)
  23874. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23875. // - norm is linear interpolation of vertex corner normal
  23876. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23877. // - uv is linear interpolation
  23878. //
  23879. // Topology is as below for sub-divide by 2
  23880. // vertex shown as v0,v1,v2
  23881. // interp index is i1 to progress in range [v0,v1[
  23882. // interp index is i2 to progress in range [v0,v2[
  23883. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23884. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23885. //
  23886. //
  23887. // i2 v2
  23888. // ^ ^
  23889. // / / \
  23890. // / / \
  23891. // / / \
  23892. // / / (0,1) \
  23893. // / #---------\
  23894. // / / \ (0,0)'/ \
  23895. // / / \ / \
  23896. // / / \ / \
  23897. // / / (0,0) \ / (1,0) \
  23898. // / #---------#---------\
  23899. // v0 v1
  23900. //
  23901. // --------------------> i1
  23902. //
  23903. // interp of (i1,i2):
  23904. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23905. // along i1 : lerp(x0,x1, i1/(S-i2))
  23906. //
  23907. // centroid of triangle is needed to get help normal computation
  23908. // (c1,c2) are used for centroid location
  23909. var interp_vertex = function (i1, i2, c1, c2) {
  23910. // vertex is interpolated from
  23911. // - face_vertex_pos[0..2]
  23912. // - face_vertex_uv[0..2]
  23913. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  23914. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  23915. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  23916. pos_interp.normalize();
  23917. var vertex_normal;
  23918. if (flat) {
  23919. // in flat mode, recalculate normal as face centroid normal
  23920. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  23921. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  23922. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  23923. }
  23924. else {
  23925. // in smooth mode, recalculate normal from each single vertex position
  23926. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  23927. }
  23928. // Vertex normal need correction due to X,Y,Z radius scaling
  23929. vertex_normal.x /= radiusX;
  23930. vertex_normal.y /= radiusY;
  23931. vertex_normal.z /= radiusZ;
  23932. vertex_normal.normalize();
  23933. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  23934. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  23935. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  23936. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  23937. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  23938. uvs.push(uv_interp.x, uv_interp.y);
  23939. // push each vertex has member of a face
  23940. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  23941. indices.push(current_indice);
  23942. current_indice++;
  23943. };
  23944. for (var i2 = 0; i2 < subdivisions; i2++) {
  23945. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  23946. // face : (i1,i2) for /\ :
  23947. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  23948. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23949. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23950. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23951. if (i1 + i2 + 1 < subdivisions) {
  23952. // face : (i1,i2)' for \/ :
  23953. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23954. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23955. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23956. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23957. }
  23958. }
  23959. }
  23960. }
  23961. // Sides
  23962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23963. // Result
  23964. var vertexData = new VertexData();
  23965. vertexData.indices = indices;
  23966. vertexData.positions = positions;
  23967. vertexData.normals = normals;
  23968. vertexData.uvs = uvs;
  23969. return vertexData;
  23970. };
  23971. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23972. VertexData.CreatePolyhedron = function (options) {
  23973. // provided polyhedron types :
  23974. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23975. // 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)
  23976. var polyhedra = [];
  23977. 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]] };
  23978. 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]] };
  23979. polyhedra[2] = {
  23980. 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]],
  23981. 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]]
  23982. };
  23983. polyhedra[3] = {
  23984. 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]],
  23985. 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]]
  23986. };
  23987. polyhedra[4] = {
  23988. 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]],
  23989. 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]]
  23990. };
  23991. 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]] };
  23992. 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]] };
  23993. 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]] };
  23994. 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]] };
  23995. 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]] };
  23996. 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]] };
  23997. 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]] };
  23998. 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]] };
  23999. 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]] };
  24000. polyhedra[14] = {
  24001. 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]],
  24002. 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]]
  24003. };
  24004. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24005. var size = options.size;
  24006. var sizeX = options.sizeX || size || 1;
  24007. var sizeY = options.sizeY || size || 1;
  24008. var sizeZ = options.sizeZ || size || 1;
  24009. var data = options.custom || polyhedra[type];
  24010. var nbfaces = data.face.length;
  24011. var faceUV = options.faceUV || new Array(nbfaces);
  24012. var faceColors = options.faceColors;
  24013. var flat = (options.flat === undefined) ? true : options.flat;
  24014. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24015. var positions = [];
  24016. var indices = [];
  24017. var normals = [];
  24018. var uvs = [];
  24019. var colors = [];
  24020. var index = 0;
  24021. var faceIdx = 0; // face cursor in the array "indexes"
  24022. var indexes = [];
  24023. var i = 0;
  24024. var f = 0;
  24025. var u, v, ang, x, y, tmp;
  24026. // default face colors and UV if undefined
  24027. if (flat) {
  24028. for (f = 0; f < nbfaces; f++) {
  24029. if (faceColors && faceColors[f] === undefined) {
  24030. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24031. }
  24032. if (faceUV && faceUV[f] === undefined) {
  24033. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24034. }
  24035. }
  24036. }
  24037. if (!flat) {
  24038. for (i = 0; i < data.vertex.length; i++) {
  24039. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24040. uvs.push(0, 0);
  24041. }
  24042. for (f = 0; f < nbfaces; f++) {
  24043. for (i = 0; i < data.face[f].length - 2; i++) {
  24044. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24045. }
  24046. }
  24047. }
  24048. else {
  24049. for (f = 0; f < nbfaces; f++) {
  24050. var fl = data.face[f].length; // number of vertices of the current face
  24051. ang = 2 * Math.PI / fl;
  24052. x = 0.5 * Math.tan(ang / 2);
  24053. y = 0.5;
  24054. // positions, uvs, colors
  24055. for (i = 0; i < fl; i++) {
  24056. // positions
  24057. 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);
  24058. indexes.push(index);
  24059. index++;
  24060. // uvs
  24061. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24062. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24063. uvs.push(u, v);
  24064. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24065. y = x * Math.sin(ang) + y * Math.cos(ang);
  24066. x = tmp;
  24067. // colors
  24068. if (faceColors) {
  24069. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24070. }
  24071. }
  24072. // indices from indexes
  24073. for (i = 0; i < fl - 2; i++) {
  24074. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24075. }
  24076. faceIdx += fl;
  24077. }
  24078. }
  24079. VertexData.ComputeNormals(positions, indices, normals);
  24080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24081. var vertexData = new VertexData();
  24082. vertexData.positions = positions;
  24083. vertexData.indices = indices;
  24084. vertexData.normals = normals;
  24085. vertexData.uvs = uvs;
  24086. if (faceColors && flat) {
  24087. vertexData.colors = colors;
  24088. }
  24089. return vertexData;
  24090. };
  24091. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24092. VertexData.CreateTorusKnot = function (options) {
  24093. var indices = [];
  24094. var positions = [];
  24095. var normals = [];
  24096. var uvs = [];
  24097. var radius = options.radius || 2;
  24098. var tube = options.tube || 0.5;
  24099. var radialSegments = options.radialSegments || 32;
  24100. var tubularSegments = options.tubularSegments || 32;
  24101. var p = options.p || 2;
  24102. var q = options.q || 3;
  24103. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24104. // Helper
  24105. var getPos = function (angle) {
  24106. var cu = Math.cos(angle);
  24107. var su = Math.sin(angle);
  24108. var quOverP = q / p * angle;
  24109. var cs = Math.cos(quOverP);
  24110. var tx = radius * (2 + cs) * 0.5 * cu;
  24111. var ty = radius * (2 + cs) * su * 0.5;
  24112. var tz = radius * Math.sin(quOverP) * 0.5;
  24113. return new BABYLON.Vector3(tx, ty, tz);
  24114. };
  24115. // Vertices
  24116. var i;
  24117. var j;
  24118. for (i = 0; i <= radialSegments; i++) {
  24119. var modI = i % radialSegments;
  24120. var u = modI / radialSegments * 2 * p * Math.PI;
  24121. var p1 = getPos(u);
  24122. var p2 = getPos(u + 0.01);
  24123. var tang = p2.subtract(p1);
  24124. var n = p2.add(p1);
  24125. var bitan = BABYLON.Vector3.Cross(tang, n);
  24126. n = BABYLON.Vector3.Cross(bitan, tang);
  24127. bitan.normalize();
  24128. n.normalize();
  24129. for (j = 0; j < tubularSegments; j++) {
  24130. var modJ = j % tubularSegments;
  24131. var v = modJ / tubularSegments * 2 * Math.PI;
  24132. var cx = -tube * Math.cos(v);
  24133. var cy = tube * Math.sin(v);
  24134. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24135. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24136. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24137. uvs.push(i / radialSegments);
  24138. uvs.push(j / tubularSegments);
  24139. }
  24140. }
  24141. for (i = 0; i < radialSegments; i++) {
  24142. for (j = 0; j < tubularSegments; j++) {
  24143. var jNext = (j + 1) % tubularSegments;
  24144. var a = i * tubularSegments + j;
  24145. var b = (i + 1) * tubularSegments + j;
  24146. var c = (i + 1) * tubularSegments + jNext;
  24147. var d = i * tubularSegments + jNext;
  24148. indices.push(d);
  24149. indices.push(b);
  24150. indices.push(a);
  24151. indices.push(d);
  24152. indices.push(c);
  24153. indices.push(b);
  24154. }
  24155. }
  24156. // Normals
  24157. VertexData.ComputeNormals(positions, indices, normals);
  24158. // Sides
  24159. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24160. // Result
  24161. var vertexData = new VertexData();
  24162. vertexData.indices = indices;
  24163. vertexData.positions = positions;
  24164. vertexData.normals = normals;
  24165. vertexData.uvs = uvs;
  24166. return vertexData;
  24167. };
  24168. // Tools
  24169. /**
  24170. * @param {any} - positions (number[] or Float32Array)
  24171. * @param {any} - indices (number[] or Uint16Array)
  24172. * @param {any} - normals (number[] or Float32Array)
  24173. */
  24174. VertexData.ComputeNormals = function (positions, indices, normals) {
  24175. var index = 0;
  24176. var p1p2x = 0.0;
  24177. var p1p2y = 0.0;
  24178. var p1p2z = 0.0;
  24179. var p3p2x = 0.0;
  24180. var p3p2y = 0.0;
  24181. var p3p2z = 0.0;
  24182. var faceNormalx = 0.0;
  24183. var faceNormaly = 0.0;
  24184. var faceNormalz = 0.0;
  24185. var length = 0.0;
  24186. var i1 = 0;
  24187. var i2 = 0;
  24188. var i3 = 0;
  24189. for (index = 0; index < positions.length; index++) {
  24190. normals[index] = 0.0;
  24191. }
  24192. // indice triplet = 1 face
  24193. var nbFaces = indices.length / 3;
  24194. for (index = 0; index < nbFaces; index++) {
  24195. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24196. i2 = indices[index * 3 + 1];
  24197. i3 = indices[index * 3 + 2];
  24198. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24199. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24200. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24201. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24202. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24203. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24204. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24205. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24206. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24207. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24208. length = (length === 0) ? 1.0 : length;
  24209. faceNormalx /= length; // normalize this normal
  24210. faceNormaly /= length;
  24211. faceNormalz /= length;
  24212. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24213. normals[i1 * 3 + 1] += faceNormaly;
  24214. normals[i1 * 3 + 2] += faceNormalz;
  24215. normals[i2 * 3] += faceNormalx;
  24216. normals[i2 * 3 + 1] += faceNormaly;
  24217. normals[i2 * 3 + 2] += faceNormalz;
  24218. normals[i3 * 3] += faceNormalx;
  24219. normals[i3 * 3 + 1] += faceNormaly;
  24220. normals[i3 * 3 + 2] += faceNormalz;
  24221. }
  24222. // last normalization of each normal
  24223. for (index = 0; index < normals.length / 3; index++) {
  24224. faceNormalx = normals[index * 3];
  24225. faceNormaly = normals[index * 3 + 1];
  24226. faceNormalz = normals[index * 3 + 2];
  24227. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24228. length = (length === 0) ? 1.0 : length;
  24229. faceNormalx /= length;
  24230. faceNormaly /= length;
  24231. faceNormalz /= length;
  24232. normals[index * 3] = faceNormalx;
  24233. normals[index * 3 + 1] = faceNormaly;
  24234. normals[index * 3 + 2] = faceNormalz;
  24235. }
  24236. };
  24237. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24238. var li = indices.length;
  24239. var ln = normals.length;
  24240. var i;
  24241. var n;
  24242. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24243. switch (sideOrientation) {
  24244. case BABYLON.Mesh.FRONTSIDE:
  24245. // nothing changed
  24246. break;
  24247. case BABYLON.Mesh.BACKSIDE:
  24248. var tmp;
  24249. // indices
  24250. for (i = 0; i < li; i += 3) {
  24251. tmp = indices[i];
  24252. indices[i] = indices[i + 2];
  24253. indices[i + 2] = tmp;
  24254. }
  24255. // normals
  24256. for (n = 0; n < ln; n++) {
  24257. normals[n] = -normals[n];
  24258. }
  24259. break;
  24260. case BABYLON.Mesh.DOUBLESIDE:
  24261. // positions
  24262. var lp = positions.length;
  24263. var l = lp / 3;
  24264. for (var p = 0; p < lp; p++) {
  24265. positions[lp + p] = positions[p];
  24266. }
  24267. // indices
  24268. for (i = 0; i < li; i += 3) {
  24269. indices[i + li] = indices[i + 2] + l;
  24270. indices[i + 1 + li] = indices[i + 1] + l;
  24271. indices[i + 2 + li] = indices[i] + l;
  24272. }
  24273. // normals
  24274. for (n = 0; n < ln; n++) {
  24275. normals[ln + n] = -normals[n];
  24276. }
  24277. // uvs
  24278. var lu = uvs.length;
  24279. for (var u = 0; u < lu; u++) {
  24280. uvs[u + lu] = uvs[u];
  24281. }
  24282. break;
  24283. }
  24284. };
  24285. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24286. var vertexData = new VertexData();
  24287. // positions
  24288. var positions = parsedVertexData.positions;
  24289. if (positions) {
  24290. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24291. }
  24292. // normals
  24293. var normals = parsedVertexData.normals;
  24294. if (normals) {
  24295. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24296. }
  24297. // uvs
  24298. var uvs = parsedVertexData.uvs;
  24299. if (uvs) {
  24300. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24301. }
  24302. // uv2s
  24303. var uv2s = parsedVertexData.uv2s;
  24304. if (uv2s) {
  24305. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24306. }
  24307. // uv3s
  24308. var uv3s = parsedVertexData.uv3s;
  24309. if (uv3s) {
  24310. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24311. }
  24312. // uv4s
  24313. var uv4s = parsedVertexData.uv4s;
  24314. if (uv4s) {
  24315. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24316. }
  24317. // uv5s
  24318. var uv5s = parsedVertexData.uv5s;
  24319. if (uv5s) {
  24320. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24321. }
  24322. // uv6s
  24323. var uv6s = parsedVertexData.uv6s;
  24324. if (uv6s) {
  24325. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24326. }
  24327. // colors
  24328. var colors = parsedVertexData.colors;
  24329. if (colors) {
  24330. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24331. }
  24332. // matricesIndices
  24333. var matricesIndices = parsedVertexData.matricesIndices;
  24334. if (matricesIndices) {
  24335. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24336. }
  24337. // matricesWeights
  24338. var matricesWeights = parsedVertexData.matricesWeights;
  24339. if (matricesWeights) {
  24340. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24341. }
  24342. // indices
  24343. var indices = parsedVertexData.indices;
  24344. if (indices) {
  24345. vertexData.indices = indices;
  24346. }
  24347. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24348. };
  24349. return VertexData;
  24350. })();
  24351. BABYLON.VertexData = VertexData;
  24352. })(BABYLON || (BABYLON = {}));
  24353. var BABYLON;
  24354. (function (BABYLON) {
  24355. var Tags = (function () {
  24356. function Tags() {
  24357. }
  24358. Tags.EnableFor = function (obj) {
  24359. obj._tags = obj._tags || {};
  24360. obj.hasTags = function () {
  24361. return Tags.HasTags(obj);
  24362. };
  24363. obj.addTags = function (tagsString) {
  24364. return Tags.AddTagsTo(obj, tagsString);
  24365. };
  24366. obj.removeTags = function (tagsString) {
  24367. return Tags.RemoveTagsFrom(obj, tagsString);
  24368. };
  24369. obj.matchesTagsQuery = function (tagsQuery) {
  24370. return Tags.MatchesQuery(obj, tagsQuery);
  24371. };
  24372. };
  24373. Tags.DisableFor = function (obj) {
  24374. delete obj._tags;
  24375. delete obj.hasTags;
  24376. delete obj.addTags;
  24377. delete obj.removeTags;
  24378. delete obj.matchesTagsQuery;
  24379. };
  24380. Tags.HasTags = function (obj) {
  24381. if (!obj._tags) {
  24382. return false;
  24383. }
  24384. return !BABYLON.Tools.IsEmpty(obj._tags);
  24385. };
  24386. Tags.GetTags = function (obj) {
  24387. if (!obj._tags) {
  24388. return null;
  24389. }
  24390. return obj._tags;
  24391. };
  24392. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24393. // a tag cannot start with '||', '&&', and '!'
  24394. // it cannot contain whitespaces
  24395. Tags.AddTagsTo = function (obj, tagsString) {
  24396. if (!tagsString) {
  24397. return;
  24398. }
  24399. if (typeof tagsString !== "string") {
  24400. return;
  24401. }
  24402. var tags = tagsString.split(" ");
  24403. for (var t in tags) {
  24404. Tags._AddTagTo(obj, tags[t]);
  24405. }
  24406. };
  24407. Tags._AddTagTo = function (obj, tag) {
  24408. tag = tag.trim();
  24409. if (tag === "" || tag === "true" || tag === "false") {
  24410. return;
  24411. }
  24412. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24413. return;
  24414. }
  24415. Tags.EnableFor(obj);
  24416. obj._tags[tag] = true;
  24417. };
  24418. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24419. if (!Tags.HasTags(obj)) {
  24420. return;
  24421. }
  24422. var tags = tagsString.split(" ");
  24423. for (var t in tags) {
  24424. Tags._RemoveTagFrom(obj, tags[t]);
  24425. }
  24426. };
  24427. Tags._RemoveTagFrom = function (obj, tag) {
  24428. delete obj._tags[tag];
  24429. };
  24430. Tags.MatchesQuery = function (obj, tagsQuery) {
  24431. if (tagsQuery === undefined) {
  24432. return true;
  24433. }
  24434. if (tagsQuery === "") {
  24435. return Tags.HasTags(obj);
  24436. }
  24437. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24438. };
  24439. return Tags;
  24440. })();
  24441. BABYLON.Tags = Tags;
  24442. })(BABYLON || (BABYLON = {}));
  24443. var BABYLON;
  24444. (function (BABYLON) {
  24445. var Internals;
  24446. (function (Internals) {
  24447. var AndOrNotEvaluator = (function () {
  24448. function AndOrNotEvaluator() {
  24449. }
  24450. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24451. if (!query.match(/\([^\(\)]*\)/g)) {
  24452. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24453. }
  24454. else {
  24455. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24456. // remove parenthesis
  24457. r = r.slice(1, r.length - 1);
  24458. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24459. });
  24460. }
  24461. if (query === "true") {
  24462. return true;
  24463. }
  24464. if (query === "false") {
  24465. return false;
  24466. }
  24467. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24468. };
  24469. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24470. evaluateCallback = evaluateCallback || (function (r) {
  24471. return r === "true" ? true : false;
  24472. });
  24473. var result;
  24474. var or = parenthesisContent.split("||");
  24475. for (var i in or) {
  24476. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24477. var and = ori.split("&&");
  24478. if (and.length > 1) {
  24479. for (var j = 0; j < and.length; ++j) {
  24480. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24481. if (andj !== "true" && andj !== "false") {
  24482. if (andj[0] === "!") {
  24483. result = !evaluateCallback(andj.substring(1));
  24484. }
  24485. else {
  24486. result = evaluateCallback(andj);
  24487. }
  24488. }
  24489. else {
  24490. result = andj === "true" ? true : false;
  24491. }
  24492. if (!result) {
  24493. ori = "false";
  24494. break;
  24495. }
  24496. }
  24497. }
  24498. if (result || ori === "true") {
  24499. result = true;
  24500. break;
  24501. }
  24502. // result equals false (or undefined)
  24503. if (ori !== "true" && ori !== "false") {
  24504. if (ori[0] === "!") {
  24505. result = !evaluateCallback(ori.substring(1));
  24506. }
  24507. else {
  24508. result = evaluateCallback(ori);
  24509. }
  24510. }
  24511. else {
  24512. result = ori === "true" ? true : false;
  24513. }
  24514. }
  24515. // the whole parenthesis scope is replaced by 'true' or 'false'
  24516. return result ? "true" : "false";
  24517. };
  24518. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24519. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24520. // remove whitespaces
  24521. r = r.replace(/[\s]/g, function () { return ""; });
  24522. return r.length % 2 ? "!" : "";
  24523. });
  24524. booleanString = booleanString.trim();
  24525. if (booleanString === "!true") {
  24526. booleanString = "false";
  24527. }
  24528. else if (booleanString === "!false") {
  24529. booleanString = "true";
  24530. }
  24531. return booleanString;
  24532. };
  24533. return AndOrNotEvaluator;
  24534. })();
  24535. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24536. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24537. })(BABYLON || (BABYLON = {}));
  24538. var BABYLON;
  24539. (function (BABYLON) {
  24540. var PostProcessRenderPass = (function () {
  24541. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24542. this._enabled = true;
  24543. this._refCount = 0;
  24544. this._name = name;
  24545. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24546. this.setRenderList(renderList);
  24547. this._renderTexture.onBeforeRender = beforeRender;
  24548. this._renderTexture.onAfterRender = afterRender;
  24549. this._scene = scene;
  24550. this._renderList = renderList;
  24551. }
  24552. // private
  24553. PostProcessRenderPass.prototype._incRefCount = function () {
  24554. if (this._refCount === 0) {
  24555. this._scene.customRenderTargets.push(this._renderTexture);
  24556. }
  24557. return ++this._refCount;
  24558. };
  24559. PostProcessRenderPass.prototype._decRefCount = function () {
  24560. this._refCount--;
  24561. if (this._refCount <= 0) {
  24562. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24563. }
  24564. return this._refCount;
  24565. };
  24566. PostProcessRenderPass.prototype._update = function () {
  24567. this.setRenderList(this._renderList);
  24568. };
  24569. // public
  24570. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24571. this._renderTexture.renderList = renderList;
  24572. };
  24573. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24574. return this._renderTexture;
  24575. };
  24576. return PostProcessRenderPass;
  24577. })();
  24578. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24579. })(BABYLON || (BABYLON = {}));
  24580. var BABYLON;
  24581. (function (BABYLON) {
  24582. var PostProcessRenderEffect = (function () {
  24583. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24584. this._engine = engine;
  24585. this._name = name;
  24586. this._singleInstance = singleInstance || true;
  24587. this._getPostProcess = getPostProcess;
  24588. this._cameras = [];
  24589. this._indicesForCamera = [];
  24590. this._postProcesses = {};
  24591. this._renderPasses = {};
  24592. this._renderEffectAsPasses = {};
  24593. }
  24594. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24595. get: function () {
  24596. for (var index in this._postProcesses) {
  24597. if (!this._postProcesses[index].isSupported) {
  24598. return false;
  24599. }
  24600. }
  24601. return true;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. PostProcessRenderEffect.prototype._update = function () {
  24607. for (var renderPassName in this._renderPasses) {
  24608. this._renderPasses[renderPassName]._update();
  24609. }
  24610. };
  24611. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24612. this._renderPasses[renderPass._name] = renderPass;
  24613. this._linkParameters();
  24614. };
  24615. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24616. delete this._renderPasses[renderPass._name];
  24617. this._linkParameters();
  24618. };
  24619. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24620. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24621. this._linkParameters();
  24622. };
  24623. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24624. for (var renderPassName in this._renderPasses) {
  24625. if (renderPassName === passName) {
  24626. return this._renderPasses[passName];
  24627. }
  24628. }
  24629. };
  24630. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24631. this._renderPasses = {};
  24632. this._linkParameters();
  24633. };
  24634. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24635. var cameraKey;
  24636. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24637. for (var i = 0; i < _cam.length; i++) {
  24638. var camera = _cam[i];
  24639. var cameraName = camera.name;
  24640. if (this._singleInstance) {
  24641. cameraKey = 0;
  24642. }
  24643. else {
  24644. cameraKey = cameraName;
  24645. }
  24646. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24647. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24648. if (!this._indicesForCamera[cameraName]) {
  24649. this._indicesForCamera[cameraName] = [];
  24650. }
  24651. this._indicesForCamera[cameraName].push(index);
  24652. if (this._cameras.indexOf(camera) === -1) {
  24653. this._cameras[cameraName] = camera;
  24654. }
  24655. for (var passName in this._renderPasses) {
  24656. this._renderPasses[passName]._incRefCount();
  24657. }
  24658. }
  24659. this._linkParameters();
  24660. };
  24661. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24663. for (var i = 0; i < _cam.length; i++) {
  24664. var camera = _cam[i];
  24665. var cameraName = camera.name;
  24666. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24667. var index = this._cameras.indexOf(cameraName);
  24668. this._indicesForCamera.splice(index, 1);
  24669. this._cameras.splice(index, 1);
  24670. for (var passName in this._renderPasses) {
  24671. this._renderPasses[passName]._decRefCount();
  24672. }
  24673. }
  24674. };
  24675. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24676. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24677. for (var i = 0; i < _cam.length; i++) {
  24678. var camera = _cam[i];
  24679. var cameraName = camera.name;
  24680. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24681. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24682. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24683. }
  24684. }
  24685. for (var passName in this._renderPasses) {
  24686. this._renderPasses[passName]._incRefCount();
  24687. }
  24688. }
  24689. };
  24690. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24691. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24692. for (var i = 0; i < _cam.length; i++) {
  24693. var camera = _cam[i];
  24694. var cameraName = camera.Name;
  24695. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24696. for (var passName in this._renderPasses) {
  24697. this._renderPasses[passName]._decRefCount();
  24698. }
  24699. }
  24700. };
  24701. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24702. if (this._singleInstance) {
  24703. return this._postProcesses[0];
  24704. }
  24705. else {
  24706. return this._postProcesses[camera.name];
  24707. }
  24708. };
  24709. PostProcessRenderEffect.prototype._linkParameters = function () {
  24710. var _this = this;
  24711. for (var index in this._postProcesses) {
  24712. if (this.applyParameters) {
  24713. this.applyParameters(this._postProcesses[index]);
  24714. }
  24715. this._postProcesses[index].onBeforeRender = function (effect) {
  24716. _this._linkTextures(effect);
  24717. };
  24718. }
  24719. };
  24720. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24721. for (var renderPassName in this._renderPasses) {
  24722. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24723. }
  24724. for (var renderEffectName in this._renderEffectAsPasses) {
  24725. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24726. }
  24727. };
  24728. return PostProcessRenderEffect;
  24729. })();
  24730. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24731. })(BABYLON || (BABYLON = {}));
  24732. var BABYLON;
  24733. (function (BABYLON) {
  24734. var PostProcessRenderPipeline = (function () {
  24735. function PostProcessRenderPipeline(engine, name) {
  24736. this._engine = engine;
  24737. this._name = name;
  24738. this._renderEffects = {};
  24739. this._renderEffectsForIsolatedPass = {};
  24740. this._cameras = [];
  24741. }
  24742. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24743. get: function () {
  24744. for (var renderEffectName in this._renderEffects) {
  24745. if (!this._renderEffects[renderEffectName].isSupported) {
  24746. return false;
  24747. }
  24748. }
  24749. return true;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24755. this._renderEffects[renderEffect._name] = renderEffect;
  24756. };
  24757. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24758. var renderEffects = this._renderEffects[renderEffectName];
  24759. if (!renderEffects) {
  24760. return;
  24761. }
  24762. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24763. };
  24764. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24765. var renderEffects = this._renderEffects[renderEffectName];
  24766. if (!renderEffects) {
  24767. return;
  24768. }
  24769. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24770. };
  24771. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24772. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24773. var indicesToDelete = [];
  24774. var i;
  24775. for (i = 0; i < _cam.length; i++) {
  24776. var camera = _cam[i];
  24777. var cameraName = camera.name;
  24778. if (this._cameras.indexOf(camera) === -1) {
  24779. this._cameras[cameraName] = camera;
  24780. }
  24781. else if (unique) {
  24782. indicesToDelete.push(i);
  24783. }
  24784. }
  24785. for (i = 0; i < indicesToDelete.length; i++) {
  24786. cameras.splice(indicesToDelete[i], 1);
  24787. }
  24788. for (var renderEffectName in this._renderEffects) {
  24789. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24790. }
  24791. };
  24792. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24793. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24794. for (var renderEffectName in this._renderEffects) {
  24795. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24796. }
  24797. for (var i = 0; i < _cam.length; i++) {
  24798. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24799. }
  24800. };
  24801. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24802. var _this = this;
  24803. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24804. var pass = null;
  24805. var renderEffectName;
  24806. for (renderEffectName in this._renderEffects) {
  24807. pass = this._renderEffects[renderEffectName].getPass(passName);
  24808. if (pass != null) {
  24809. break;
  24810. }
  24811. }
  24812. if (pass === null) {
  24813. return;
  24814. }
  24815. for (renderEffectName in this._renderEffects) {
  24816. this._renderEffects[renderEffectName]._disable(_cam);
  24817. }
  24818. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24819. for (var i = 0; i < _cam.length; i++) {
  24820. var camera = _cam[i];
  24821. var cameraName = camera.name;
  24822. 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); });
  24823. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24824. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24825. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24826. }
  24827. };
  24828. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24829. var _this = this;
  24830. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24831. for (var i = 0; i < _cam.length; i++) {
  24832. var camera = _cam[i];
  24833. var cameraName = camera.name;
  24834. 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); });
  24835. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24836. }
  24837. for (var renderEffectName in this._renderEffects) {
  24838. this._renderEffects[renderEffectName]._enable(_cam);
  24839. }
  24840. };
  24841. PostProcessRenderPipeline.prototype._update = function () {
  24842. for (var renderEffectName in this._renderEffects) {
  24843. this._renderEffects[renderEffectName]._update();
  24844. }
  24845. for (var i = 0; i < this._cameras.length; i++) {
  24846. var cameraName = this._cameras[i].name;
  24847. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24848. this._renderEffectsForIsolatedPass[cameraName]._update();
  24849. }
  24850. }
  24851. };
  24852. PostProcessRenderPipeline.prototype.dispose = function () {
  24853. // Must be implemented by children
  24854. };
  24855. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24856. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24857. return PostProcessRenderPipeline;
  24858. })();
  24859. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24860. })(BABYLON || (BABYLON = {}));
  24861. var BABYLON;
  24862. (function (BABYLON) {
  24863. var PostProcessRenderPipelineManager = (function () {
  24864. function PostProcessRenderPipelineManager() {
  24865. this._renderPipelines = {};
  24866. }
  24867. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24868. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24869. };
  24870. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24871. var renderPipeline = this._renderPipelines[renderPipelineName];
  24872. if (!renderPipeline) {
  24873. return;
  24874. }
  24875. renderPipeline._attachCameras(cameras, unique);
  24876. };
  24877. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24878. var renderPipeline = this._renderPipelines[renderPipelineName];
  24879. if (!renderPipeline) {
  24880. return;
  24881. }
  24882. renderPipeline._detachCameras(cameras);
  24883. };
  24884. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24885. var renderPipeline = this._renderPipelines[renderPipelineName];
  24886. if (!renderPipeline) {
  24887. return;
  24888. }
  24889. renderPipeline._enableEffect(renderEffectName, cameras);
  24890. };
  24891. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24892. var renderPipeline = this._renderPipelines[renderPipelineName];
  24893. if (!renderPipeline) {
  24894. return;
  24895. }
  24896. renderPipeline._disableEffect(renderEffectName, cameras);
  24897. };
  24898. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24899. var renderPipeline = this._renderPipelines[renderPipelineName];
  24900. if (!renderPipeline) {
  24901. return;
  24902. }
  24903. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24904. };
  24905. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24906. var renderPipeline = this._renderPipelines[renderPipelineName];
  24907. if (!renderPipeline) {
  24908. return;
  24909. }
  24910. renderPipeline._disableDisplayOnlyPass(cameras);
  24911. };
  24912. PostProcessRenderPipelineManager.prototype.update = function () {
  24913. for (var renderPipelineName in this._renderPipelines) {
  24914. var pipeline = this._renderPipelines[renderPipelineName];
  24915. if (!pipeline.isSupported) {
  24916. pipeline.dispose();
  24917. delete this._renderPipelines[renderPipelineName];
  24918. }
  24919. else {
  24920. pipeline._update();
  24921. }
  24922. }
  24923. };
  24924. return PostProcessRenderPipelineManager;
  24925. })();
  24926. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24927. })(BABYLON || (BABYLON = {}));
  24928. var BABYLON;
  24929. (function (BABYLON) {
  24930. var BoundingBoxRenderer = (function () {
  24931. function BoundingBoxRenderer(scene) {
  24932. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24933. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24934. this.showBackLines = true;
  24935. this.renderList = new BABYLON.SmartArray(32);
  24936. this._scene = scene;
  24937. }
  24938. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24939. if (this._colorShader) {
  24940. return;
  24941. }
  24942. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24943. attributes: ["position"],
  24944. uniforms: ["worldViewProjection", "color"]
  24945. });
  24946. var engine = this._scene.getEngine();
  24947. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24948. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24949. 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]);
  24950. };
  24951. BoundingBoxRenderer.prototype.reset = function () {
  24952. this.renderList.reset();
  24953. };
  24954. BoundingBoxRenderer.prototype.render = function () {
  24955. if (this.renderList.length === 0) {
  24956. return;
  24957. }
  24958. this._prepareRessources();
  24959. if (!this._colorShader.isReady()) {
  24960. return;
  24961. }
  24962. var engine = this._scene.getEngine();
  24963. engine.setDepthWrite(false);
  24964. this._colorShader._preBind();
  24965. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24966. var boundingBox = this.renderList.data[boundingBoxIndex];
  24967. var min = boundingBox.minimum;
  24968. var max = boundingBox.maximum;
  24969. var diff = max.subtract(min);
  24970. var median = min.add(diff.scale(0.5));
  24971. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24972. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24973. .multiply(boundingBox.getWorldMatrix());
  24974. // VBOs
  24975. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24976. if (this.showBackLines) {
  24977. // Back
  24978. engine.setDepthFunctionToGreaterOrEqual();
  24979. this._scene.resetCachedMaterial();
  24980. this._colorShader.setColor4("color", this.backColor.toColor4());
  24981. this._colorShader.bind(worldMatrix);
  24982. // Draw order
  24983. engine.draw(false, 0, 24);
  24984. }
  24985. // Front
  24986. engine.setDepthFunctionToLess();
  24987. this._scene.resetCachedMaterial();
  24988. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24989. this._colorShader.bind(worldMatrix);
  24990. // Draw order
  24991. engine.draw(false, 0, 24);
  24992. }
  24993. this._colorShader.unbind();
  24994. engine.setDepthFunctionToLessOrEqual();
  24995. engine.setDepthWrite(true);
  24996. };
  24997. BoundingBoxRenderer.prototype.dispose = function () {
  24998. if (!this._colorShader) {
  24999. return;
  25000. }
  25001. this._colorShader.dispose();
  25002. this._vb.dispose();
  25003. this._scene.getEngine()._releaseBuffer(this._ib);
  25004. };
  25005. return BoundingBoxRenderer;
  25006. })();
  25007. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25008. })(BABYLON || (BABYLON = {}));
  25009. var BABYLON;
  25010. (function (BABYLON) {
  25011. var Condition = (function () {
  25012. function Condition(actionManager) {
  25013. this._actionManager = actionManager;
  25014. }
  25015. Condition.prototype.isValid = function () {
  25016. return true;
  25017. };
  25018. Condition.prototype._getProperty = function (propertyPath) {
  25019. return this._actionManager._getProperty(propertyPath);
  25020. };
  25021. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25022. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25023. };
  25024. return Condition;
  25025. })();
  25026. BABYLON.Condition = Condition;
  25027. var ValueCondition = (function (_super) {
  25028. __extends(ValueCondition, _super);
  25029. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25030. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25031. _super.call(this, actionManager);
  25032. this.propertyPath = propertyPath;
  25033. this.value = value;
  25034. this.operator = operator;
  25035. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25036. this._property = this._getProperty(this.propertyPath);
  25037. }
  25038. Object.defineProperty(ValueCondition, "IsEqual", {
  25039. get: function () {
  25040. return ValueCondition._IsEqual;
  25041. },
  25042. enumerable: true,
  25043. configurable: true
  25044. });
  25045. Object.defineProperty(ValueCondition, "IsDifferent", {
  25046. get: function () {
  25047. return ValueCondition._IsDifferent;
  25048. },
  25049. enumerable: true,
  25050. configurable: true
  25051. });
  25052. Object.defineProperty(ValueCondition, "IsGreater", {
  25053. get: function () {
  25054. return ValueCondition._IsGreater;
  25055. },
  25056. enumerable: true,
  25057. configurable: true
  25058. });
  25059. Object.defineProperty(ValueCondition, "IsLesser", {
  25060. get: function () {
  25061. return ValueCondition._IsLesser;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. // Methods
  25067. ValueCondition.prototype.isValid = function () {
  25068. switch (this.operator) {
  25069. case ValueCondition.IsGreater:
  25070. return this._target[this._property] > this.value;
  25071. case ValueCondition.IsLesser:
  25072. return this._target[this._property] < this.value;
  25073. case ValueCondition.IsEqual:
  25074. case ValueCondition.IsDifferent:
  25075. var check;
  25076. if (this.value.equals) {
  25077. check = this.value.equals(this._target[this._property]);
  25078. }
  25079. else {
  25080. check = this.value === this._target[this._property];
  25081. }
  25082. return this.operator === ValueCondition.IsEqual ? check : !check;
  25083. }
  25084. return false;
  25085. };
  25086. // Statics
  25087. ValueCondition._IsEqual = 0;
  25088. ValueCondition._IsDifferent = 1;
  25089. ValueCondition._IsGreater = 2;
  25090. ValueCondition._IsLesser = 3;
  25091. return ValueCondition;
  25092. })(Condition);
  25093. BABYLON.ValueCondition = ValueCondition;
  25094. var PredicateCondition = (function (_super) {
  25095. __extends(PredicateCondition, _super);
  25096. function PredicateCondition(actionManager, predicate) {
  25097. _super.call(this, actionManager);
  25098. this.predicate = predicate;
  25099. }
  25100. PredicateCondition.prototype.isValid = function () {
  25101. return this.predicate();
  25102. };
  25103. return PredicateCondition;
  25104. })(Condition);
  25105. BABYLON.PredicateCondition = PredicateCondition;
  25106. var StateCondition = (function (_super) {
  25107. __extends(StateCondition, _super);
  25108. function StateCondition(actionManager, target, value) {
  25109. _super.call(this, actionManager);
  25110. this.value = value;
  25111. this._target = target;
  25112. }
  25113. // Methods
  25114. StateCondition.prototype.isValid = function () {
  25115. return this._target.state === this.value;
  25116. };
  25117. return StateCondition;
  25118. })(Condition);
  25119. BABYLON.StateCondition = StateCondition;
  25120. })(BABYLON || (BABYLON = {}));
  25121. var BABYLON;
  25122. (function (BABYLON) {
  25123. var Action = (function () {
  25124. function Action(triggerOptions, condition) {
  25125. this.triggerOptions = triggerOptions;
  25126. if (triggerOptions.parameter) {
  25127. this.trigger = triggerOptions.trigger;
  25128. this._triggerParameter = triggerOptions.parameter;
  25129. }
  25130. else {
  25131. this.trigger = triggerOptions;
  25132. }
  25133. this._nextActiveAction = this;
  25134. this._condition = condition;
  25135. }
  25136. // Methods
  25137. Action.prototype._prepare = function () {
  25138. };
  25139. Action.prototype.getTriggerParameter = function () {
  25140. return this._triggerParameter;
  25141. };
  25142. Action.prototype._executeCurrent = function (evt) {
  25143. if (this._nextActiveAction._condition) {
  25144. var condition = this._nextActiveAction._condition;
  25145. var currentRenderId = this._actionManager.getScene().getRenderId();
  25146. // We cache the current evaluation for the current frame
  25147. if (condition._evaluationId === currentRenderId) {
  25148. if (!condition._currentResult) {
  25149. return;
  25150. }
  25151. }
  25152. else {
  25153. condition._evaluationId = currentRenderId;
  25154. if (!condition.isValid()) {
  25155. condition._currentResult = false;
  25156. return;
  25157. }
  25158. condition._currentResult = true;
  25159. }
  25160. }
  25161. this._nextActiveAction.execute(evt);
  25162. if (this._nextActiveAction._child) {
  25163. if (!this._nextActiveAction._child._actionManager) {
  25164. this._nextActiveAction._child._actionManager = this._actionManager;
  25165. }
  25166. this._nextActiveAction = this._nextActiveAction._child;
  25167. }
  25168. else {
  25169. this._nextActiveAction = this;
  25170. }
  25171. };
  25172. Action.prototype.execute = function (evt) {
  25173. };
  25174. Action.prototype.then = function (action) {
  25175. this._child = action;
  25176. action._actionManager = this._actionManager;
  25177. action._prepare();
  25178. return action;
  25179. };
  25180. Action.prototype._getProperty = function (propertyPath) {
  25181. return this._actionManager._getProperty(propertyPath);
  25182. };
  25183. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25184. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25185. };
  25186. return Action;
  25187. })();
  25188. BABYLON.Action = Action;
  25189. })(BABYLON || (BABYLON = {}));
  25190. var BABYLON;
  25191. (function (BABYLON) {
  25192. /**
  25193. * ActionEvent is the event beint sent when an action is triggered.
  25194. */
  25195. var ActionEvent = (function () {
  25196. /**
  25197. * @constructor
  25198. * @param source The mesh or sprite that triggered the action.
  25199. * @param pointerX The X mouse cursor position at the time of the event
  25200. * @param pointerY The Y mouse cursor position at the time of the event
  25201. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25202. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25203. */
  25204. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25205. this.source = source;
  25206. this.pointerX = pointerX;
  25207. this.pointerY = pointerY;
  25208. this.meshUnderPointer = meshUnderPointer;
  25209. this.sourceEvent = sourceEvent;
  25210. this.additionalData = additionalData;
  25211. }
  25212. /**
  25213. * Helper function to auto-create an ActionEvent from a source mesh.
  25214. * @param source The source mesh that triggered the event
  25215. * @param evt {Event} The original (browser) event
  25216. */
  25217. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25218. var scene = source.getScene();
  25219. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25220. };
  25221. /**
  25222. * Helper function to auto-create an ActionEvent from a source mesh.
  25223. * @param source The source sprite that triggered the event
  25224. * @param scene Scene associated with the sprite
  25225. * @param evt {Event} The original (browser) event
  25226. */
  25227. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25228. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25229. };
  25230. /**
  25231. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25232. * @param scene the scene where the event occurred
  25233. * @param evt {Event} The original (browser) event
  25234. */
  25235. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25236. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25237. };
  25238. return ActionEvent;
  25239. })();
  25240. BABYLON.ActionEvent = ActionEvent;
  25241. /**
  25242. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25243. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25244. */
  25245. var ActionManager = (function () {
  25246. function ActionManager(scene) {
  25247. // Members
  25248. this.actions = new Array();
  25249. this._scene = scene;
  25250. scene._actionManagers.push(this);
  25251. }
  25252. Object.defineProperty(ActionManager, "NothingTrigger", {
  25253. get: function () {
  25254. return ActionManager._NothingTrigger;
  25255. },
  25256. enumerable: true,
  25257. configurable: true
  25258. });
  25259. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25260. get: function () {
  25261. return ActionManager._OnPickTrigger;
  25262. },
  25263. enumerable: true,
  25264. configurable: true
  25265. });
  25266. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25267. get: function () {
  25268. return ActionManager._OnLeftPickTrigger;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25274. get: function () {
  25275. return ActionManager._OnRightPickTrigger;
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25281. get: function () {
  25282. return ActionManager._OnCenterPickTrigger;
  25283. },
  25284. enumerable: true,
  25285. configurable: true
  25286. });
  25287. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25288. get: function () {
  25289. return ActionManager._OnPointerOverTrigger;
  25290. },
  25291. enumerable: true,
  25292. configurable: true
  25293. });
  25294. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25295. get: function () {
  25296. return ActionManager._OnPointerOutTrigger;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25302. get: function () {
  25303. return ActionManager._OnEveryFrameTrigger;
  25304. },
  25305. enumerable: true,
  25306. configurable: true
  25307. });
  25308. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25309. get: function () {
  25310. return ActionManager._OnIntersectionEnterTrigger;
  25311. },
  25312. enumerable: true,
  25313. configurable: true
  25314. });
  25315. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25316. get: function () {
  25317. return ActionManager._OnIntersectionExitTrigger;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25323. get: function () {
  25324. return ActionManager._OnKeyDownTrigger;
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25330. get: function () {
  25331. return ActionManager._OnKeyUpTrigger;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25337. get: function () {
  25338. return ActionManager._OnPickUpTrigger;
  25339. },
  25340. enumerable: true,
  25341. configurable: true
  25342. });
  25343. // Methods
  25344. ActionManager.prototype.dispose = function () {
  25345. var index = this._scene._actionManagers.indexOf(this);
  25346. if (index > -1) {
  25347. this._scene._actionManagers.splice(index, 1);
  25348. }
  25349. };
  25350. ActionManager.prototype.getScene = function () {
  25351. return this._scene;
  25352. };
  25353. /**
  25354. * Does this action manager handles actions of any of the given triggers
  25355. * @param {number[]} triggers - the triggers to be tested
  25356. * @return {boolean} whether one (or more) of the triggers is handeled
  25357. */
  25358. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25359. for (var index = 0; index < this.actions.length; index++) {
  25360. var action = this.actions[index];
  25361. if (triggers.indexOf(action.trigger) > -1) {
  25362. return true;
  25363. }
  25364. }
  25365. return false;
  25366. };
  25367. /**
  25368. * Does this action manager handles actions of a given trigger
  25369. * @param {number} trigger - the trigger to be tested
  25370. * @return {boolean} whether the trigger is handeled
  25371. */
  25372. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25373. for (var index = 0; index < this.actions.length; index++) {
  25374. var action = this.actions[index];
  25375. if (action.trigger === trigger) {
  25376. return true;
  25377. }
  25378. }
  25379. return false;
  25380. };
  25381. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25382. /**
  25383. * Does this action manager has pointer triggers
  25384. * @return {boolean} whether or not it has pointer triggers
  25385. */
  25386. get: function () {
  25387. for (var index = 0; index < this.actions.length; index++) {
  25388. var action = this.actions[index];
  25389. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25390. return true;
  25391. }
  25392. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25393. return true;
  25394. }
  25395. }
  25396. return false;
  25397. },
  25398. enumerable: true,
  25399. configurable: true
  25400. });
  25401. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25402. /**
  25403. * Does this action manager has pick triggers
  25404. * @return {boolean} whether or not it has pick triggers
  25405. */
  25406. get: function () {
  25407. for (var index = 0; index < this.actions.length; index++) {
  25408. var action = this.actions[index];
  25409. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25410. return true;
  25411. }
  25412. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25413. return true;
  25414. }
  25415. }
  25416. return false;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. /**
  25422. * Registers an action to this action manager
  25423. * @param {BABYLON.Action} action - the action to be registered
  25424. * @return {BABYLON.Action} the action amended (prepared) after registration
  25425. */
  25426. ActionManager.prototype.registerAction = function (action) {
  25427. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25428. if (this.getScene().actionManager !== this) {
  25429. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25430. return null;
  25431. }
  25432. }
  25433. this.actions.push(action);
  25434. action._actionManager = this;
  25435. action._prepare();
  25436. return action;
  25437. };
  25438. /**
  25439. * Process a specific trigger
  25440. * @param {number} trigger - the trigger to process
  25441. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25442. */
  25443. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25444. for (var index = 0; index < this.actions.length; index++) {
  25445. var action = this.actions[index];
  25446. if (action.trigger === trigger) {
  25447. if (trigger === ActionManager.OnKeyUpTrigger
  25448. || trigger === ActionManager.OnKeyDownTrigger) {
  25449. var parameter = action.getTriggerParameter();
  25450. if (parameter) {
  25451. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25452. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25453. if (actualkey !== parameter.toLowerCase()) {
  25454. continue;
  25455. }
  25456. }
  25457. }
  25458. action._executeCurrent(evt);
  25459. }
  25460. }
  25461. };
  25462. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25463. var properties = propertyPath.split(".");
  25464. for (var index = 0; index < properties.length - 1; index++) {
  25465. target = target[properties[index]];
  25466. }
  25467. return target;
  25468. };
  25469. ActionManager.prototype._getProperty = function (propertyPath) {
  25470. var properties = propertyPath.split(".");
  25471. return properties[properties.length - 1];
  25472. };
  25473. ActionManager.Parse = function (parsedActions, object, scene) {
  25474. var actionManager = new BABYLON.ActionManager(scene);
  25475. if (object === null)
  25476. scene.actionManager = actionManager;
  25477. else
  25478. object.actionManager = actionManager;
  25479. // instanciate a new object
  25480. var instanciate = function (name, params) {
  25481. var newInstance = Object.create(BABYLON[name].prototype);
  25482. newInstance.constructor.apply(newInstance, params);
  25483. return newInstance;
  25484. };
  25485. var parseParameter = function (name, value, target, propertyPath) {
  25486. if (propertyPath === null) {
  25487. // String, boolean or float
  25488. var floatValue = parseFloat(value);
  25489. if (value === "true" || value === "false")
  25490. return value === "true";
  25491. else
  25492. return isNaN(floatValue) ? value : floatValue;
  25493. }
  25494. var effectiveTarget = propertyPath.split(".");
  25495. var values = value.split(",");
  25496. // Get effective Target
  25497. for (var i = 0; i < effectiveTarget.length; i++) {
  25498. target = target[effectiveTarget[i]];
  25499. }
  25500. // Return appropriate value with its type
  25501. if (typeof (target) === "boolean")
  25502. return values[0] === "true";
  25503. if (typeof (target) === "string")
  25504. return values[0];
  25505. // Parameters with multiple values such as Vector3 etc.
  25506. var split = new Array();
  25507. for (var i = 0; i < values.length; i++)
  25508. split.push(parseFloat(values[i]));
  25509. if (target instanceof BABYLON.Vector3)
  25510. return BABYLON.Vector3.FromArray(split);
  25511. if (target instanceof BABYLON.Vector4)
  25512. return BABYLON.Vector4.FromArray(split);
  25513. if (target instanceof BABYLON.Color3)
  25514. return BABYLON.Color3.FromArray(split);
  25515. if (target instanceof BABYLON.Color4)
  25516. return BABYLON.Color4.FromArray(split);
  25517. return parseFloat(values[0]);
  25518. };
  25519. // traverse graph per trigger
  25520. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25521. if (combineArray === void 0) { combineArray = null; }
  25522. if (parsedAction.detached)
  25523. return;
  25524. var parameters = new Array();
  25525. var target = null;
  25526. var propertyPath = null;
  25527. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25528. // Parameters
  25529. if (parsedAction.type === 2)
  25530. parameters.push(actionManager);
  25531. else
  25532. parameters.push(trigger);
  25533. if (combine) {
  25534. var actions = new Array();
  25535. for (var j = 0; j < parsedAction.combine.length; j++) {
  25536. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25537. }
  25538. parameters.push(actions);
  25539. }
  25540. else {
  25541. for (var i = 0; i < parsedAction.properties.length; i++) {
  25542. var value = parsedAction.properties[i].value;
  25543. var name = parsedAction.properties[i].name;
  25544. var targetType = parsedAction.properties[i].targetType;
  25545. if (name === "target")
  25546. if (targetType !== null && targetType === "SceneProperties")
  25547. value = target = scene;
  25548. else
  25549. value = target = scene.getNodeByName(value);
  25550. else if (name === "parent")
  25551. value = scene.getNodeByName(value);
  25552. else if (name === "sound")
  25553. value = scene.getSoundByName(value);
  25554. else if (name !== "propertyPath") {
  25555. if (parsedAction.type === 2 && name === "operator")
  25556. value = BABYLON.ValueCondition[value];
  25557. else
  25558. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25559. }
  25560. else {
  25561. propertyPath = value;
  25562. }
  25563. parameters.push(value);
  25564. }
  25565. }
  25566. if (combineArray === null) {
  25567. parameters.push(condition);
  25568. }
  25569. else {
  25570. parameters.push(null);
  25571. }
  25572. // If interpolate value action
  25573. if (parsedAction.name === "InterpolateValueAction") {
  25574. var param = parameters[parameters.length - 2];
  25575. parameters[parameters.length - 1] = param;
  25576. parameters[parameters.length - 2] = condition;
  25577. }
  25578. // Action or condition(s) and not CombineAction
  25579. var newAction = instanciate(parsedAction.name, parameters);
  25580. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25581. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25582. if (action)
  25583. action.then(nothing);
  25584. else
  25585. actionManager.registerAction(nothing);
  25586. action = nothing;
  25587. }
  25588. if (combineArray === null) {
  25589. if (newAction instanceof BABYLON.Condition) {
  25590. condition = newAction;
  25591. newAction = action;
  25592. }
  25593. else {
  25594. condition = null;
  25595. if (action)
  25596. action.then(newAction);
  25597. else
  25598. actionManager.registerAction(newAction);
  25599. }
  25600. }
  25601. else {
  25602. combineArray.push(newAction);
  25603. }
  25604. for (var i = 0; i < parsedAction.children.length; i++)
  25605. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25606. };
  25607. // triggers
  25608. for (var i = 0; i < parsedActions.children.length; i++) {
  25609. var triggerParams;
  25610. var trigger = parsedActions.children[i];
  25611. if (trigger.properties.length > 0) {
  25612. var param = trigger.properties[0].value;
  25613. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25614. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25615. }
  25616. else
  25617. triggerParams = BABYLON.ActionManager[trigger.name];
  25618. for (var j = 0; j < trigger.children.length; j++) {
  25619. if (!trigger.detached)
  25620. traverse(trigger.children[j], triggerParams, null, null);
  25621. }
  25622. }
  25623. };
  25624. // Statics
  25625. ActionManager._NothingTrigger = 0;
  25626. ActionManager._OnPickTrigger = 1;
  25627. ActionManager._OnLeftPickTrigger = 2;
  25628. ActionManager._OnRightPickTrigger = 3;
  25629. ActionManager._OnCenterPickTrigger = 4;
  25630. ActionManager._OnPointerOverTrigger = 5;
  25631. ActionManager._OnPointerOutTrigger = 6;
  25632. ActionManager._OnEveryFrameTrigger = 7;
  25633. ActionManager._OnIntersectionEnterTrigger = 8;
  25634. ActionManager._OnIntersectionExitTrigger = 9;
  25635. ActionManager._OnKeyDownTrigger = 10;
  25636. ActionManager._OnKeyUpTrigger = 11;
  25637. ActionManager._OnPickUpTrigger = 12;
  25638. return ActionManager;
  25639. })();
  25640. BABYLON.ActionManager = ActionManager;
  25641. })(BABYLON || (BABYLON = {}));
  25642. var BABYLON;
  25643. (function (BABYLON) {
  25644. var InterpolateValueAction = (function (_super) {
  25645. __extends(InterpolateValueAction, _super);
  25646. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25647. if (duration === void 0) { duration = 1000; }
  25648. _super.call(this, triggerOptions, condition);
  25649. this.propertyPath = propertyPath;
  25650. this.value = value;
  25651. this.duration = duration;
  25652. this.stopOtherAnimations = stopOtherAnimations;
  25653. this.onInterpolationDone = onInterpolationDone;
  25654. this._target = target;
  25655. }
  25656. InterpolateValueAction.prototype._prepare = function () {
  25657. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25658. this._property = this._getProperty(this.propertyPath);
  25659. };
  25660. InterpolateValueAction.prototype.execute = function () {
  25661. var scene = this._actionManager.getScene();
  25662. var keys = [
  25663. {
  25664. frame: 0,
  25665. value: this._target[this._property]
  25666. }, {
  25667. frame: 100,
  25668. value: this.value
  25669. }
  25670. ];
  25671. var dataType;
  25672. if (typeof this.value === "number") {
  25673. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25674. }
  25675. else if (this.value instanceof BABYLON.Color3) {
  25676. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25677. }
  25678. else if (this.value instanceof BABYLON.Vector3) {
  25679. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25680. }
  25681. else if (this.value instanceof BABYLON.Matrix) {
  25682. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25683. }
  25684. else if (this.value instanceof BABYLON.Quaternion) {
  25685. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25686. }
  25687. else {
  25688. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25689. return;
  25690. }
  25691. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25692. animation.setKeys(keys);
  25693. if (this.stopOtherAnimations) {
  25694. scene.stopAnimation(this._target);
  25695. }
  25696. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25697. };
  25698. return InterpolateValueAction;
  25699. })(BABYLON.Action);
  25700. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25701. })(BABYLON || (BABYLON = {}));
  25702. var BABYLON;
  25703. (function (BABYLON) {
  25704. var SwitchBooleanAction = (function (_super) {
  25705. __extends(SwitchBooleanAction, _super);
  25706. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25707. _super.call(this, triggerOptions, condition);
  25708. this.propertyPath = propertyPath;
  25709. this._target = target;
  25710. }
  25711. SwitchBooleanAction.prototype._prepare = function () {
  25712. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25713. this._property = this._getProperty(this.propertyPath);
  25714. };
  25715. SwitchBooleanAction.prototype.execute = function () {
  25716. this._target[this._property] = !this._target[this._property];
  25717. };
  25718. return SwitchBooleanAction;
  25719. })(BABYLON.Action);
  25720. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25721. var SetStateAction = (function (_super) {
  25722. __extends(SetStateAction, _super);
  25723. function SetStateAction(triggerOptions, target, value, condition) {
  25724. _super.call(this, triggerOptions, condition);
  25725. this.value = value;
  25726. this._target = target;
  25727. }
  25728. SetStateAction.prototype.execute = function () {
  25729. this._target.state = this.value;
  25730. };
  25731. return SetStateAction;
  25732. })(BABYLON.Action);
  25733. BABYLON.SetStateAction = SetStateAction;
  25734. var SetValueAction = (function (_super) {
  25735. __extends(SetValueAction, _super);
  25736. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25737. _super.call(this, triggerOptions, condition);
  25738. this.propertyPath = propertyPath;
  25739. this.value = value;
  25740. this._target = target;
  25741. }
  25742. SetValueAction.prototype._prepare = function () {
  25743. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25744. this._property = this._getProperty(this.propertyPath);
  25745. };
  25746. SetValueAction.prototype.execute = function () {
  25747. this._target[this._property] = this.value;
  25748. };
  25749. return SetValueAction;
  25750. })(BABYLON.Action);
  25751. BABYLON.SetValueAction = SetValueAction;
  25752. var IncrementValueAction = (function (_super) {
  25753. __extends(IncrementValueAction, _super);
  25754. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25755. _super.call(this, triggerOptions, condition);
  25756. this.propertyPath = propertyPath;
  25757. this.value = value;
  25758. this._target = target;
  25759. }
  25760. IncrementValueAction.prototype._prepare = function () {
  25761. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25762. this._property = this._getProperty(this.propertyPath);
  25763. if (typeof this._target[this._property] !== "number") {
  25764. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25765. }
  25766. };
  25767. IncrementValueAction.prototype.execute = function () {
  25768. this._target[this._property] += this.value;
  25769. };
  25770. return IncrementValueAction;
  25771. })(BABYLON.Action);
  25772. BABYLON.IncrementValueAction = IncrementValueAction;
  25773. var PlayAnimationAction = (function (_super) {
  25774. __extends(PlayAnimationAction, _super);
  25775. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25776. _super.call(this, triggerOptions, condition);
  25777. this.from = from;
  25778. this.to = to;
  25779. this.loop = loop;
  25780. this._target = target;
  25781. }
  25782. PlayAnimationAction.prototype._prepare = function () {
  25783. };
  25784. PlayAnimationAction.prototype.execute = function () {
  25785. var scene = this._actionManager.getScene();
  25786. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25787. };
  25788. return PlayAnimationAction;
  25789. })(BABYLON.Action);
  25790. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25791. var StopAnimationAction = (function (_super) {
  25792. __extends(StopAnimationAction, _super);
  25793. function StopAnimationAction(triggerOptions, target, condition) {
  25794. _super.call(this, triggerOptions, condition);
  25795. this._target = target;
  25796. }
  25797. StopAnimationAction.prototype._prepare = function () {
  25798. };
  25799. StopAnimationAction.prototype.execute = function () {
  25800. var scene = this._actionManager.getScene();
  25801. scene.stopAnimation(this._target);
  25802. };
  25803. return StopAnimationAction;
  25804. })(BABYLON.Action);
  25805. BABYLON.StopAnimationAction = StopAnimationAction;
  25806. var DoNothingAction = (function (_super) {
  25807. __extends(DoNothingAction, _super);
  25808. function DoNothingAction(triggerOptions, condition) {
  25809. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25810. _super.call(this, triggerOptions, condition);
  25811. }
  25812. DoNothingAction.prototype.execute = function () {
  25813. };
  25814. return DoNothingAction;
  25815. })(BABYLON.Action);
  25816. BABYLON.DoNothingAction = DoNothingAction;
  25817. var CombineAction = (function (_super) {
  25818. __extends(CombineAction, _super);
  25819. function CombineAction(triggerOptions, children, condition) {
  25820. _super.call(this, triggerOptions, condition);
  25821. this.children = children;
  25822. }
  25823. CombineAction.prototype._prepare = function () {
  25824. for (var index = 0; index < this.children.length; index++) {
  25825. this.children[index]._actionManager = this._actionManager;
  25826. this.children[index]._prepare();
  25827. }
  25828. };
  25829. CombineAction.prototype.execute = function (evt) {
  25830. for (var index = 0; index < this.children.length; index++) {
  25831. this.children[index].execute(evt);
  25832. }
  25833. };
  25834. return CombineAction;
  25835. })(BABYLON.Action);
  25836. BABYLON.CombineAction = CombineAction;
  25837. var ExecuteCodeAction = (function (_super) {
  25838. __extends(ExecuteCodeAction, _super);
  25839. function ExecuteCodeAction(triggerOptions, func, condition) {
  25840. _super.call(this, triggerOptions, condition);
  25841. this.func = func;
  25842. }
  25843. ExecuteCodeAction.prototype.execute = function (evt) {
  25844. this.func(evt);
  25845. };
  25846. return ExecuteCodeAction;
  25847. })(BABYLON.Action);
  25848. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25849. var SetParentAction = (function (_super) {
  25850. __extends(SetParentAction, _super);
  25851. function SetParentAction(triggerOptions, target, parent, condition) {
  25852. _super.call(this, triggerOptions, condition);
  25853. this._target = target;
  25854. this._parent = parent;
  25855. }
  25856. SetParentAction.prototype._prepare = function () {
  25857. };
  25858. SetParentAction.prototype.execute = function () {
  25859. if (this._target.parent === this._parent) {
  25860. return;
  25861. }
  25862. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25863. invertParentWorldMatrix.invert();
  25864. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25865. this._target.parent = this._parent;
  25866. };
  25867. return SetParentAction;
  25868. })(BABYLON.Action);
  25869. BABYLON.SetParentAction = SetParentAction;
  25870. var PlaySoundAction = (function (_super) {
  25871. __extends(PlaySoundAction, _super);
  25872. function PlaySoundAction(triggerOptions, sound, condition) {
  25873. _super.call(this, triggerOptions, condition);
  25874. this._sound = sound;
  25875. }
  25876. PlaySoundAction.prototype._prepare = function () {
  25877. };
  25878. PlaySoundAction.prototype.execute = function () {
  25879. if (this._sound !== undefined)
  25880. this._sound.play();
  25881. };
  25882. return PlaySoundAction;
  25883. })(BABYLON.Action);
  25884. BABYLON.PlaySoundAction = PlaySoundAction;
  25885. var StopSoundAction = (function (_super) {
  25886. __extends(StopSoundAction, _super);
  25887. function StopSoundAction(triggerOptions, sound, condition) {
  25888. _super.call(this, triggerOptions, condition);
  25889. this._sound = sound;
  25890. }
  25891. StopSoundAction.prototype._prepare = function () {
  25892. };
  25893. StopSoundAction.prototype.execute = function () {
  25894. if (this._sound !== undefined)
  25895. this._sound.stop();
  25896. };
  25897. return StopSoundAction;
  25898. })(BABYLON.Action);
  25899. BABYLON.StopSoundAction = StopSoundAction;
  25900. })(BABYLON || (BABYLON = {}));
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. var Geometry = (function () {
  25904. function Geometry(id, scene, vertexData, updatable, mesh) {
  25905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25906. this._totalVertices = 0;
  25907. this._isDisposed = false;
  25908. this.id = id;
  25909. this._engine = scene.getEngine();
  25910. this._meshes = [];
  25911. this._scene = scene;
  25912. //Init vertex buffer cache
  25913. this._vertexBuffers = {};
  25914. this._indices = [];
  25915. // vertexData
  25916. if (vertexData) {
  25917. this.setAllVerticesData(vertexData, updatable);
  25918. }
  25919. else {
  25920. this._totalVertices = 0;
  25921. this._indices = [];
  25922. }
  25923. // applyToMesh
  25924. if (mesh) {
  25925. this.applyToMesh(mesh);
  25926. mesh.computeWorldMatrix(true);
  25927. }
  25928. }
  25929. Object.defineProperty(Geometry.prototype, "extend", {
  25930. get: function () {
  25931. return this._extend;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Geometry.prototype.getScene = function () {
  25937. return this._scene;
  25938. };
  25939. Geometry.prototype.getEngine = function () {
  25940. return this._engine;
  25941. };
  25942. Geometry.prototype.isReady = function () {
  25943. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25944. };
  25945. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25946. vertexData.applyToGeometry(this, updatable);
  25947. this.notifyUpdate();
  25948. };
  25949. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25950. if (this._vertexBuffers[kind]) {
  25951. this._vertexBuffers[kind].dispose();
  25952. }
  25953. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25954. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25955. stride = this._vertexBuffers[kind].getStrideSize();
  25956. this._totalVertices = data.length / stride;
  25957. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25958. var meshes = this._meshes;
  25959. var numOfMeshes = meshes.length;
  25960. for (var index = 0; index < numOfMeshes; index++) {
  25961. var mesh = meshes[index];
  25962. mesh._resetPointsArrayCache();
  25963. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25964. mesh._createGlobalSubMesh();
  25965. mesh.computeWorldMatrix(true);
  25966. }
  25967. }
  25968. this.notifyUpdate(kind);
  25969. };
  25970. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25971. var vertexBuffer = this.getVertexBuffer(kind);
  25972. if (!vertexBuffer) {
  25973. return;
  25974. }
  25975. vertexBuffer.updateDirectly(data, offset);
  25976. this.notifyUpdate(kind);
  25977. };
  25978. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25979. var vertexBuffer = this.getVertexBuffer(kind);
  25980. if (!vertexBuffer) {
  25981. return;
  25982. }
  25983. vertexBuffer.update(data);
  25984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25985. var stride = vertexBuffer.getStrideSize();
  25986. this._totalVertices = data.length / stride;
  25987. if (updateExtends) {
  25988. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25989. }
  25990. var meshes = this._meshes;
  25991. var numOfMeshes = meshes.length;
  25992. for (var index = 0; index < numOfMeshes; index++) {
  25993. var mesh = meshes[index];
  25994. mesh._resetPointsArrayCache();
  25995. if (updateExtends) {
  25996. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25997. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25998. var subMesh = mesh.subMeshes[subIndex];
  25999. subMesh.refreshBoundingInfo();
  26000. }
  26001. }
  26002. }
  26003. }
  26004. this.notifyUpdate(kind);
  26005. };
  26006. Geometry.prototype.getTotalVertices = function () {
  26007. if (!this.isReady()) {
  26008. return 0;
  26009. }
  26010. return this._totalVertices;
  26011. };
  26012. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26013. var vertexBuffer = this.getVertexBuffer(kind);
  26014. if (!vertexBuffer) {
  26015. return null;
  26016. }
  26017. var orig = vertexBuffer.getData();
  26018. if (!copyWhenShared || this._meshes.length === 1) {
  26019. return orig;
  26020. }
  26021. else {
  26022. var len = orig.length;
  26023. var copy = [];
  26024. for (var i = 0; i < len; i++) {
  26025. copy.push(orig[i]);
  26026. }
  26027. return copy;
  26028. }
  26029. };
  26030. Geometry.prototype.getVertexBuffer = function (kind) {
  26031. if (!this.isReady()) {
  26032. return null;
  26033. }
  26034. return this._vertexBuffers[kind];
  26035. };
  26036. Geometry.prototype.getVertexBuffers = function () {
  26037. if (!this.isReady()) {
  26038. return null;
  26039. }
  26040. return this._vertexBuffers;
  26041. };
  26042. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26043. if (!this._vertexBuffers) {
  26044. if (this._delayInfo) {
  26045. return this._delayInfo.indexOf(kind) !== -1;
  26046. }
  26047. return false;
  26048. }
  26049. return this._vertexBuffers[kind] !== undefined;
  26050. };
  26051. Geometry.prototype.getVerticesDataKinds = function () {
  26052. var result = [];
  26053. var kind;
  26054. if (!this._vertexBuffers && this._delayInfo) {
  26055. for (kind in this._delayInfo) {
  26056. result.push(kind);
  26057. }
  26058. }
  26059. else {
  26060. for (kind in this._vertexBuffers) {
  26061. result.push(kind);
  26062. }
  26063. }
  26064. return result;
  26065. };
  26066. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26067. if (this._indexBuffer) {
  26068. this._engine._releaseBuffer(this._indexBuffer);
  26069. }
  26070. this._indices = indices;
  26071. if (this._meshes.length !== 0 && this._indices) {
  26072. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26073. }
  26074. if (totalVertices !== undefined) {
  26075. this._totalVertices = totalVertices;
  26076. }
  26077. var meshes = this._meshes;
  26078. var numOfMeshes = meshes.length;
  26079. for (var index = 0; index < numOfMeshes; index++) {
  26080. meshes[index]._createGlobalSubMesh();
  26081. }
  26082. this.notifyUpdate();
  26083. };
  26084. Geometry.prototype.getTotalIndices = function () {
  26085. if (!this.isReady()) {
  26086. return 0;
  26087. }
  26088. return this._indices.length;
  26089. };
  26090. Geometry.prototype.getIndices = function (copyWhenShared) {
  26091. if (!this.isReady()) {
  26092. return null;
  26093. }
  26094. var orig = this._indices;
  26095. if (!copyWhenShared || this._meshes.length === 1) {
  26096. return orig;
  26097. }
  26098. else {
  26099. var len = orig.length;
  26100. var copy = [];
  26101. for (var i = 0; i < len; i++) {
  26102. copy.push(orig[i]);
  26103. }
  26104. return copy;
  26105. }
  26106. };
  26107. Geometry.prototype.getIndexBuffer = function () {
  26108. if (!this.isReady()) {
  26109. return null;
  26110. }
  26111. return this._indexBuffer;
  26112. };
  26113. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26114. var meshes = this._meshes;
  26115. var index = meshes.indexOf(mesh);
  26116. if (index === -1) {
  26117. return;
  26118. }
  26119. for (var kind in this._vertexBuffers) {
  26120. this._vertexBuffers[kind].dispose();
  26121. }
  26122. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26123. this._indexBuffer = null;
  26124. }
  26125. meshes.splice(index, 1);
  26126. mesh._geometry = null;
  26127. if (meshes.length === 0 && shouldDispose) {
  26128. this.dispose();
  26129. }
  26130. };
  26131. Geometry.prototype.applyToMesh = function (mesh) {
  26132. if (mesh._geometry === this) {
  26133. return;
  26134. }
  26135. var previousGeometry = mesh._geometry;
  26136. if (previousGeometry) {
  26137. previousGeometry.releaseForMesh(mesh);
  26138. }
  26139. var meshes = this._meshes;
  26140. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26141. mesh._geometry = this;
  26142. this._scene.pushGeometry(this);
  26143. meshes.push(mesh);
  26144. if (this.isReady()) {
  26145. this._applyToMesh(mesh);
  26146. }
  26147. else {
  26148. mesh._boundingInfo = this._boundingInfo;
  26149. }
  26150. };
  26151. Geometry.prototype._applyToMesh = function (mesh) {
  26152. var numOfMeshes = this._meshes.length;
  26153. // vertexBuffers
  26154. for (var kind in this._vertexBuffers) {
  26155. if (numOfMeshes === 1) {
  26156. this._vertexBuffers[kind].create();
  26157. }
  26158. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26159. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26160. mesh._resetPointsArrayCache();
  26161. if (!this._extend) {
  26162. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26163. }
  26164. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26165. mesh._createGlobalSubMesh();
  26166. //bounding info was just created again, world matrix should be applied again.
  26167. mesh._updateBoundingInfo();
  26168. }
  26169. }
  26170. // indexBuffer
  26171. if (numOfMeshes === 1 && this._indices) {
  26172. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26173. }
  26174. if (this._indexBuffer) {
  26175. this._indexBuffer.references = numOfMeshes;
  26176. }
  26177. };
  26178. Geometry.prototype.notifyUpdate = function (kind) {
  26179. if (this.onGeometryUpdated) {
  26180. this.onGeometryUpdated(this, kind);
  26181. }
  26182. };
  26183. Geometry.prototype.load = function (scene, onLoaded) {
  26184. var _this = this;
  26185. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26186. return;
  26187. }
  26188. if (this.isReady()) {
  26189. if (onLoaded) {
  26190. onLoaded();
  26191. }
  26192. return;
  26193. }
  26194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26195. scene._addPendingData(this);
  26196. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26197. _this._delayLoadingFunction(JSON.parse(data), _this);
  26198. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26199. _this._delayInfo = [];
  26200. scene._removePendingData(_this);
  26201. var meshes = _this._meshes;
  26202. var numOfMeshes = meshes.length;
  26203. for (var index = 0; index < numOfMeshes; index++) {
  26204. _this._applyToMesh(meshes[index]);
  26205. }
  26206. if (onLoaded) {
  26207. onLoaded();
  26208. }
  26209. }, function () { }, scene.database);
  26210. };
  26211. Geometry.prototype.isDisposed = function () {
  26212. return this._isDisposed;
  26213. };
  26214. Geometry.prototype.dispose = function () {
  26215. var meshes = this._meshes;
  26216. var numOfMeshes = meshes.length;
  26217. var index;
  26218. for (index = 0; index < numOfMeshes; index++) {
  26219. this.releaseForMesh(meshes[index]);
  26220. }
  26221. this._meshes = [];
  26222. for (var kind in this._vertexBuffers) {
  26223. this._vertexBuffers[kind].dispose();
  26224. }
  26225. this._vertexBuffers = [];
  26226. this._totalVertices = 0;
  26227. if (this._indexBuffer) {
  26228. this._engine._releaseBuffer(this._indexBuffer);
  26229. }
  26230. this._indexBuffer = null;
  26231. this._indices = [];
  26232. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26233. this.delayLoadingFile = null;
  26234. this._delayLoadingFunction = null;
  26235. this._delayInfo = [];
  26236. this._boundingInfo = null;
  26237. this._scene.removeGeometry(this);
  26238. this._isDisposed = true;
  26239. };
  26240. Geometry.prototype.copy = function (id) {
  26241. var vertexData = new BABYLON.VertexData();
  26242. vertexData.indices = [];
  26243. var indices = this.getIndices();
  26244. for (var index = 0; index < indices.length; index++) {
  26245. vertexData.indices.push(indices[index]);
  26246. }
  26247. var updatable = false;
  26248. var stopChecking = false;
  26249. var kind;
  26250. for (kind in this._vertexBuffers) {
  26251. // using slice() to make a copy of the array and not just reference it
  26252. var data = this.getVerticesData(kind);
  26253. if (data instanceof Float32Array) {
  26254. vertexData.set(new Float32Array(data), kind);
  26255. }
  26256. else {
  26257. vertexData.set(data.slice(0), kind);
  26258. }
  26259. if (!stopChecking) {
  26260. updatable = this.getVertexBuffer(kind).isUpdatable();
  26261. stopChecking = !updatable;
  26262. }
  26263. }
  26264. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26265. geometry.delayLoadState = this.delayLoadState;
  26266. geometry.delayLoadingFile = this.delayLoadingFile;
  26267. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26268. for (kind in this._delayInfo) {
  26269. geometry._delayInfo = geometry._delayInfo || [];
  26270. geometry._delayInfo.push(kind);
  26271. }
  26272. // Bounding info
  26273. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26274. return geometry;
  26275. };
  26276. Geometry.prototype.serialize = function () {
  26277. var serializationObject = {};
  26278. serializationObject.id = this.id;
  26279. if (BABYLON.Tags.HasTags(this)) {
  26280. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26281. }
  26282. return serializationObject;
  26283. };
  26284. Geometry.prototype.serializeVerticeData = function () {
  26285. var serializationObject = this.serialize();
  26286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26287. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26288. }
  26289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26290. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26291. }
  26292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26293. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26294. }
  26295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26296. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26297. }
  26298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26299. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26300. }
  26301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26302. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26303. }
  26304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26305. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26306. }
  26307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26308. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26309. }
  26310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26311. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26312. }
  26313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26314. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26315. serializationObject.matricesIndices._isExpanded = true;
  26316. }
  26317. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26318. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26319. }
  26320. serializationObject.indices = this.getIndices();
  26321. return serializationObject;
  26322. };
  26323. // Statics
  26324. Geometry.ExtractFromMesh = function (mesh, id) {
  26325. var geometry = mesh._geometry;
  26326. if (!geometry) {
  26327. return null;
  26328. }
  26329. return geometry.copy(id);
  26330. };
  26331. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26332. // be aware Math.random() could cause collisions
  26333. Geometry.RandomId = function () {
  26334. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26335. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26336. return v.toString(16);
  26337. });
  26338. };
  26339. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26340. var scene = mesh.getScene();
  26341. // Geometry
  26342. var geometryId = parsedGeometry.geometryId;
  26343. if (geometryId) {
  26344. var geometry = scene.getGeometryByID(geometryId);
  26345. if (geometry) {
  26346. geometry.applyToMesh(mesh);
  26347. }
  26348. }
  26349. else if (parsedGeometry instanceof ArrayBuffer) {
  26350. var binaryInfo = mesh._binaryInfo;
  26351. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26352. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26353. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26354. }
  26355. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26356. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26357. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26358. }
  26359. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26360. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26361. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26362. }
  26363. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26364. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26365. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26366. }
  26367. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26368. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26369. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26370. }
  26371. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26372. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26373. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26374. }
  26375. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26376. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26377. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26378. }
  26379. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26380. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26381. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26382. }
  26383. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26384. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26385. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26386. }
  26387. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26388. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26389. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26390. }
  26391. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26392. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26393. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26394. }
  26395. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26396. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26397. mesh.setIndices(indicesData);
  26398. }
  26399. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26400. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26401. mesh.subMeshes = [];
  26402. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26403. var materialIndex = subMeshesData[(i * 5) + 0];
  26404. var verticesStart = subMeshesData[(i * 5) + 1];
  26405. var verticesCount = subMeshesData[(i * 5) + 2];
  26406. var indexStart = subMeshesData[(i * 5) + 3];
  26407. var indexCount = subMeshesData[(i * 5) + 4];
  26408. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26409. }
  26410. }
  26411. }
  26412. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26413. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26414. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26415. if (parsedGeometry.uvs) {
  26416. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26417. }
  26418. if (parsedGeometry.uvs2) {
  26419. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26420. }
  26421. if (parsedGeometry.uvs3) {
  26422. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26423. }
  26424. if (parsedGeometry.uvs4) {
  26425. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26426. }
  26427. if (parsedGeometry.uvs5) {
  26428. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26429. }
  26430. if (parsedGeometry.uvs6) {
  26431. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26432. }
  26433. if (parsedGeometry.colors) {
  26434. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26435. }
  26436. if (parsedGeometry.matricesIndices) {
  26437. if (!parsedGeometry.matricesIndices._isExpanded) {
  26438. var floatIndices = [];
  26439. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26440. var matricesIndex = parsedGeometry.matricesIndices[i];
  26441. floatIndices.push(matricesIndex & 0x000000FF);
  26442. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26443. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26444. floatIndices.push(matricesIndex >> 24);
  26445. }
  26446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26447. }
  26448. else {
  26449. delete parsedGeometry.matricesIndices._isExpanded;
  26450. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26451. }
  26452. }
  26453. if (parsedGeometry.matricesIndicesExtra) {
  26454. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26455. var floatIndices = [];
  26456. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26457. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26458. floatIndices.push(matricesIndex & 0x000000FF);
  26459. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26460. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26461. floatIndices.push(matricesIndex >> 24);
  26462. }
  26463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26464. }
  26465. else {
  26466. delete parsedGeometry.matricesIndices._isExpanded;
  26467. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26468. }
  26469. }
  26470. if (parsedGeometry.matricesWeights) {
  26471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26472. }
  26473. if (parsedGeometry.matricesWeightsExtra) {
  26474. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26475. }
  26476. mesh.setIndices(parsedGeometry.indices);
  26477. }
  26478. // SubMeshes
  26479. if (parsedGeometry.subMeshes) {
  26480. mesh.subMeshes = [];
  26481. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26482. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26483. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26484. }
  26485. }
  26486. // Flat shading
  26487. if (mesh._shouldGenerateFlatShading) {
  26488. mesh.convertToFlatShadedMesh();
  26489. delete mesh._shouldGenerateFlatShading;
  26490. }
  26491. // Update
  26492. mesh.computeWorldMatrix(true);
  26493. // Octree
  26494. if (scene['_selectionOctree']) {
  26495. scene['_selectionOctree'].addMesh(mesh);
  26496. }
  26497. };
  26498. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26499. if (scene.getGeometryByID(parsedVertexData.id)) {
  26500. return null; // null since geometry could be something else than a box...
  26501. }
  26502. var geometry = new Geometry(parsedVertexData.id, scene);
  26503. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26504. if (parsedVertexData.delayLoadingFile) {
  26505. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26506. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26507. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26508. geometry._delayInfo = [];
  26509. if (parsedVertexData.hasUVs) {
  26510. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26511. }
  26512. if (parsedVertexData.hasUVs2) {
  26513. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26514. }
  26515. if (parsedVertexData.hasUVs3) {
  26516. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26517. }
  26518. if (parsedVertexData.hasUVs4) {
  26519. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26520. }
  26521. if (parsedVertexData.hasUVs5) {
  26522. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26523. }
  26524. if (parsedVertexData.hasUVs6) {
  26525. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26526. }
  26527. if (parsedVertexData.hasColors) {
  26528. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26529. }
  26530. if (parsedVertexData.hasMatricesIndices) {
  26531. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26532. }
  26533. if (parsedVertexData.hasMatricesWeights) {
  26534. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26535. }
  26536. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26537. }
  26538. else {
  26539. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26540. }
  26541. scene.pushGeometry(geometry, true);
  26542. return geometry;
  26543. };
  26544. return Geometry;
  26545. })();
  26546. BABYLON.Geometry = Geometry;
  26547. /////// Primitives //////////////////////////////////////////////
  26548. var Geometry;
  26549. (function (Geometry) {
  26550. var Primitives;
  26551. (function (Primitives) {
  26552. /// Abstract class
  26553. var _Primitive = (function (_super) {
  26554. __extends(_Primitive, _super);
  26555. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26556. this._beingRegenerated = true;
  26557. this._canBeRegenerated = canBeRegenerated;
  26558. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26559. this._beingRegenerated = false;
  26560. }
  26561. _Primitive.prototype.canBeRegenerated = function () {
  26562. return this._canBeRegenerated;
  26563. };
  26564. _Primitive.prototype.regenerate = function () {
  26565. if (!this._canBeRegenerated) {
  26566. return;
  26567. }
  26568. this._beingRegenerated = true;
  26569. this.setAllVerticesData(this._regenerateVertexData(), false);
  26570. this._beingRegenerated = false;
  26571. };
  26572. _Primitive.prototype.asNewGeometry = function (id) {
  26573. return _super.prototype.copy.call(this, id);
  26574. };
  26575. // overrides
  26576. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26577. if (!this._beingRegenerated) {
  26578. return;
  26579. }
  26580. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26581. };
  26582. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26583. if (!this._beingRegenerated) {
  26584. return;
  26585. }
  26586. _super.prototype.setVerticesData.call(this, kind, data, false);
  26587. };
  26588. // to override
  26589. // protected
  26590. _Primitive.prototype._regenerateVertexData = function () {
  26591. throw new Error("Abstract method");
  26592. };
  26593. _Primitive.prototype.copy = function (id) {
  26594. throw new Error("Must be overriden in sub-classes.");
  26595. };
  26596. _Primitive.prototype.serialize = function () {
  26597. var serializationObject = _super.prototype.serialize.call(this);
  26598. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26599. return serializationObject;
  26600. };
  26601. return _Primitive;
  26602. })(Geometry);
  26603. Primitives._Primitive = _Primitive;
  26604. var Ribbon = (function (_super) {
  26605. __extends(Ribbon, _super);
  26606. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26607. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26608. this.pathArray = pathArray;
  26609. this.closeArray = closeArray;
  26610. this.closePath = closePath;
  26611. this.offset = offset;
  26612. this.side = side;
  26613. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26614. }
  26615. Ribbon.prototype._regenerateVertexData = function () {
  26616. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26617. };
  26618. Ribbon.prototype.copy = function (id) {
  26619. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26620. };
  26621. return Ribbon;
  26622. })(_Primitive);
  26623. Primitives.Ribbon = Ribbon;
  26624. var Box = (function (_super) {
  26625. __extends(Box, _super);
  26626. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26627. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26628. this.size = size;
  26629. this.side = side;
  26630. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26631. }
  26632. Box.prototype._regenerateVertexData = function () {
  26633. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26634. };
  26635. Box.prototype.copy = function (id) {
  26636. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26637. };
  26638. Box.prototype.serialize = function () {
  26639. var serializationObject = _super.prototype.serialize.call(this);
  26640. serializationObject.size = this.size;
  26641. return serializationObject;
  26642. };
  26643. Box.Parse = function (parsedBox, scene) {
  26644. if (scene.getGeometryByID(parsedBox.id)) {
  26645. return null; // null since geometry could be something else than a box...
  26646. }
  26647. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26648. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26649. scene.pushGeometry(box, true);
  26650. return box;
  26651. };
  26652. return Box;
  26653. })(_Primitive);
  26654. Primitives.Box = Box;
  26655. var Sphere = (function (_super) {
  26656. __extends(Sphere, _super);
  26657. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26658. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26659. this.segments = segments;
  26660. this.diameter = diameter;
  26661. this.side = side;
  26662. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26663. }
  26664. Sphere.prototype._regenerateVertexData = function () {
  26665. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26666. };
  26667. Sphere.prototype.copy = function (id) {
  26668. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26669. };
  26670. Sphere.prototype.serialize = function () {
  26671. var serializationObject = _super.prototype.serialize.call(this);
  26672. serializationObject.segments = this.segments;
  26673. serializationObject.diameter = this.diameter;
  26674. return serializationObject;
  26675. };
  26676. Sphere.Parse = function (parsedSphere, scene) {
  26677. if (scene.getGeometryByID(parsedSphere.id)) {
  26678. return null; // null since geometry could be something else than a sphere...
  26679. }
  26680. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26681. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26682. scene.pushGeometry(sphere, true);
  26683. return sphere;
  26684. };
  26685. return Sphere;
  26686. })(_Primitive);
  26687. Primitives.Sphere = Sphere;
  26688. var Disc = (function (_super) {
  26689. __extends(Disc, _super);
  26690. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26692. this.radius = radius;
  26693. this.tessellation = tessellation;
  26694. this.side = side;
  26695. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26696. }
  26697. Disc.prototype._regenerateVertexData = function () {
  26698. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26699. };
  26700. Disc.prototype.copy = function (id) {
  26701. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26702. };
  26703. return Disc;
  26704. })(_Primitive);
  26705. Primitives.Disc = Disc;
  26706. var Cylinder = (function (_super) {
  26707. __extends(Cylinder, _super);
  26708. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26709. if (subdivisions === void 0) { subdivisions = 1; }
  26710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26711. this.height = height;
  26712. this.diameterTop = diameterTop;
  26713. this.diameterBottom = diameterBottom;
  26714. this.tessellation = tessellation;
  26715. this.subdivisions = subdivisions;
  26716. this.side = side;
  26717. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26718. }
  26719. Cylinder.prototype._regenerateVertexData = function () {
  26720. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26721. };
  26722. Cylinder.prototype.copy = function (id) {
  26723. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26724. };
  26725. Cylinder.prototype.serialize = function () {
  26726. var serializationObject = _super.prototype.serialize.call(this);
  26727. serializationObject.height = this.height;
  26728. serializationObject.diameterTop = this.diameterTop;
  26729. serializationObject.diameterBottom = this.diameterBottom;
  26730. serializationObject.tessellation = this.tessellation;
  26731. return serializationObject;
  26732. };
  26733. Cylinder.Parse = function (parsedCylinder, scene) {
  26734. if (scene.getGeometryByID(parsedCylinder.id)) {
  26735. return null; // null since geometry could be something else than a cylinder...
  26736. }
  26737. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26738. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26739. scene.pushGeometry(cylinder, true);
  26740. return cylinder;
  26741. };
  26742. return Cylinder;
  26743. })(_Primitive);
  26744. Primitives.Cylinder = Cylinder;
  26745. var Torus = (function (_super) {
  26746. __extends(Torus, _super);
  26747. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26748. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26749. this.diameter = diameter;
  26750. this.thickness = thickness;
  26751. this.tessellation = tessellation;
  26752. this.side = side;
  26753. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26754. }
  26755. Torus.prototype._regenerateVertexData = function () {
  26756. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26757. };
  26758. Torus.prototype.copy = function (id) {
  26759. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26760. };
  26761. Torus.prototype.serialize = function () {
  26762. var serializationObject = _super.prototype.serialize.call(this);
  26763. serializationObject.diameter = this.diameter;
  26764. serializationObject.thickness = this.thickness;
  26765. serializationObject.tessellation = this.tessellation;
  26766. return serializationObject;
  26767. };
  26768. Torus.Parse = function (parsedTorus, scene) {
  26769. if (scene.getGeometryByID(parsedTorus.id)) {
  26770. return null; // null since geometry could be something else than a torus...
  26771. }
  26772. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26773. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26774. scene.pushGeometry(torus, true);
  26775. return torus;
  26776. };
  26777. return Torus;
  26778. })(_Primitive);
  26779. Primitives.Torus = Torus;
  26780. var Ground = (function (_super) {
  26781. __extends(Ground, _super);
  26782. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26783. this.width = width;
  26784. this.height = height;
  26785. this.subdivisions = subdivisions;
  26786. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26787. }
  26788. Ground.prototype._regenerateVertexData = function () {
  26789. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26790. };
  26791. Ground.prototype.copy = function (id) {
  26792. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26793. };
  26794. Ground.prototype.serialize = function () {
  26795. var serializationObject = _super.prototype.serialize.call(this);
  26796. serializationObject.width = this.width;
  26797. serializationObject.height = this.height;
  26798. serializationObject.subdivisions = this.subdivisions;
  26799. return serializationObject;
  26800. };
  26801. Ground.Parse = function (parsedGround, scene) {
  26802. if (scene.getGeometryByID(parsedGround.id)) {
  26803. return null; // null since geometry could be something else than a ground...
  26804. }
  26805. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26806. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26807. scene.pushGeometry(ground, true);
  26808. return ground;
  26809. };
  26810. return Ground;
  26811. })(_Primitive);
  26812. Primitives.Ground = Ground;
  26813. var TiledGround = (function (_super) {
  26814. __extends(TiledGround, _super);
  26815. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26816. this.xmin = xmin;
  26817. this.zmin = zmin;
  26818. this.xmax = xmax;
  26819. this.zmax = zmax;
  26820. this.subdivisions = subdivisions;
  26821. this.precision = precision;
  26822. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26823. }
  26824. TiledGround.prototype._regenerateVertexData = function () {
  26825. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26826. };
  26827. TiledGround.prototype.copy = function (id) {
  26828. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26829. };
  26830. return TiledGround;
  26831. })(_Primitive);
  26832. Primitives.TiledGround = TiledGround;
  26833. var Plane = (function (_super) {
  26834. __extends(Plane, _super);
  26835. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26837. this.size = size;
  26838. this.side = side;
  26839. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26840. }
  26841. Plane.prototype._regenerateVertexData = function () {
  26842. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26843. };
  26844. Plane.prototype.copy = function (id) {
  26845. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26846. };
  26847. Plane.prototype.serialize = function () {
  26848. var serializationObject = _super.prototype.serialize.call(this);
  26849. serializationObject.size = this.size;
  26850. return serializationObject;
  26851. };
  26852. Plane.Parse = function (parsedPlane, scene) {
  26853. if (scene.getGeometryByID(parsedPlane.id)) {
  26854. return null; // null since geometry could be something else than a ground...
  26855. }
  26856. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26857. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26858. scene.pushGeometry(plane, true);
  26859. return plane;
  26860. };
  26861. return Plane;
  26862. })(_Primitive);
  26863. Primitives.Plane = Plane;
  26864. var TorusKnot = (function (_super) {
  26865. __extends(TorusKnot, _super);
  26866. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26868. this.radius = radius;
  26869. this.tube = tube;
  26870. this.radialSegments = radialSegments;
  26871. this.tubularSegments = tubularSegments;
  26872. this.p = p;
  26873. this.q = q;
  26874. this.side = side;
  26875. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26876. }
  26877. TorusKnot.prototype._regenerateVertexData = function () {
  26878. 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 });
  26879. };
  26880. TorusKnot.prototype.copy = function (id) {
  26881. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26882. };
  26883. TorusKnot.prototype.serialize = function () {
  26884. var serializationObject = _super.prototype.serialize.call(this);
  26885. serializationObject.radius = this.radius;
  26886. serializationObject.tube = this.tube;
  26887. serializationObject.radialSegments = this.radialSegments;
  26888. serializationObject.tubularSegments = this.tubularSegments;
  26889. serializationObject.p = this.p;
  26890. serializationObject.q = this.q;
  26891. return serializationObject;
  26892. };
  26893. ;
  26894. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26895. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26896. return null; // null since geometry could be something else than a ground...
  26897. }
  26898. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26899. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26900. scene.pushGeometry(torusKnot, true);
  26901. return torusKnot;
  26902. };
  26903. return TorusKnot;
  26904. })(_Primitive);
  26905. Primitives.TorusKnot = TorusKnot;
  26906. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26907. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26908. })(BABYLON || (BABYLON = {}));
  26909. var BABYLON;
  26910. (function (BABYLON) {
  26911. var GroundMesh = (function (_super) {
  26912. __extends(GroundMesh, _super);
  26913. function GroundMesh(name, scene) {
  26914. _super.call(this, name, scene);
  26915. this.generateOctree = false;
  26916. this._worldInverse = new BABYLON.Matrix();
  26917. }
  26918. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26919. get: function () {
  26920. return this._subdivisions;
  26921. },
  26922. enumerable: true,
  26923. configurable: true
  26924. });
  26925. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26926. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26927. this._subdivisions = chunksCount;
  26928. this.subdivide(this._subdivisions);
  26929. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26930. };
  26931. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26932. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26933. this.getWorldMatrix().invertToRef(this._worldInverse);
  26934. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26935. var pickInfo = this.intersects(ray);
  26936. if (pickInfo.hit) {
  26937. return pickInfo.pickedPoint.y;
  26938. }
  26939. return 0;
  26940. };
  26941. return GroundMesh;
  26942. })(BABYLON.Mesh);
  26943. BABYLON.GroundMesh = GroundMesh;
  26944. })(BABYLON || (BABYLON = {}));
  26945. var BABYLON;
  26946. (function (BABYLON) {
  26947. var LinesMesh = (function (_super) {
  26948. __extends(LinesMesh, _super);
  26949. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26950. if (parent === void 0) { parent = null; }
  26951. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26952. this.color = new BABYLON.Color3(1, 1, 1);
  26953. this.alpha = 1;
  26954. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26955. attributes: ["position"],
  26956. uniforms: ["worldViewProjection", "color"],
  26957. needAlphaBlending: true
  26958. });
  26959. }
  26960. Object.defineProperty(LinesMesh.prototype, "material", {
  26961. get: function () {
  26962. return this._colorShader;
  26963. },
  26964. enumerable: true,
  26965. configurable: true
  26966. });
  26967. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26968. get: function () {
  26969. return false;
  26970. },
  26971. enumerable: true,
  26972. configurable: true
  26973. });
  26974. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26975. get: function () {
  26976. return false;
  26977. },
  26978. enumerable: true,
  26979. configurable: true
  26980. });
  26981. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26982. var engine = this.getScene().getEngine();
  26983. var indexToBind = this._geometry.getIndexBuffer();
  26984. // VBOs
  26985. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26986. // Color
  26987. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26988. };
  26989. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26990. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26991. return;
  26992. }
  26993. var engine = this.getScene().getEngine();
  26994. // Draw order
  26995. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26996. };
  26997. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26998. return null;
  26999. };
  27000. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27001. this._colorShader.dispose();
  27002. _super.prototype.dispose.call(this, doNotRecurse);
  27003. };
  27004. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27005. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27006. };
  27007. return LinesMesh;
  27008. })(BABYLON.Mesh);
  27009. BABYLON.LinesMesh = LinesMesh;
  27010. })(BABYLON || (BABYLON = {}));
  27011. var BABYLON;
  27012. (function (BABYLON) {
  27013. var DebugLayer = (function () {
  27014. function DebugLayer(scene) {
  27015. var _this = this;
  27016. this._transformationMatrix = BABYLON.Matrix.Identity();
  27017. this._enabled = false;
  27018. this._labelsEnabled = false;
  27019. this._displayStatistics = true;
  27020. this._displayTree = false;
  27021. this._displayLogs = false;
  27022. this._identityMatrix = BABYLON.Matrix.Identity();
  27023. this.axisRatio = 0.02;
  27024. this.accentColor = "orange";
  27025. this._scene = scene;
  27026. this._syncPositions = function () {
  27027. var engine = _this._scene.getEngine();
  27028. var canvasRect = engine.getRenderingCanvasClientRect();
  27029. if (_this._showUI) {
  27030. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27031. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27032. _this._statsDiv.style.width = "400px";
  27033. _this._statsDiv.style.height = "auto";
  27034. _this._statsSubsetDiv.style.maxHeight = "240px";
  27035. _this._optionsDiv.style.left = "0px";
  27036. _this._optionsDiv.style.top = "10px";
  27037. _this._optionsDiv.style.width = "200px";
  27038. _this._optionsDiv.style.height = "auto";
  27039. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27040. _this._logDiv.style.left = "0px";
  27041. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27042. _this._logDiv.style.width = "600px";
  27043. _this._logDiv.style.height = "160px";
  27044. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27045. _this._treeDiv.style.top = "10px";
  27046. _this._treeDiv.style.width = "300px";
  27047. _this._treeDiv.style.height = "auto";
  27048. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27049. }
  27050. _this._globalDiv.style.left = canvasRect.left + "px";
  27051. _this._globalDiv.style.top = canvasRect.top + "px";
  27052. _this._drawingCanvas.style.left = "0px";
  27053. _this._drawingCanvas.style.top = "0px";
  27054. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27055. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27056. var devicePixelRatio = window.devicePixelRatio || 1;
  27057. var context = _this._drawingContext;
  27058. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27059. context.mozBackingStorePixelRatio ||
  27060. context.msBackingStorePixelRatio ||
  27061. context.oBackingStorePixelRatio ||
  27062. context.backingStorePixelRatio || 1;
  27063. _this._ratio = devicePixelRatio / backingStoreRatio;
  27064. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27065. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27066. };
  27067. this._onCanvasClick = function (evt) {
  27068. _this._clickPosition = {
  27069. x: evt.clientX * _this._ratio,
  27070. y: evt.clientY * _this._ratio
  27071. };
  27072. };
  27073. this._syncUI = function () {
  27074. if (_this._showUI) {
  27075. if (_this._displayStatistics) {
  27076. _this._displayStats();
  27077. _this._statsDiv.style.display = "";
  27078. }
  27079. else {
  27080. _this._statsDiv.style.display = "none";
  27081. }
  27082. if (_this._displayLogs) {
  27083. _this._logDiv.style.display = "";
  27084. }
  27085. else {
  27086. _this._logDiv.style.display = "none";
  27087. }
  27088. if (_this._displayTree) {
  27089. _this._treeDiv.style.display = "";
  27090. if (_this._needToRefreshMeshesTree) {
  27091. _this._needToRefreshMeshesTree = false;
  27092. _this._refreshMeshesTreeContent();
  27093. }
  27094. }
  27095. else {
  27096. _this._treeDiv.style.display = "none";
  27097. }
  27098. }
  27099. };
  27100. this._syncData = function () {
  27101. if (_this._labelsEnabled || !_this._showUI) {
  27102. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27103. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27104. var engine = _this._scene.getEngine();
  27105. var viewport = _this._camera.viewport;
  27106. var globalViewport = viewport.toGlobal(engine);
  27107. // Meshes
  27108. var meshes = _this._camera.getActiveMeshes();
  27109. var index;
  27110. var projectedPosition;
  27111. for (index = 0; index < meshes.length; index++) {
  27112. var mesh = meshes.data[index];
  27113. var position = mesh.getBoundingInfo().boundingSphere.center;
  27114. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27115. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27116. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27117. }
  27118. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27119. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27120. }
  27121. }
  27122. // Cameras
  27123. var cameras = _this._scene.cameras;
  27124. for (index = 0; index < cameras.length; index++) {
  27125. var camera = cameras[index];
  27126. if (camera === _this._camera) {
  27127. continue;
  27128. }
  27129. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27130. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27131. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27132. _this._camera.detachControl(engine.getRenderingCanvas());
  27133. _this._camera = camera;
  27134. _this._camera.attachControl(engine.getRenderingCanvas());
  27135. }, function () { return "purple"; });
  27136. }
  27137. }
  27138. // Lights
  27139. var lights = _this._scene.lights;
  27140. for (index = 0; index < lights.length; index++) {
  27141. var light = lights[index];
  27142. if (light.position) {
  27143. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27144. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27145. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27146. light.setEnabled(!light.isEnabled());
  27147. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27148. }
  27149. }
  27150. }
  27151. }
  27152. _this._clickPosition = undefined;
  27153. };
  27154. }
  27155. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27156. while (this._treeSubsetDiv.hasChildNodes()) {
  27157. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27158. }
  27159. // Add meshes
  27160. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27161. sortedArray.sort(function (a, b) {
  27162. if (a.name === b.name) {
  27163. return 0;
  27164. }
  27165. return (a.name > b.name) ? 1 : -1;
  27166. });
  27167. for (var index = 0; index < sortedArray.length; index++) {
  27168. var mesh = sortedArray[index];
  27169. if (!mesh.isEnabled()) {
  27170. continue;
  27171. }
  27172. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27173. m.isVisible = element.checked;
  27174. }, mesh);
  27175. }
  27176. };
  27177. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27178. this._drawingContext.beginPath();
  27179. this._drawingContext.moveTo(zero.x, zero.y);
  27180. this._drawingContext.lineTo(unit.x, unit.y);
  27181. this._drawingContext.strokeStyle = color;
  27182. this._drawingContext.lineWidth = 4;
  27183. this._drawingContext.stroke();
  27184. this._drawingContext.font = "normal 14px Segoe UI";
  27185. this._drawingContext.fillStyle = color;
  27186. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27187. };
  27188. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27189. var position = mesh.getBoundingInfo().boundingSphere.center;
  27190. var worldMatrix = mesh.getWorldMatrix();
  27191. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27192. var unit = (unprojectedVector.subtract(position)).length();
  27193. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27194. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27195. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27196. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27197. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27198. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27199. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27200. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27201. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27202. };
  27203. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27204. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27205. this._drawingContext.font = "normal 12px Segoe UI";
  27206. var textMetrics = this._drawingContext.measureText(text);
  27207. var centerX = projectedPosition.x - textMetrics.width / 2;
  27208. var centerY = projectedPosition.y;
  27209. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27210. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27211. onClick();
  27212. }
  27213. this._drawingContext.beginPath();
  27214. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27215. this._drawingContext.fillStyle = getFillStyle();
  27216. this._drawingContext.globalAlpha = 0.5;
  27217. this._drawingContext.fill();
  27218. this._drawingContext.globalAlpha = 1.0;
  27219. this._drawingContext.strokeStyle = '#FFFFFF';
  27220. this._drawingContext.lineWidth = 1;
  27221. this._drawingContext.stroke();
  27222. this._drawingContext.fillStyle = "#FFFFFF";
  27223. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27224. this._drawingContext.beginPath();
  27225. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27226. this._drawingContext.fill();
  27227. }
  27228. };
  27229. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27230. if (!this._clickPosition) {
  27231. return false;
  27232. }
  27233. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27234. return false;
  27235. }
  27236. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27237. return false;
  27238. }
  27239. return true;
  27240. };
  27241. DebugLayer.prototype.isVisible = function () {
  27242. return this._enabled;
  27243. };
  27244. DebugLayer.prototype.hide = function () {
  27245. if (!this._enabled) {
  27246. return;
  27247. }
  27248. this._enabled = false;
  27249. var engine = this._scene.getEngine();
  27250. this._scene.unregisterBeforeRender(this._syncData);
  27251. this._scene.unregisterAfterRender(this._syncUI);
  27252. this._rootElement.removeChild(this._globalDiv);
  27253. this._scene.forceShowBoundingBoxes = false;
  27254. this._scene.forceWireframe = false;
  27255. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27256. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27257. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27258. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27259. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27260. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27261. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27262. BABYLON.StandardMaterial.LightmapEnabled = true;
  27263. this._scene.shadowsEnabled = true;
  27264. this._scene.particlesEnabled = true;
  27265. this._scene.postProcessesEnabled = true;
  27266. this._scene.collisionsEnabled = true;
  27267. this._scene.lightsEnabled = true;
  27268. this._scene.texturesEnabled = true;
  27269. this._scene.lensFlaresEnabled = true;
  27270. this._scene.proceduralTexturesEnabled = true;
  27271. this._scene.renderTargetsEnabled = true;
  27272. this._scene.probesEnabled = true;
  27273. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27274. };
  27275. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27276. if (showUI === void 0) { showUI = true; }
  27277. if (camera === void 0) { camera = null; }
  27278. if (rootElement === void 0) { rootElement = null; }
  27279. if (this._enabled) {
  27280. return;
  27281. }
  27282. this._enabled = true;
  27283. if (camera) {
  27284. this._camera = camera;
  27285. }
  27286. else {
  27287. this._camera = this._scene.activeCamera;
  27288. }
  27289. this._showUI = showUI;
  27290. var engine = this._scene.getEngine();
  27291. this._globalDiv = document.createElement("div");
  27292. this._rootElement = rootElement || document.body;
  27293. this._rootElement.appendChild(this._globalDiv);
  27294. this._generateDOMelements();
  27295. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27296. this._syncPositions();
  27297. this._scene.registerBeforeRender(this._syncData);
  27298. this._scene.registerAfterRender(this._syncUI);
  27299. };
  27300. DebugLayer.prototype._clearLabels = function () {
  27301. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27302. for (var index = 0; index < this._scene.meshes.length; index++) {
  27303. var mesh = this._scene.meshes[index];
  27304. mesh.renderOverlay = false;
  27305. }
  27306. };
  27307. DebugLayer.prototype._generateheader = function (root, text) {
  27308. var header = document.createElement("div");
  27309. header.innerHTML = text + "&nbsp;";
  27310. header.style.textAlign = "right";
  27311. header.style.width = "100%";
  27312. header.style.color = "white";
  27313. header.style.backgroundColor = "Black";
  27314. header.style.padding = "5px 5px 4px 0px";
  27315. header.style.marginLeft = "-5px";
  27316. header.style.fontWeight = "bold";
  27317. root.appendChild(header);
  27318. };
  27319. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27320. var label = document.createElement("label");
  27321. label.innerHTML = title;
  27322. label.style.color = color;
  27323. root.appendChild(label);
  27324. root.appendChild(document.createElement("br"));
  27325. };
  27326. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27327. if (tag === void 0) { tag = null; }
  27328. var label = document.createElement("label");
  27329. var boundingBoxesCheckbox = document.createElement("input");
  27330. boundingBoxesCheckbox.type = "checkbox";
  27331. boundingBoxesCheckbox.checked = initialState;
  27332. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27333. task(evt.target, tag);
  27334. });
  27335. label.appendChild(boundingBoxesCheckbox);
  27336. var container = document.createElement("span");
  27337. var leftPart = document.createElement("span");
  27338. var rightPart = document.createElement("span");
  27339. rightPart.style.cssFloat = "right";
  27340. leftPart.innerHTML = leftTitle;
  27341. rightPart.innerHTML = rightTitle;
  27342. rightPart.style.fontSize = "12px";
  27343. rightPart.style.maxWidth = "200px";
  27344. container.appendChild(leftPart);
  27345. container.appendChild(rightPart);
  27346. label.appendChild(container);
  27347. root.appendChild(label);
  27348. root.appendChild(document.createElement("br"));
  27349. };
  27350. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27351. if (tag === void 0) { tag = null; }
  27352. var label = document.createElement("label");
  27353. var checkBox = document.createElement("input");
  27354. checkBox.type = "checkbox";
  27355. checkBox.checked = initialState;
  27356. checkBox.addEventListener("change", function (evt) {
  27357. task(evt.target, tag);
  27358. });
  27359. label.appendChild(checkBox);
  27360. label.appendChild(document.createTextNode(title));
  27361. root.appendChild(label);
  27362. root.appendChild(document.createElement("br"));
  27363. };
  27364. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27365. if (tag === void 0) { tag = null; }
  27366. var button = document.createElement("button");
  27367. button.innerHTML = title;
  27368. button.style.height = "24px";
  27369. button.style.width = "150px";
  27370. button.style.marginBottom = "5px";
  27371. button.style.color = "#444444";
  27372. button.style.border = "1px solid white";
  27373. button.className = "debugLayerButton";
  27374. button.addEventListener("click", function (evt) {
  27375. task(evt.target, tag);
  27376. });
  27377. root.appendChild(button);
  27378. root.appendChild(document.createElement("br"));
  27379. };
  27380. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27381. if (tag === void 0) { tag = null; }
  27382. var label = document.createElement("label");
  27383. var boundingBoxesRadio = document.createElement("input");
  27384. boundingBoxesRadio.type = "radio";
  27385. boundingBoxesRadio.name = name;
  27386. boundingBoxesRadio.checked = initialState;
  27387. boundingBoxesRadio.addEventListener("change", function (evt) {
  27388. task(evt.target, tag);
  27389. });
  27390. label.appendChild(boundingBoxesRadio);
  27391. label.appendChild(document.createTextNode(title));
  27392. root.appendChild(label);
  27393. root.appendChild(document.createElement("br"));
  27394. };
  27395. DebugLayer.prototype._generateDOMelements = function () {
  27396. var _this = this;
  27397. this._globalDiv.id = "DebugLayer";
  27398. this._globalDiv.style.position = "absolute";
  27399. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27400. this._globalDiv.style.fontSize = "14px";
  27401. this._globalDiv.style.color = "white";
  27402. // Drawing canvas
  27403. this._drawingCanvas = document.createElement("canvas");
  27404. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27405. this._drawingCanvas.style.position = "absolute";
  27406. this._drawingCanvas.style.pointerEvents = "none";
  27407. this._drawingCanvas.style.backgroundColor = "transparent";
  27408. this._drawingContext = this._drawingCanvas.getContext("2d");
  27409. this._globalDiv.appendChild(this._drawingCanvas);
  27410. if (this._showUI) {
  27411. var background = "rgba(128, 128, 128, 0.4)";
  27412. var border = "rgb(180, 180, 180) solid 1px";
  27413. // Stats
  27414. this._statsDiv = document.createElement("div");
  27415. this._statsDiv.id = "DebugLayerStats";
  27416. this._statsDiv.style.border = border;
  27417. this._statsDiv.style.position = "absolute";
  27418. this._statsDiv.style.background = background;
  27419. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27420. this._generateheader(this._statsDiv, "STATISTICS");
  27421. this._statsSubsetDiv = document.createElement("div");
  27422. this._statsSubsetDiv.style.paddingTop = "5px";
  27423. this._statsSubsetDiv.style.paddingBottom = "5px";
  27424. this._statsSubsetDiv.style.overflowY = "auto";
  27425. this._statsDiv.appendChild(this._statsSubsetDiv);
  27426. // Tree
  27427. this._treeDiv = document.createElement("div");
  27428. this._treeDiv.id = "DebugLayerTree";
  27429. this._treeDiv.style.border = border;
  27430. this._treeDiv.style.position = "absolute";
  27431. this._treeDiv.style.background = background;
  27432. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27433. this._treeDiv.style.display = "none";
  27434. this._generateheader(this._treeDiv, "MESHES TREE");
  27435. this._treeSubsetDiv = document.createElement("div");
  27436. this._treeSubsetDiv.style.paddingTop = "5px";
  27437. this._treeSubsetDiv.style.paddingRight = "5px";
  27438. this._treeSubsetDiv.style.overflowY = "auto";
  27439. this._treeSubsetDiv.style.maxHeight = "300px";
  27440. this._treeDiv.appendChild(this._treeSubsetDiv);
  27441. this._needToRefreshMeshesTree = true;
  27442. // Logs
  27443. this._logDiv = document.createElement("div");
  27444. this._logDiv.style.border = border;
  27445. this._logDiv.id = "DebugLayerLogs";
  27446. this._logDiv.style.position = "absolute";
  27447. this._logDiv.style.background = background;
  27448. this._logDiv.style.padding = "0px 0px 0px 5px";
  27449. this._logDiv.style.display = "none";
  27450. this._generateheader(this._logDiv, "LOGS");
  27451. this._logSubsetDiv = document.createElement("div");
  27452. this._logSubsetDiv.style.height = "127px";
  27453. this._logSubsetDiv.style.paddingTop = "5px";
  27454. this._logSubsetDiv.style.overflowY = "auto";
  27455. this._logSubsetDiv.style.fontSize = "12px";
  27456. this._logSubsetDiv.style.fontFamily = "consolas";
  27457. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27458. this._logDiv.appendChild(this._logSubsetDiv);
  27459. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27460. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27461. };
  27462. // Options
  27463. this._optionsDiv = document.createElement("div");
  27464. this._optionsDiv.id = "DebugLayerOptions";
  27465. this._optionsDiv.style.border = border;
  27466. this._optionsDiv.style.position = "absolute";
  27467. this._optionsDiv.style.background = background;
  27468. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27469. this._optionsDiv.style.overflowY = "auto";
  27470. this._generateheader(this._optionsDiv, "OPTIONS");
  27471. this._optionsSubsetDiv = document.createElement("div");
  27472. this._optionsSubsetDiv.style.paddingTop = "5px";
  27473. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27474. this._optionsSubsetDiv.style.overflowY = "auto";
  27475. this._optionsSubsetDiv.style.maxHeight = "200px";
  27476. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27477. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27478. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27479. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27480. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27481. _this._displayTree = element.checked;
  27482. _this._needToRefreshMeshesTree = true;
  27483. });
  27484. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27485. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27486. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27487. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27488. _this._labelsEnabled = element.checked;
  27489. if (!_this._labelsEnabled) {
  27490. _this._clearLabels();
  27491. }
  27492. });
  27493. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27494. if (element.checked) {
  27495. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27496. }
  27497. else {
  27498. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27499. }
  27500. });
  27501. ;
  27502. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27503. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27504. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27505. if (element.checked) {
  27506. _this._scene.forceWireframe = false;
  27507. _this._scene.forcePointsCloud = false;
  27508. }
  27509. });
  27510. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27511. if (element.checked) {
  27512. _this._scene.forceWireframe = true;
  27513. _this._scene.forcePointsCloud = false;
  27514. }
  27515. });
  27516. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27517. if (element.checked) {
  27518. _this._scene.forceWireframe = false;
  27519. _this._scene.forcePointsCloud = true;
  27520. }
  27521. });
  27522. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27523. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27524. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27525. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27526. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27527. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27528. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27529. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27530. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27531. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27532. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27533. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27534. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27535. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27536. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27537. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27538. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27539. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27540. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27541. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27542. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27543. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27544. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27545. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27546. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27547. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27548. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27549. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27550. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27551. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27552. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27553. if (element.checked) {
  27554. _this._scene.headphone = true;
  27555. }
  27556. });
  27557. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27558. if (element.checked) {
  27559. _this._scene.headphone = false;
  27560. }
  27561. });
  27562. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27563. _this._scene.audioEnabled = !element.checked;
  27564. });
  27565. }
  27566. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27567. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27568. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27569. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27570. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27571. if (_this._camera) {
  27572. console.log(_this._camera);
  27573. }
  27574. else {
  27575. console.warn("No camera defined, or debug layer created before camera creation!");
  27576. }
  27577. });
  27578. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27579. this._globalDiv.appendChild(this._statsDiv);
  27580. this._globalDiv.appendChild(this._logDiv);
  27581. this._globalDiv.appendChild(this._optionsDiv);
  27582. this._globalDiv.appendChild(this._treeDiv);
  27583. }
  27584. };
  27585. DebugLayer.prototype._displayStats = function () {
  27586. var scene = this._scene;
  27587. var engine = scene.getEngine();
  27588. var glInfo = engine.getGlInfo();
  27589. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27590. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27591. + "<b>Count</b><br>"
  27592. + "Total meshes: " + scene.meshes.length + "<br>"
  27593. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27594. + "Total materials: " + scene.materials.length + "<br>"
  27595. + "Total textures: " + scene.textures.length + "<br>"
  27596. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27597. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27598. + "Active bones: " + scene.getActiveBones() + "<br>"
  27599. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27600. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27601. + "<b>Duration</b><br>"
  27602. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27603. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27604. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27605. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27606. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27607. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27608. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27609. + "</div>"
  27610. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27611. + "<b>Extensions</b><br>"
  27612. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27613. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27614. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27615. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27616. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27617. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27618. + "<b>Caps.</b><br>"
  27619. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27620. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27621. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27622. + "</div><br>"
  27623. + "<b>Info</b><br>"
  27624. + glInfo.version + "<br>"
  27625. + glInfo.renderer + "<br>";
  27626. if (this.customStatsFunction) {
  27627. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27628. }
  27629. };
  27630. return DebugLayer;
  27631. })();
  27632. BABYLON.DebugLayer = DebugLayer;
  27633. })(BABYLON || (BABYLON = {}));
  27634. var BABYLON;
  27635. (function (BABYLON) {
  27636. var DefaultLoadingScreen = (function () {
  27637. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27638. var _this = this;
  27639. if (_loadingText === void 0) { _loadingText = ""; }
  27640. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27641. this._renderingCanvas = _renderingCanvas;
  27642. this._loadingText = _loadingText;
  27643. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27644. // Resize
  27645. this._resizeLoadingUI = function () {
  27646. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27647. _this._loadingDiv.style.position = "absolute";
  27648. _this._loadingDiv.style.left = canvasRect.left + "px";
  27649. _this._loadingDiv.style.top = canvasRect.top + "px";
  27650. _this._loadingDiv.style.width = canvasRect.width + "px";
  27651. _this._loadingDiv.style.height = canvasRect.height + "px";
  27652. };
  27653. }
  27654. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27655. var _this = this;
  27656. this._loadingDiv = document.createElement("div");
  27657. this._loadingDiv.id = "babylonjsLoadingDiv";
  27658. this._loadingDiv.style.opacity = "0";
  27659. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27660. // Loading text
  27661. this._loadingTextDiv = document.createElement("div");
  27662. this._loadingTextDiv.style.position = "absolute";
  27663. this._loadingTextDiv.style.left = "0";
  27664. this._loadingTextDiv.style.top = "50%";
  27665. this._loadingTextDiv.style.marginTop = "80px";
  27666. this._loadingTextDiv.style.width = "100%";
  27667. this._loadingTextDiv.style.height = "20px";
  27668. this._loadingTextDiv.style.fontFamily = "Arial";
  27669. this._loadingTextDiv.style.fontSize = "14px";
  27670. this._loadingTextDiv.style.color = "white";
  27671. this._loadingTextDiv.style.textAlign = "center";
  27672. this._loadingTextDiv.innerHTML = "Loading";
  27673. this._loadingDiv.appendChild(this._loadingTextDiv);
  27674. //set the predefined text
  27675. this._loadingTextDiv.innerHTML = this._loadingText;
  27676. // Loading img
  27677. var imgBack = new Image();
  27678. 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==";
  27679. imgBack.style.position = "absolute";
  27680. imgBack.style.left = "50%";
  27681. imgBack.style.top = "50%";
  27682. imgBack.style.marginLeft = "-50px";
  27683. imgBack.style.marginTop = "-50px";
  27684. imgBack.style.transition = "transform 1.0s ease";
  27685. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27686. var deg = 360;
  27687. var onTransitionEnd = function () {
  27688. deg += 360;
  27689. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27690. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27691. };
  27692. imgBack.addEventListener("transitionend", onTransitionEnd);
  27693. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27694. this._loadingDiv.appendChild(imgBack);
  27695. // front image
  27696. var imgFront = new Image();
  27697. 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=";
  27698. imgFront.style.position = "absolute";
  27699. imgFront.style.left = "50%";
  27700. imgFront.style.top = "50%";
  27701. imgFront.style.marginLeft = "-50px";
  27702. imgFront.style.marginTop = "-50px";
  27703. this._loadingDiv.appendChild(imgFront);
  27704. this._resizeLoadingUI();
  27705. window.addEventListener("resize", this._resizeLoadingUI);
  27706. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27707. document.body.appendChild(this._loadingDiv);
  27708. setTimeout(function () {
  27709. _this._loadingDiv.style.opacity = "1";
  27710. imgBack.style.transform = "rotateZ(360deg)";
  27711. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27712. }, 0);
  27713. };
  27714. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27715. var _this = this;
  27716. if (!this._loadingDiv) {
  27717. return;
  27718. }
  27719. var onTransitionEnd = function () {
  27720. if (!_this._loadingDiv) {
  27721. return;
  27722. }
  27723. document.body.removeChild(_this._loadingDiv);
  27724. window.removeEventListener("resize", _this._resizeLoadingUI);
  27725. _this._loadingDiv = null;
  27726. };
  27727. this._loadingDiv.style.opacity = "0";
  27728. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27729. };
  27730. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27731. set: function (text) {
  27732. this._loadingText = text;
  27733. if (this._loadingTextDiv) {
  27734. this._loadingTextDiv.innerHTML = this._loadingText;
  27735. }
  27736. },
  27737. enumerable: true,
  27738. configurable: true
  27739. });
  27740. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27741. get: function () {
  27742. return this._loadingDivBackgroundColor;
  27743. },
  27744. set: function (color) {
  27745. this._loadingDivBackgroundColor = color;
  27746. if (!this._loadingDiv) {
  27747. return;
  27748. }
  27749. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27750. },
  27751. enumerable: true,
  27752. configurable: true
  27753. });
  27754. return DefaultLoadingScreen;
  27755. })();
  27756. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27757. })(BABYLON || (BABYLON = {}));
  27758. var BABYLON;
  27759. (function (BABYLON) {
  27760. var SIMDVector3 = (function () {
  27761. function SIMDVector3() {
  27762. }
  27763. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27764. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27765. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27766. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27767. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27768. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27769. 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));
  27770. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27771. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27772. };
  27773. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27774. var v0 = SIMD.float32x4.splat(x);
  27775. var v1 = SIMD.float32x4.splat(y);
  27776. var v2 = SIMD.float32x4.splat(z);
  27777. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27778. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27779. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27780. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27781. 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));
  27782. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27783. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27784. };
  27785. return SIMDVector3;
  27786. })();
  27787. BABYLON.SIMDVector3 = SIMDVector3;
  27788. var SIMDMatrix = (function () {
  27789. function SIMDMatrix() {
  27790. }
  27791. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27792. if (offset === void 0) { offset = 0; }
  27793. var tm = this.m;
  27794. var om = other.m;
  27795. var om0 = SIMD.float32x4.load(om, 0);
  27796. var om1 = SIMD.float32x4.load(om, 4);
  27797. var om2 = SIMD.float32x4.load(om, 8);
  27798. var om3 = SIMD.float32x4.load(om, 12);
  27799. var tm0 = SIMD.float32x4.load(tm, 0);
  27800. 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)))));
  27801. var tm1 = SIMD.float32x4.load(tm, 4);
  27802. 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)))));
  27803. var tm2 = SIMD.float32x4.load(tm, 8);
  27804. 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)))));
  27805. var tm3 = SIMD.float32x4.load(tm, 12);
  27806. 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)))));
  27807. };
  27808. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27809. var src = this.m;
  27810. var dest = other.m;
  27811. var row0, row1, row2, row3;
  27812. var tmp1;
  27813. var minor0, minor1, minor2, minor3;
  27814. var det;
  27815. // Load the 4 rows
  27816. var src0 = SIMD.float32x4.load(src, 0);
  27817. var src1 = SIMD.float32x4.load(src, 4);
  27818. var src2 = SIMD.float32x4.load(src, 8);
  27819. var src3 = SIMD.float32x4.load(src, 12);
  27820. // Transpose the source matrix. Sort of. Not a true transpose operation
  27821. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27822. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27823. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27824. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27825. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27826. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27827. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27828. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27829. // This is a true transposition, but it will lead to an incorrect result
  27830. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27831. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27832. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27833. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27834. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27835. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27836. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27837. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27838. // ----
  27839. tmp1 = SIMD.float32x4.mul(row2, row3);
  27840. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27841. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27842. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27843. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27844. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27845. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27846. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27847. // ----
  27848. tmp1 = SIMD.float32x4.mul(row1, row2);
  27849. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27850. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27851. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27852. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27853. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27854. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27855. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27856. // ----
  27857. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27858. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27859. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27860. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27861. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27862. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27863. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27864. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27865. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27866. // ----
  27867. tmp1 = SIMD.float32x4.mul(row0, row1);
  27868. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27869. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27870. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27871. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27872. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27873. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27874. // ----
  27875. tmp1 = SIMD.float32x4.mul(row0, row3);
  27876. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27877. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27878. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27879. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27880. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27881. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27882. // ----
  27883. tmp1 = SIMD.float32x4.mul(row0, row2);
  27884. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27885. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27886. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27887. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27888. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27889. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27890. // Compute determinant
  27891. det = SIMD.float32x4.mul(row0, minor0);
  27892. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27893. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27894. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27895. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27896. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27897. // These shuffles aren't necessary if the faulty transposition is done
  27898. // up at the top of this function.
  27899. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27900. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27901. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27902. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27903. // Compute final values by multiplying with 1/det
  27904. minor0 = SIMD.float32x4.mul(det, minor0);
  27905. minor1 = SIMD.float32x4.mul(det, minor1);
  27906. minor2 = SIMD.float32x4.mul(det, minor2);
  27907. minor3 = SIMD.float32x4.mul(det, minor3);
  27908. SIMD.float32x4.store(dest, 0, minor0);
  27909. SIMD.float32x4.store(dest, 4, minor1);
  27910. SIMD.float32x4.store(dest, 8, minor2);
  27911. SIMD.float32x4.store(dest, 12, minor3);
  27912. return this;
  27913. };
  27914. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27915. var out = result.m;
  27916. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27917. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27918. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27919. // cc.kmVec3Subtract(f, pCenter, pEye);
  27920. var f = SIMD.float32x4.sub(center, eye);
  27921. // cc.kmVec3Normalize(f, f);
  27922. var tmp = SIMD.float32x4.mul(f, f);
  27923. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27924. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27925. // cc.kmVec3Assign(up, pUp);
  27926. // cc.kmVec3Normalize(up, up);
  27927. tmp = SIMD.float32x4.mul(up, up);
  27928. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27929. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27930. // cc.kmVec3Cross(s, f, up);
  27931. 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)));
  27932. // cc.kmVec3Normalize(s, s);
  27933. tmp = SIMD.float32x4.mul(s, s);
  27934. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27935. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27936. // cc.kmVec3Cross(u, s, f);
  27937. 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)));
  27938. // cc.kmVec3Normalize(s, s);
  27939. tmp = SIMD.float32x4.mul(s, s);
  27940. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27941. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27942. var zero = SIMD.float32x4.splat(0.0);
  27943. s = SIMD.float32x4.neg(s);
  27944. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27945. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27946. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27947. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27948. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27949. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27950. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27951. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27952. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27953. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27954. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27955. var b3 = SIMD.float32x4.neg(eye);
  27956. b3 = SIMD.float32x4.withW(b3, 1.0);
  27957. 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)))));
  27958. 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)))));
  27959. 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)))));
  27960. 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)))));
  27961. };
  27962. return SIMDMatrix;
  27963. })();
  27964. BABYLON.SIMDMatrix = SIMDMatrix;
  27965. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27966. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27967. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27968. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27969. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27970. var SIMDHelper = (function () {
  27971. function SIMDHelper() {
  27972. }
  27973. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27974. get: function () {
  27975. return SIMDHelper._isEnabled;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. SIMDHelper.DisableSIMD = function () {
  27981. // Replace functions
  27982. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27983. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27984. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27985. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27986. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27987. SIMDHelper._isEnabled = false;
  27988. };
  27989. SIMDHelper.EnableSIMD = function () {
  27990. if (window.SIMD === undefined) {
  27991. return;
  27992. }
  27993. // Replace functions
  27994. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27995. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27996. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27997. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27999. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28000. get: function () { return this._data[0]; },
  28001. set: function (value) {
  28002. if (!this._data) {
  28003. this._data = new Float32Array(3);
  28004. }
  28005. this._data[0] = value;
  28006. }
  28007. });
  28008. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28009. get: function () { return this._data[1]; },
  28010. set: function (value) {
  28011. this._data[1] = value;
  28012. }
  28013. });
  28014. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28015. get: function () { return this._data[2]; },
  28016. set: function (value) {
  28017. this._data[2] = value;
  28018. }
  28019. });
  28020. SIMDHelper._isEnabled = true;
  28021. };
  28022. SIMDHelper._isEnabled = false;
  28023. return SIMDHelper;
  28024. })();
  28025. BABYLON.SIMDHelper = SIMDHelper;
  28026. })(BABYLON || (BABYLON = {}));
  28027. var BABYLON;
  28028. (function (BABYLON) {
  28029. var ShaderMaterial = (function (_super) {
  28030. __extends(ShaderMaterial, _super);
  28031. function ShaderMaterial(name, scene, shaderPath, options) {
  28032. _super.call(this, name, scene);
  28033. this._textures = new Array();
  28034. this._floats = new Array();
  28035. this._floatsArrays = {};
  28036. this._colors3 = new Array();
  28037. this._colors4 = new Array();
  28038. this._vectors2 = new Array();
  28039. this._vectors3 = new Array();
  28040. this._vectors4 = new Array();
  28041. this._matrices = new Array();
  28042. this._matrices3x3 = new Array();
  28043. this._matrices2x2 = new Array();
  28044. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28045. this._shaderPath = shaderPath;
  28046. options.needAlphaBlending = options.needAlphaBlending || false;
  28047. options.needAlphaTesting = options.needAlphaTesting || false;
  28048. options.attributes = options.attributes || ["position", "normal", "uv"];
  28049. options.uniforms = options.uniforms || ["worldViewProjection"];
  28050. options.samplers = options.samplers || [];
  28051. options.defines = options.defines || [];
  28052. this._options = options;
  28053. }
  28054. ShaderMaterial.prototype.needAlphaBlending = function () {
  28055. return this._options.needAlphaBlending;
  28056. };
  28057. ShaderMaterial.prototype.needAlphaTesting = function () {
  28058. return this._options.needAlphaTesting;
  28059. };
  28060. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28061. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28062. this._options.uniforms.push(uniformName);
  28063. }
  28064. };
  28065. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28066. if (this._options.samplers.indexOf(name) === -1) {
  28067. this._options.samplers.push(name);
  28068. }
  28069. this._textures[name] = texture;
  28070. return this;
  28071. };
  28072. ShaderMaterial.prototype.setFloat = function (name, value) {
  28073. this._checkUniform(name);
  28074. this._floats[name] = value;
  28075. return this;
  28076. };
  28077. ShaderMaterial.prototype.setFloats = function (name, value) {
  28078. this._checkUniform(name);
  28079. this._floatsArrays[name] = value;
  28080. return this;
  28081. };
  28082. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28083. this._checkUniform(name);
  28084. this._colors3[name] = value;
  28085. return this;
  28086. };
  28087. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28088. this._checkUniform(name);
  28089. this._colors4[name] = value;
  28090. return this;
  28091. };
  28092. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28093. this._checkUniform(name);
  28094. this._vectors2[name] = value;
  28095. return this;
  28096. };
  28097. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28098. this._checkUniform(name);
  28099. this._vectors3[name] = value;
  28100. return this;
  28101. };
  28102. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28103. this._checkUniform(name);
  28104. this._vectors4[name] = value;
  28105. return this;
  28106. };
  28107. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28108. this._checkUniform(name);
  28109. this._matrices[name] = value;
  28110. return this;
  28111. };
  28112. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28113. this._checkUniform(name);
  28114. this._matrices3x3[name] = value;
  28115. return this;
  28116. };
  28117. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28118. this._checkUniform(name);
  28119. this._matrices2x2[name] = value;
  28120. return this;
  28121. };
  28122. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28123. var scene = this.getScene();
  28124. var engine = scene.getEngine();
  28125. if (!this.checkReadyOnEveryCall) {
  28126. if (this._renderId === scene.getRenderId()) {
  28127. return true;
  28128. }
  28129. }
  28130. // Instances
  28131. var defines = [];
  28132. var fallbacks = new BABYLON.EffectFallbacks();
  28133. if (useInstances) {
  28134. defines.push("#define INSTANCES");
  28135. }
  28136. for (var index = 0; index < this._options.defines.length; index++) {
  28137. defines.push(this._options.defines[index]);
  28138. }
  28139. // Bones
  28140. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28141. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28142. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28143. fallbacks.addCPUSkinningFallback(0, mesh);
  28144. }
  28145. // Alpha test
  28146. if (engine.getAlphaTesting()) {
  28147. defines.push("#define ALPHATEST");
  28148. }
  28149. var previousEffect = this._effect;
  28150. var join = defines.join("\n");
  28151. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28152. if (!this._effect.isReady()) {
  28153. return false;
  28154. }
  28155. if (previousEffect !== this._effect) {
  28156. scene.resetCachedMaterial();
  28157. }
  28158. this._renderId = scene.getRenderId();
  28159. return true;
  28160. };
  28161. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28162. var scene = this.getScene();
  28163. if (this._options.uniforms.indexOf("world") !== -1) {
  28164. this._effect.setMatrix("world", world);
  28165. }
  28166. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28167. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28168. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28169. }
  28170. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28171. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28172. }
  28173. };
  28174. ShaderMaterial.prototype.bind = function (world, mesh) {
  28175. // Std values
  28176. this.bindOnlyWorldMatrix(world);
  28177. if (this.getScene().getCachedMaterial() !== this) {
  28178. if (this._options.uniforms.indexOf("view") !== -1) {
  28179. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28180. }
  28181. if (this._options.uniforms.indexOf("projection") !== -1) {
  28182. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28183. }
  28184. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28185. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28186. }
  28187. // Bones
  28188. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28189. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28190. }
  28191. // Texture
  28192. for (var name in this._textures) {
  28193. this._effect.setTexture(name, this._textures[name]);
  28194. }
  28195. // Float
  28196. for (name in this._floats) {
  28197. this._effect.setFloat(name, this._floats[name]);
  28198. }
  28199. // Float s
  28200. for (name in this._floatsArrays) {
  28201. this._effect.setArray(name, this._floatsArrays[name]);
  28202. }
  28203. // Color3
  28204. for (name in this._colors3) {
  28205. this._effect.setColor3(name, this._colors3[name]);
  28206. }
  28207. // Color4
  28208. for (name in this._colors4) {
  28209. var color = this._colors4[name];
  28210. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28211. }
  28212. // Vector2
  28213. for (name in this._vectors2) {
  28214. this._effect.setVector2(name, this._vectors2[name]);
  28215. }
  28216. // Vector3
  28217. for (name in this._vectors3) {
  28218. this._effect.setVector3(name, this._vectors3[name]);
  28219. }
  28220. // Vector4
  28221. for (name in this._vectors4) {
  28222. this._effect.setVector4(name, this._vectors4[name]);
  28223. }
  28224. // Matrix
  28225. for (name in this._matrices) {
  28226. this._effect.setMatrix(name, this._matrices[name]);
  28227. }
  28228. // Matrix 3x3
  28229. for (name in this._matrices3x3) {
  28230. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28231. }
  28232. // Matrix 2x2
  28233. for (name in this._matrices2x2) {
  28234. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28235. }
  28236. }
  28237. _super.prototype.bind.call(this, world, mesh);
  28238. };
  28239. ShaderMaterial.prototype.clone = function (name) {
  28240. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28241. return newShaderMaterial;
  28242. };
  28243. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28244. for (var name in this._textures) {
  28245. this._textures[name].dispose();
  28246. }
  28247. this._textures = [];
  28248. _super.prototype.dispose.call(this, forceDisposeEffect);
  28249. };
  28250. return ShaderMaterial;
  28251. })(BABYLON.Material);
  28252. BABYLON.ShaderMaterial = ShaderMaterial;
  28253. })(BABYLON || (BABYLON = {}));
  28254. var BABYLON;
  28255. (function (BABYLON) {
  28256. var Internals;
  28257. (function (Internals) {
  28258. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28259. // All values and structures referenced from:
  28260. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28261. var DDS_MAGIC = 0x20534444;
  28262. 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;
  28263. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28264. 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;
  28265. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28266. function FourCCToInt32(value) {
  28267. return value.charCodeAt(0) +
  28268. (value.charCodeAt(1) << 8) +
  28269. (value.charCodeAt(2) << 16) +
  28270. (value.charCodeAt(3) << 24);
  28271. }
  28272. function Int32ToFourCC(value) {
  28273. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28274. }
  28275. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28276. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28277. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28278. var headerLengthInt = 31; // The header length in 32 bit ints
  28279. // Offsets into the header array
  28280. var off_magic = 0;
  28281. var off_size = 1;
  28282. var off_flags = 2;
  28283. var off_height = 3;
  28284. var off_width = 4;
  28285. var off_mipmapCount = 7;
  28286. var off_pfFlags = 20;
  28287. var off_pfFourCC = 21;
  28288. var off_RGBbpp = 22;
  28289. var off_RMask = 23;
  28290. var off_GMask = 24;
  28291. var off_BMask = 25;
  28292. var off_AMask = 26;
  28293. var off_caps1 = 27;
  28294. var off_caps2 = 28;
  28295. ;
  28296. var DDSTools = (function () {
  28297. function DDSTools() {
  28298. }
  28299. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28300. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28301. var mipmapCount = 1;
  28302. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28303. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28304. }
  28305. return {
  28306. width: header[off_width],
  28307. height: header[off_height],
  28308. mipmapCount: mipmapCount,
  28309. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28310. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28311. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28312. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28313. };
  28314. };
  28315. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28316. var byteArray = new Uint8Array(dataLength);
  28317. var srcData = new Uint8Array(arrayBuffer);
  28318. var index = 0;
  28319. for (var y = height - 1; y >= 0; y--) {
  28320. for (var x = 0; x < width; x++) {
  28321. var srcPos = dataOffset + (x + y * width) * 4;
  28322. byteArray[index + 2] = srcData[srcPos];
  28323. byteArray[index + 1] = srcData[srcPos + 1];
  28324. byteArray[index] = srcData[srcPos + 2];
  28325. byteArray[index + 3] = srcData[srcPos + 3];
  28326. index += 4;
  28327. }
  28328. }
  28329. return byteArray;
  28330. };
  28331. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28332. var byteArray = new Uint8Array(dataLength);
  28333. var srcData = new Uint8Array(arrayBuffer);
  28334. var index = 0;
  28335. for (var y = height - 1; y >= 0; y--) {
  28336. for (var x = 0; x < width; x++) {
  28337. var srcPos = dataOffset + (x + y * width) * 3;
  28338. byteArray[index + 2] = srcData[srcPos];
  28339. byteArray[index + 1] = srcData[srcPos + 1];
  28340. byteArray[index] = srcData[srcPos + 2];
  28341. index += 3;
  28342. }
  28343. }
  28344. return byteArray;
  28345. };
  28346. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28347. var byteArray = new Uint8Array(dataLength);
  28348. var srcData = new Uint8Array(arrayBuffer);
  28349. var index = 0;
  28350. for (var y = height - 1; y >= 0; y--) {
  28351. for (var x = 0; x < width; x++) {
  28352. var srcPos = dataOffset + (x + y * width);
  28353. byteArray[index] = srcData[srcPos];
  28354. index++;
  28355. }
  28356. }
  28357. return byteArray;
  28358. };
  28359. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28360. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28361. if (header[off_magic] != DDS_MAGIC) {
  28362. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28363. return;
  28364. }
  28365. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28366. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28367. return;
  28368. }
  28369. if (info.isFourCC) {
  28370. fourCC = header[off_pfFourCC];
  28371. switch (fourCC) {
  28372. case FOURCC_DXT1:
  28373. blockBytes = 8;
  28374. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28375. break;
  28376. case FOURCC_DXT3:
  28377. blockBytes = 16;
  28378. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28379. break;
  28380. case FOURCC_DXT5:
  28381. blockBytes = 16;
  28382. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28383. break;
  28384. default:
  28385. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28386. return;
  28387. }
  28388. }
  28389. mipmapCount = 1;
  28390. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28391. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28392. }
  28393. var bpp = header[off_RGBbpp];
  28394. for (var face = 0; face < faces; face++) {
  28395. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28396. width = header[off_width];
  28397. height = header[off_height];
  28398. dataOffset = header[off_size] + 4;
  28399. for (i = 0; i < mipmapCount; ++i) {
  28400. if (info.isRGB) {
  28401. if (bpp === 24) {
  28402. dataLength = width * height * 3;
  28403. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28404. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28405. }
  28406. else {
  28407. dataLength = width * height * 4;
  28408. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28409. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28410. }
  28411. }
  28412. else if (info.isLuminance) {
  28413. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28414. var unpaddedRowSize = width;
  28415. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28416. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28417. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28418. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28419. }
  28420. else {
  28421. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28422. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28423. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28424. }
  28425. dataOffset += dataLength;
  28426. width *= 0.5;
  28427. height *= 0.5;
  28428. width = Math.max(1.0, width);
  28429. height = Math.max(1.0, height);
  28430. }
  28431. }
  28432. };
  28433. return DDSTools;
  28434. })();
  28435. Internals.DDSTools = DDSTools;
  28436. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28437. })(BABYLON || (BABYLON = {}));
  28438. var BABYLON;
  28439. (function (BABYLON) {
  28440. var CannonJSPlugin = (function () {
  28441. function CannonJSPlugin() {
  28442. this._registeredMeshes = [];
  28443. this._physicsMaterials = [];
  28444. this.name = "cannon";
  28445. this.updateBodyPosition = function (mesh) {
  28446. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28447. var registeredMesh = this._registeredMeshes[index];
  28448. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28449. var body = registeredMesh.body;
  28450. var center = mesh.getBoundingInfo().boundingBox.center;
  28451. body.position.set(center.x, center.y, center.z);
  28452. body.quaternion.copy(mesh.rotationQuaternion);
  28453. if (registeredMesh.deltaRotation) {
  28454. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28455. body.quaternion = body.quaternion.mult(tmpQ);
  28456. }
  28457. if (registeredMesh.heightmap) {
  28458. //calculate the correct body position:
  28459. var rotationQuaternion = mesh.rotationQuaternion;
  28460. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28461. mesh.computeWorldMatrix(true);
  28462. //get original center with no rotation
  28463. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28464. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28465. //rotation is back
  28466. mesh.rotationQuaternion = rotationQuaternion;
  28467. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28468. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28469. mesh.setPivotMatrix(p);
  28470. mesh.computeWorldMatrix(true);
  28471. //calculate the translation
  28472. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28473. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28474. //add it inverted to the delta
  28475. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28476. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28477. mesh.setPivotMatrix(oldPivot);
  28478. mesh.computeWorldMatrix(true);
  28479. }
  28480. return;
  28481. }
  28482. }
  28483. };
  28484. }
  28485. CannonJSPlugin.prototype.initialize = function (iterations) {
  28486. if (iterations === void 0) { iterations = 10; }
  28487. this._world = new CANNON.World();
  28488. this._world.broadphase = new CANNON.NaiveBroadphase();
  28489. this._world.solver.iterations = iterations;
  28490. };
  28491. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28492. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28493. };
  28494. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28495. var _this = this;
  28496. this._world.step(delta);
  28497. this._registeredMeshes.forEach(function (registeredMesh) {
  28498. // Body position
  28499. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28500. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28501. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28502. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28503. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28504. if (registeredMesh.deltaRotation) {
  28505. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28506. }
  28507. //is the physics collision callback is set?
  28508. if (registeredMesh.mesh.onPhysicsCollide) {
  28509. if (!registeredMesh.collisionFunction) {
  28510. registeredMesh.collisionFunction = function (e) {
  28511. //find the mesh that collided with the registered mesh
  28512. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28513. if (_this._registeredMeshes[idx].body == e.body) {
  28514. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28515. }
  28516. }
  28517. };
  28518. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28519. }
  28520. }
  28521. else {
  28522. //unregister, in case the function was removed for some reason
  28523. if (registeredMesh.collisionFunction) {
  28524. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28525. }
  28526. }
  28527. });
  28528. };
  28529. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28530. this._gravity = gravity;
  28531. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28532. };
  28533. CannonJSPlugin.prototype.getGravity = function () {
  28534. return this._gravity;
  28535. };
  28536. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28537. this.unregisterMesh(mesh);
  28538. if (!mesh.rotationQuaternion) {
  28539. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28540. }
  28541. mesh.computeWorldMatrix(true);
  28542. var shape = this._createShape(mesh, impostor);
  28543. return this._createRigidBodyFromShape(shape, mesh, options);
  28544. };
  28545. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28546. //get the correct bounding box
  28547. var oldQuaternion = mesh.rotationQuaternion;
  28548. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28549. mesh.computeWorldMatrix(true);
  28550. var returnValue;
  28551. switch (impostor) {
  28552. case BABYLON.PhysicsEngine.SphereImpostor:
  28553. var bbox = mesh.getBoundingInfo().boundingBox;
  28554. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28555. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28556. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28557. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28558. break;
  28559. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28560. case BABYLON.PhysicsEngine.CylinderImpostor:
  28561. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28562. case BABYLON.PhysicsEngine.BoxImpostor:
  28563. bbox = mesh.getBoundingInfo().boundingBox;
  28564. var min = bbox.minimumWorld;
  28565. var max = bbox.maximumWorld;
  28566. var box = max.subtract(min).scale(0.5);
  28567. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28568. break;
  28569. case BABYLON.PhysicsEngine.PlaneImpostor:
  28570. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28571. returnValue = new CANNON.Plane();
  28572. break;
  28573. case BABYLON.PhysicsEngine.MeshImpostor:
  28574. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28575. var rawFaces = mesh.getIndices();
  28576. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28577. break;
  28578. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28579. returnValue = this._createHeightmap(mesh);
  28580. break;
  28581. }
  28582. mesh.rotationQuaternion = oldQuaternion;
  28583. return returnValue;
  28584. };
  28585. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28586. var verts = [], faces = [];
  28587. mesh.computeWorldMatrix(true);
  28588. //reuse this variable
  28589. var transformed = BABYLON.Vector3.Zero();
  28590. // Get vertices
  28591. for (var i = 0; i < rawVerts.length; i += 3) {
  28592. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28593. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28594. }
  28595. // Get faces
  28596. for (var j = 0; j < rawFaces.length; j += 3) {
  28597. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28598. }
  28599. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28600. return shape;
  28601. };
  28602. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28603. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28604. var matrix = [];
  28605. //For now pointDepth will not be used and will be automatically calculated.
  28606. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28607. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28608. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28609. var elementSize = dim * 2 / arraySize;
  28610. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28611. for (var i = 0; i < pos.length; i = i + 3) {
  28612. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28613. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28614. var y = pos[i + 1] + minY;
  28615. if (!matrix[x]) {
  28616. matrix[x] = [];
  28617. }
  28618. if (!matrix[x][z]) {
  28619. matrix[x][z] = y;
  28620. }
  28621. matrix[x][z] = Math.max(y, matrix[x][z]);
  28622. }
  28623. for (var x = 0; x <= arraySize; ++x) {
  28624. if (!matrix[x]) {
  28625. var loc = 1;
  28626. while (!matrix[(x + loc) % arraySize]) {
  28627. loc++;
  28628. }
  28629. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28630. }
  28631. for (var z = 0; z <= arraySize; ++z) {
  28632. if (!matrix[x][z]) {
  28633. var loc = 1;
  28634. var newValue;
  28635. while (newValue === undefined) {
  28636. newValue = matrix[x][(z + loc++) % arraySize];
  28637. }
  28638. matrix[x][z] = newValue;
  28639. }
  28640. }
  28641. }
  28642. var shape = new CANNON.Heightfield(matrix, {
  28643. elementSize: elementSize
  28644. });
  28645. //For future reference, needed for body transformation
  28646. shape.minY = minY;
  28647. return shape;
  28648. };
  28649. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28650. var index;
  28651. var mat;
  28652. for (index = 0; index < this._physicsMaterials.length; index++) {
  28653. mat = this._physicsMaterials[index];
  28654. if (mat.friction === friction && mat.restitution === restitution) {
  28655. return mat;
  28656. }
  28657. }
  28658. var currentMat = new CANNON.Material("mat");
  28659. this._physicsMaterials.push(currentMat);
  28660. for (index = 0; index < this._physicsMaterials.length; index++) {
  28661. mat = this._physicsMaterials[index];
  28662. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28663. this._world.addContactMaterial(contactMaterial);
  28664. }
  28665. return currentMat;
  28666. };
  28667. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28668. if (!mesh.rotationQuaternion) {
  28669. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28670. }
  28671. // The delta between the mesh position and the mesh bounding box center
  28672. var bbox = mesh.getBoundingInfo().boundingBox;
  28673. var deltaPosition = mesh.position.subtract(bbox.center);
  28674. var deltaRotation;
  28675. var material = this._addMaterial(options.friction, options.restitution);
  28676. var body = new CANNON.Body({
  28677. mass: options.mass,
  28678. material: material,
  28679. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28680. });
  28681. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28682. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28683. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28684. //-90 DEG in X, precalculated
  28685. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28686. body.quaternion = body.quaternion.mult(tmpQ);
  28687. //Invert! (Precalculated, 90 deg in X)
  28688. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28689. }
  28690. //If it is a heightfield, if should be centered.
  28691. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28692. //calculate the correct body position:
  28693. var rotationQuaternion = mesh.rotationQuaternion;
  28694. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28695. mesh.computeWorldMatrix(true);
  28696. //get original center with no rotation
  28697. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28698. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28699. //rotation is back
  28700. mesh.rotationQuaternion = rotationQuaternion;
  28701. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28702. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28703. mesh.setPivotMatrix(p);
  28704. mesh.computeWorldMatrix(true);
  28705. //calculate the translation
  28706. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28707. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28708. //add it inverted to the delta
  28709. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28710. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28711. mesh.setPivotMatrix(oldPivot);
  28712. mesh.computeWorldMatrix(true);
  28713. }
  28714. //add the shape
  28715. body.addShape(shape);
  28716. this._world.add(body);
  28717. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28718. return body;
  28719. };
  28720. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28721. var initialMesh = parts[0].mesh;
  28722. this.unregisterMesh(initialMesh);
  28723. initialMesh.computeWorldMatrix(true);
  28724. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28725. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28726. for (var index = 1; index < parts.length; index++) {
  28727. var mesh = parts[index].mesh;
  28728. mesh.computeWorldMatrix(true);
  28729. var shape = this._createShape(mesh, parts[index].impostor);
  28730. var localPosition = mesh.position;
  28731. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28732. }
  28733. return body;
  28734. };
  28735. CannonJSPlugin.prototype._unbindBody = function (body) {
  28736. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28737. var registeredMesh = this._registeredMeshes[index];
  28738. if (registeredMesh.body === body) {
  28739. this._world.remove(registeredMesh.body);
  28740. registeredMesh.body = null;
  28741. registeredMesh.delta = null;
  28742. registeredMesh.deltaRotation = null;
  28743. }
  28744. }
  28745. };
  28746. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28747. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28748. var registeredMesh = this._registeredMeshes[index];
  28749. if (registeredMesh.mesh === mesh) {
  28750. // Remove body
  28751. if (registeredMesh.body) {
  28752. this._unbindBody(registeredMesh.body);
  28753. }
  28754. this._registeredMeshes.splice(index, 1);
  28755. return;
  28756. }
  28757. }
  28758. };
  28759. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28760. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28761. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28762. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28763. var registeredMesh = this._registeredMeshes[index];
  28764. if (registeredMesh.mesh === mesh) {
  28765. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28766. return;
  28767. }
  28768. }
  28769. };
  28770. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28771. var body1 = null, body2 = null;
  28772. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28773. var registeredMesh = this._registeredMeshes[index];
  28774. if (registeredMesh.mesh === mesh1) {
  28775. body1 = registeredMesh.body;
  28776. }
  28777. else if (registeredMesh.mesh === mesh2) {
  28778. body2 = registeredMesh.body;
  28779. }
  28780. }
  28781. if (!body1 || !body2) {
  28782. return false;
  28783. }
  28784. 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));
  28785. this._world.addConstraint(constraint);
  28786. return true;
  28787. };
  28788. CannonJSPlugin.prototype.dispose = function () {
  28789. while (this._registeredMeshes.length) {
  28790. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28791. }
  28792. };
  28793. CannonJSPlugin.prototype.isSupported = function () {
  28794. return window.CANNON !== undefined;
  28795. };
  28796. CannonJSPlugin.prototype.getWorldObject = function () {
  28797. return this._world;
  28798. };
  28799. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28800. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28801. var registeredMesh = this._registeredMeshes[index];
  28802. if (registeredMesh.mesh === mesh) {
  28803. return registeredMesh.body;
  28804. }
  28805. }
  28806. return null;
  28807. };
  28808. return CannonJSPlugin;
  28809. })();
  28810. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28811. })(BABYLON || (BABYLON = {}));
  28812. var BABYLON;
  28813. (function (BABYLON) {
  28814. var OimoJSPlugin = (function () {
  28815. function OimoJSPlugin() {
  28816. this._registeredMeshes = [];
  28817. this.name = "oimo";
  28818. /**
  28819. * Update the body position according to the mesh position
  28820. * @param mesh
  28821. */
  28822. this.updateBodyPosition = function (mesh) {
  28823. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28824. var registeredMesh = this._registeredMeshes[index];
  28825. var body = registeredMesh.body.body;
  28826. var updated = false;
  28827. var newPosition;
  28828. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28829. mesh.computeWorldMatrix(true);
  28830. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28831. updated = true;
  28832. }
  28833. else if (registeredMesh.mesh.parent === mesh) {
  28834. mesh.computeWorldMatrix(true);
  28835. registeredMesh.mesh.computeWorldMatrix(true);
  28836. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28837. updated = true;
  28838. }
  28839. if (updated) {
  28840. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28841. body.setQuaternion(mesh.rotationQuaternion);
  28842. body.sleeping = false;
  28843. //force Oimo to update the body's position
  28844. body.updatePosition(1);
  28845. }
  28846. }
  28847. };
  28848. }
  28849. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28850. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28851. };
  28852. OimoJSPlugin.prototype.initialize = function (iterations) {
  28853. this._world = new OIMO.World(null, null, iterations);
  28854. this._world.clear();
  28855. };
  28856. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28857. this._gravity = this._world.gravity = gravity;
  28858. };
  28859. OimoJSPlugin.prototype.getGravity = function () {
  28860. return this._gravity;
  28861. };
  28862. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28863. this.unregisterMesh(mesh);
  28864. if (!mesh.rotationQuaternion) {
  28865. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28866. }
  28867. mesh.computeWorldMatrix(true);
  28868. var bbox = mesh.getBoundingInfo().boundingBox;
  28869. // The delta between the mesh position and the mesh bounding box center
  28870. var deltaPosition = mesh.position.subtract(bbox.center);
  28871. //calculate rotation to fit Oimo's needs (Euler...)
  28872. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28873. //get the correct bounding box
  28874. var oldQuaternion = mesh.rotationQuaternion;
  28875. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28876. mesh.computeWorldMatrix(true);
  28877. var bodyConfig = {
  28878. name: mesh.uniqueId,
  28879. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28880. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28881. move: options.mass != 0,
  28882. config: [options.mass, options.friction, options.restitution],
  28883. world: this._world
  28884. };
  28885. // register mesh
  28886. switch (impostor) {
  28887. case BABYLON.PhysicsEngine.SphereImpostor:
  28888. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28889. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28890. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28891. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28892. bodyConfig.type = 'sphere';
  28893. bodyConfig.size = [size];
  28894. break;
  28895. case BABYLON.PhysicsEngine.PlaneImpostor:
  28896. //Oimo "fakes" a cylinder as a box, so why don't we!
  28897. case BABYLON.PhysicsEngine.CylinderImpostor:
  28898. case BABYLON.PhysicsEngine.BoxImpostor:
  28899. var min = bbox.minimumWorld;
  28900. var max = bbox.maximumWorld;
  28901. var box = max.subtract(min);
  28902. var sizeX = this._checkWithEpsilon(box.x);
  28903. var sizeY = this._checkWithEpsilon(box.y);
  28904. var sizeZ = this._checkWithEpsilon(box.z);
  28905. bodyConfig.type = 'box';
  28906. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28907. break;
  28908. }
  28909. var body = new OIMO.Body(bodyConfig);
  28910. //We have to access the rigid body's properties to set the quaternion.
  28911. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28912. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28913. //TEST
  28914. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28915. //update the internal rotation matrix
  28916. //body.body.syncShapes();
  28917. this._registeredMeshes.push({
  28918. mesh: mesh,
  28919. body: body,
  28920. delta: deltaPosition
  28921. });
  28922. //for the sake of consistency.
  28923. mesh.rotationQuaternion = oldQuaternion;
  28924. return body;
  28925. };
  28926. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28927. var types = [], sizes = [], positions = [], rotations = [];
  28928. var initialMesh = parts[0].mesh;
  28929. for (var index = 0; index < parts.length; index++) {
  28930. var part = parts[index];
  28931. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28932. types.push(bodyParameters.type);
  28933. sizes.push.apply(sizes, bodyParameters.size);
  28934. positions.push.apply(positions, bodyParameters.pos);
  28935. rotations.push.apply(rotations, bodyParameters.rot);
  28936. }
  28937. var body = new OIMO.Body({
  28938. name: initialMesh.uniqueId,
  28939. type: types,
  28940. size: sizes,
  28941. pos: positions,
  28942. rot: rotations,
  28943. move: options.mass != 0,
  28944. config: [options.mass, options.friction, options.restitution],
  28945. world: this._world
  28946. });
  28947. //Reset the body's rotation to be of the initial mesh's.
  28948. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28949. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28950. this._registeredMeshes.push({
  28951. mesh: initialMesh,
  28952. body: body
  28953. });
  28954. return body;
  28955. };
  28956. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28957. var mesh = part.mesh;
  28958. if (!mesh.rotationQuaternion) {
  28959. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28960. }
  28961. // We need the bounding box/sphere info to compute the physics body
  28962. mesh.computeWorldMatrix(true);
  28963. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28964. var bodyParameters = {
  28965. name: mesh.uniqueId,
  28966. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28967. //A bug in Oimo (Body class) prevents us from using rot directly.
  28968. rot: [0, 0, 0],
  28969. //For future reference, if the bug will ever be fixed.
  28970. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28971. };
  28972. var oldQuaternion = mesh.rotationQuaternion;
  28973. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28974. mesh.computeWorldMatrix(true);
  28975. switch (part.impostor) {
  28976. case BABYLON.PhysicsEngine.SphereImpostor:
  28977. var bbox = mesh.getBoundingInfo().boundingBox;
  28978. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28979. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28980. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28981. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28982. bodyParameters.type = 'sphere';
  28983. bodyParameters.size = [size, size, size];
  28984. break;
  28985. case BABYLON.PhysicsEngine.PlaneImpostor:
  28986. case BABYLON.PhysicsEngine.CylinderImpostor:
  28987. case BABYLON.PhysicsEngine.BoxImpostor:
  28988. bbox = mesh.getBoundingInfo().boundingBox;
  28989. var min = bbox.minimumWorld;
  28990. var max = bbox.maximumWorld;
  28991. var box = max.subtract(min);
  28992. var sizeX = this._checkWithEpsilon(box.x);
  28993. var sizeY = this._checkWithEpsilon(box.y);
  28994. var sizeZ = this._checkWithEpsilon(box.z);
  28995. bodyParameters.type = 'box';
  28996. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28997. break;
  28998. }
  28999. mesh.rotationQuaternion = oldQuaternion;
  29000. return bodyParameters;
  29001. };
  29002. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29003. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29004. var registeredMesh = this._registeredMeshes[index];
  29005. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29006. if (registeredMesh.body) {
  29007. this._world.removeRigidBody(registeredMesh.body.body);
  29008. this._unbindBody(registeredMesh.body);
  29009. }
  29010. this._registeredMeshes.splice(index, 1);
  29011. return;
  29012. }
  29013. }
  29014. };
  29015. OimoJSPlugin.prototype._unbindBody = function (body) {
  29016. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29017. var registeredMesh = this._registeredMeshes[index];
  29018. if (registeredMesh.body === body) {
  29019. registeredMesh.body = null;
  29020. }
  29021. }
  29022. };
  29023. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29024. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29025. var registeredMesh = this._registeredMeshes[index];
  29026. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29027. // Get object mass to have a behaviour similar to cannon.js
  29028. var mass = registeredMesh.body.body.massInfo.mass;
  29029. // The force is scaled with the mass of object
  29030. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29031. return;
  29032. }
  29033. }
  29034. };
  29035. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29036. var body1 = null, body2 = null;
  29037. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29038. var registeredMesh = this._registeredMeshes[index];
  29039. if (registeredMesh.mesh === mesh1) {
  29040. body1 = registeredMesh.body.body;
  29041. }
  29042. else if (registeredMesh.mesh === mesh2) {
  29043. body2 = registeredMesh.body.body;
  29044. }
  29045. }
  29046. if (!body1 || !body2) {
  29047. return false;
  29048. }
  29049. if (!options) {
  29050. options = {};
  29051. }
  29052. new OIMO.Link({
  29053. type: options.type,
  29054. body1: body1,
  29055. body2: body2,
  29056. min: options.min,
  29057. max: options.max,
  29058. axe1: options.axe1,
  29059. axe2: options.axe2,
  29060. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29061. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29062. collision: options.collision,
  29063. spring: options.spring,
  29064. world: this._world
  29065. });
  29066. return true;
  29067. };
  29068. OimoJSPlugin.prototype.dispose = function () {
  29069. this._world.clear();
  29070. while (this._registeredMeshes.length) {
  29071. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29072. }
  29073. };
  29074. OimoJSPlugin.prototype.isSupported = function () {
  29075. return OIMO !== undefined;
  29076. };
  29077. OimoJSPlugin.prototype.getWorldObject = function () {
  29078. return this._world;
  29079. };
  29080. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29081. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29082. var registeredMesh = this._registeredMeshes[index];
  29083. if (registeredMesh.mesh === mesh) {
  29084. return registeredMesh.body;
  29085. }
  29086. }
  29087. return null;
  29088. };
  29089. OimoJSPlugin.prototype._getLastShape = function (body) {
  29090. var lastShape = body.shapes;
  29091. while (lastShape.next) {
  29092. lastShape = lastShape.next;
  29093. }
  29094. return lastShape;
  29095. };
  29096. OimoJSPlugin.prototype.runOneStep = function (time) {
  29097. this._world.step();
  29098. // Update the position of all registered meshes
  29099. var i = this._registeredMeshes.length;
  29100. var m;
  29101. while (i--) {
  29102. var body = this._registeredMeshes[i].body.body;
  29103. var mesh = this._registeredMeshes[i].mesh;
  29104. if (!this._registeredMeshes[i].delta) {
  29105. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29106. }
  29107. if (!body.sleeping) {
  29108. //TODO check that
  29109. if (body.shapes.next) {
  29110. var parentShape = this._getLastShape(body);
  29111. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29112. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29113. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29114. }
  29115. else {
  29116. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29117. }
  29118. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29119. mesh.computeWorldMatrix();
  29120. }
  29121. //check if the collide callback is set.
  29122. if (mesh.onPhysicsCollide) {
  29123. var meshUniqueName = mesh.uniqueId;
  29124. var contact = this._world.contacts;
  29125. while (contact !== null) {
  29126. //is this body colliding with any other?
  29127. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29128. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29129. //get the mesh and execute the callback
  29130. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29131. if (otherMesh)
  29132. mesh.onPhysicsCollide(otherMesh);
  29133. }
  29134. contact = contact.next;
  29135. }
  29136. }
  29137. }
  29138. };
  29139. return OimoJSPlugin;
  29140. })();
  29141. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29142. })(BABYLON || (BABYLON = {}));
  29143. var BABYLON;
  29144. (function (BABYLON) {
  29145. var DisplayPassPostProcess = (function (_super) {
  29146. __extends(DisplayPassPostProcess, _super);
  29147. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29148. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29149. }
  29150. return DisplayPassPostProcess;
  29151. })(BABYLON.PostProcess);
  29152. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29153. })(BABYLON || (BABYLON = {}));
  29154. var BABYLON;
  29155. (function (BABYLON) {
  29156. var SimplificationSettings = (function () {
  29157. function SimplificationSettings(quality, distance, optimizeMesh) {
  29158. this.quality = quality;
  29159. this.distance = distance;
  29160. this.optimizeMesh = optimizeMesh;
  29161. }
  29162. return SimplificationSettings;
  29163. })();
  29164. BABYLON.SimplificationSettings = SimplificationSettings;
  29165. var SimplificationQueue = (function () {
  29166. function SimplificationQueue() {
  29167. this.running = false;
  29168. this._simplificationArray = [];
  29169. }
  29170. SimplificationQueue.prototype.addTask = function (task) {
  29171. this._simplificationArray.push(task);
  29172. };
  29173. SimplificationQueue.prototype.executeNext = function () {
  29174. var task = this._simplificationArray.pop();
  29175. if (task) {
  29176. this.running = true;
  29177. this.runSimplification(task);
  29178. }
  29179. else {
  29180. this.running = false;
  29181. }
  29182. };
  29183. SimplificationQueue.prototype.runSimplification = function (task) {
  29184. var _this = this;
  29185. if (task.parallelProcessing) {
  29186. //parallel simplifier
  29187. task.settings.forEach(function (setting) {
  29188. var simplifier = _this.getSimplifier(task);
  29189. simplifier.simplify(setting, function (newMesh) {
  29190. task.mesh.addLODLevel(setting.distance, newMesh);
  29191. newMesh.isVisible = true;
  29192. //check if it is the last
  29193. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29194. //all done, run the success callback.
  29195. task.successCallback();
  29196. }
  29197. _this.executeNext();
  29198. });
  29199. });
  29200. }
  29201. else {
  29202. //single simplifier.
  29203. var simplifier = this.getSimplifier(task);
  29204. var runDecimation = function (setting, callback) {
  29205. simplifier.simplify(setting, function (newMesh) {
  29206. task.mesh.addLODLevel(setting.distance, newMesh);
  29207. newMesh.isVisible = true;
  29208. //run the next quality level
  29209. callback();
  29210. });
  29211. };
  29212. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29213. runDecimation(task.settings[loop.index], function () {
  29214. loop.executeNext();
  29215. });
  29216. }, function () {
  29217. //execution ended, run the success callback.
  29218. if (task.successCallback) {
  29219. task.successCallback();
  29220. }
  29221. _this.executeNext();
  29222. });
  29223. }
  29224. };
  29225. SimplificationQueue.prototype.getSimplifier = function (task) {
  29226. switch (task.simplificationType) {
  29227. case SimplificationType.QUADRATIC:
  29228. default:
  29229. return new QuadraticErrorSimplification(task.mesh);
  29230. }
  29231. };
  29232. return SimplificationQueue;
  29233. })();
  29234. BABYLON.SimplificationQueue = SimplificationQueue;
  29235. /**
  29236. * The implemented types of simplification.
  29237. * At the moment only Quadratic Error Decimation is implemented.
  29238. */
  29239. (function (SimplificationType) {
  29240. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29241. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29242. var SimplificationType = BABYLON.SimplificationType;
  29243. var DecimationTriangle = (function () {
  29244. function DecimationTriangle(vertices) {
  29245. this.vertices = vertices;
  29246. this.error = new Array(4);
  29247. this.deleted = false;
  29248. this.isDirty = false;
  29249. this.deletePending = false;
  29250. this.borderFactor = 0;
  29251. }
  29252. return DecimationTriangle;
  29253. })();
  29254. BABYLON.DecimationTriangle = DecimationTriangle;
  29255. var DecimationVertex = (function () {
  29256. function DecimationVertex(position, id) {
  29257. this.position = position;
  29258. this.id = id;
  29259. this.isBorder = true;
  29260. this.q = new QuadraticMatrix();
  29261. this.triangleCount = 0;
  29262. this.triangleStart = 0;
  29263. this.originalOffsets = [];
  29264. }
  29265. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29266. this.position.copyFrom(newPosition);
  29267. };
  29268. return DecimationVertex;
  29269. })();
  29270. BABYLON.DecimationVertex = DecimationVertex;
  29271. var QuadraticMatrix = (function () {
  29272. function QuadraticMatrix(data) {
  29273. this.data = new Array(10);
  29274. for (var i = 0; i < 10; ++i) {
  29275. if (data && data[i]) {
  29276. this.data[i] = data[i];
  29277. }
  29278. else {
  29279. this.data[i] = 0;
  29280. }
  29281. }
  29282. }
  29283. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29284. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29285. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29286. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29287. return det;
  29288. };
  29289. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29290. for (var i = 0; i < 10; ++i) {
  29291. this.data[i] += matrix.data[i];
  29292. }
  29293. };
  29294. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29295. for (var i = 0; i < 10; ++i) {
  29296. this.data[i] += data[i];
  29297. }
  29298. };
  29299. QuadraticMatrix.prototype.add = function (matrix) {
  29300. var m = new QuadraticMatrix();
  29301. for (var i = 0; i < 10; ++i) {
  29302. m.data[i] = this.data[i] + matrix.data[i];
  29303. }
  29304. return m;
  29305. };
  29306. QuadraticMatrix.FromData = function (a, b, c, d) {
  29307. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29308. };
  29309. //returning an array to avoid garbage collection
  29310. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29311. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29312. };
  29313. return QuadraticMatrix;
  29314. })();
  29315. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29316. var Reference = (function () {
  29317. function Reference(vertexId, triangleId) {
  29318. this.vertexId = vertexId;
  29319. this.triangleId = triangleId;
  29320. }
  29321. return Reference;
  29322. })();
  29323. BABYLON.Reference = Reference;
  29324. /**
  29325. * An implementation of the Quadratic Error simplification algorithm.
  29326. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29327. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29328. * @author RaananW
  29329. */
  29330. var QuadraticErrorSimplification = (function () {
  29331. function QuadraticErrorSimplification(_mesh) {
  29332. this._mesh = _mesh;
  29333. this.initialized = false;
  29334. this.syncIterations = 5000;
  29335. this.aggressiveness = 7;
  29336. this.decimationIterations = 100;
  29337. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29338. }
  29339. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29340. var _this = this;
  29341. this.initDecimatedMesh();
  29342. //iterating through the submeshes array, one after the other.
  29343. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29344. _this.initWithMesh(loop.index, function () {
  29345. _this.runDecimation(settings, loop.index, function () {
  29346. loop.executeNext();
  29347. });
  29348. }, settings.optimizeMesh);
  29349. }, function () {
  29350. setTimeout(function () {
  29351. successCallback(_this._reconstructedMesh);
  29352. }, 0);
  29353. });
  29354. };
  29355. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29356. var _this = this;
  29357. var gCount = 0;
  29358. triangle.vertices.forEach(function (vertex) {
  29359. var count = 0;
  29360. var vPos = vertex.position;
  29361. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29362. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29363. ++count;
  29364. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29365. ++count;
  29366. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29367. ++count;
  29368. if (count > 1) {
  29369. ++gCount;
  29370. }
  29371. ;
  29372. });
  29373. if (gCount > 1) {
  29374. console.log(triangle, gCount);
  29375. }
  29376. return gCount > 1;
  29377. };
  29378. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29379. var _this = this;
  29380. var targetCount = ~~(this.triangles.length * settings.quality);
  29381. var deletedTriangles = 0;
  29382. var triangleCount = this.triangles.length;
  29383. var iterationFunction = function (iteration, callback) {
  29384. setTimeout(function () {
  29385. if (iteration % 5 === 0) {
  29386. _this.updateMesh(iteration === 0);
  29387. }
  29388. for (var i = 0; i < _this.triangles.length; ++i) {
  29389. _this.triangles[i].isDirty = false;
  29390. }
  29391. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29392. var trianglesIterator = function (i) {
  29393. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29394. var t = _this.triangles[tIdx];
  29395. if (!t)
  29396. return;
  29397. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29398. return;
  29399. }
  29400. for (var j = 0; j < 3; ++j) {
  29401. if (t.error[j] < threshold) {
  29402. var deleted0 = [];
  29403. var deleted1 = [];
  29404. var v0 = t.vertices[j];
  29405. var v1 = t.vertices[(j + 1) % 3];
  29406. if (v0.isBorder !== v1.isBorder)
  29407. continue;
  29408. var p = BABYLON.Vector3.Zero();
  29409. var n = BABYLON.Vector3.Zero();
  29410. var uv = BABYLON.Vector2.Zero();
  29411. var color = new BABYLON.Color4(0, 0, 0, 1);
  29412. _this.calculateError(v0, v1, p, n, uv, color);
  29413. var delTr = [];
  29414. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29415. continue;
  29416. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29417. continue;
  29418. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29419. continue;
  29420. var uniqueArray = [];
  29421. delTr.forEach(function (deletedT) {
  29422. if (uniqueArray.indexOf(deletedT) === -1) {
  29423. deletedT.deletePending = true;
  29424. uniqueArray.push(deletedT);
  29425. }
  29426. });
  29427. if (uniqueArray.length % 2 !== 0) {
  29428. continue;
  29429. }
  29430. v0.q = v1.q.add(v0.q);
  29431. v0.updatePosition(p);
  29432. var tStart = _this.references.length;
  29433. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29434. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29435. var tCount = _this.references.length - tStart;
  29436. if (tCount <= v0.triangleCount) {
  29437. if (tCount) {
  29438. for (var c = 0; c < tCount; c++) {
  29439. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29440. }
  29441. }
  29442. }
  29443. else {
  29444. v0.triangleStart = tStart;
  29445. }
  29446. v0.triangleCount = tCount;
  29447. break;
  29448. }
  29449. }
  29450. };
  29451. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29452. }, 0);
  29453. };
  29454. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29455. if (triangleCount - deletedTriangles <= targetCount)
  29456. loop.breakLoop();
  29457. else {
  29458. iterationFunction(loop.index, function () {
  29459. loop.executeNext();
  29460. });
  29461. }
  29462. }, function () {
  29463. setTimeout(function () {
  29464. //reconstruct this part of the mesh
  29465. _this.reconstructMesh(submeshIndex);
  29466. successCallback();
  29467. }, 0);
  29468. });
  29469. };
  29470. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29471. var _this = this;
  29472. this.vertices = [];
  29473. this.triangles = [];
  29474. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29475. var indices = this._mesh.getIndices();
  29476. var submesh = this._mesh.subMeshes[submeshIndex];
  29477. var findInVertices = function (positionToSearch) {
  29478. if (optimizeMesh) {
  29479. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29480. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29481. return _this.vertices[ii];
  29482. }
  29483. }
  29484. }
  29485. return null;
  29486. };
  29487. var vertexReferences = [];
  29488. var vertexInit = function (i) {
  29489. var offset = i + submesh.verticesStart;
  29490. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29491. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29492. vertex.originalOffsets.push(offset);
  29493. if (vertex.id === _this.vertices.length) {
  29494. _this.vertices.push(vertex);
  29495. }
  29496. vertexReferences.push(vertex.id);
  29497. };
  29498. //var totalVertices = mesh.getTotalVertices();
  29499. var totalVertices = submesh.verticesCount;
  29500. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29501. var indicesInit = function (i) {
  29502. var offset = (submesh.indexStart / 3) + i;
  29503. var pos = (offset * 3);
  29504. var i0 = indices[pos + 0];
  29505. var i1 = indices[pos + 1];
  29506. var i2 = indices[pos + 2];
  29507. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29508. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29509. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29510. var triangle = new DecimationTriangle([v0, v1, v2]);
  29511. triangle.originalOffset = pos;
  29512. _this.triangles.push(triangle);
  29513. };
  29514. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29515. _this.init(callback);
  29516. });
  29517. });
  29518. };
  29519. QuadraticErrorSimplification.prototype.init = function (callback) {
  29520. var _this = this;
  29521. var triangleInit1 = function (i) {
  29522. var t = _this.triangles[i];
  29523. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29524. for (var j = 0; j < 3; j++) {
  29525. 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))));
  29526. }
  29527. };
  29528. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29529. var triangleInit2 = function (i) {
  29530. var t = _this.triangles[i];
  29531. for (var j = 0; j < 3; ++j) {
  29532. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29533. }
  29534. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29535. };
  29536. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29537. _this.initialized = true;
  29538. callback();
  29539. });
  29540. });
  29541. };
  29542. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29543. var newTriangles = [];
  29544. var i;
  29545. for (i = 0; i < this.vertices.length; ++i) {
  29546. this.vertices[i].triangleCount = 0;
  29547. }
  29548. var t;
  29549. var j;
  29550. for (i = 0; i < this.triangles.length; ++i) {
  29551. if (!this.triangles[i].deleted) {
  29552. t = this.triangles[i];
  29553. for (j = 0; j < 3; ++j) {
  29554. t.vertices[j].triangleCount = 1;
  29555. }
  29556. newTriangles.push(t);
  29557. }
  29558. }
  29559. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29560. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29561. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29562. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29563. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29564. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29565. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29566. var vertexCount = 0;
  29567. for (i = 0; i < this.vertices.length; ++i) {
  29568. var vertex = this.vertices[i];
  29569. vertex.id = vertexCount;
  29570. if (vertex.triangleCount) {
  29571. vertex.originalOffsets.forEach(function (originalOffset) {
  29572. newPositionData.push(vertex.position.x);
  29573. newPositionData.push(vertex.position.y);
  29574. newPositionData.push(vertex.position.z);
  29575. newNormalData.push(normalData[originalOffset * 3]);
  29576. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29577. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29578. if (uvs && uvs.length) {
  29579. newUVsData.push(uvs[(originalOffset * 2)]);
  29580. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29581. }
  29582. else if (colorsData && colorsData.length) {
  29583. newColorsData.push(colorsData[(originalOffset * 4)]);
  29584. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29585. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29586. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29587. }
  29588. ++vertexCount;
  29589. });
  29590. }
  29591. }
  29592. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29593. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29594. var submeshesArray = this._reconstructedMesh.subMeshes;
  29595. this._reconstructedMesh.subMeshes = [];
  29596. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29597. var originalIndices = this._mesh.getIndices();
  29598. for (i = 0; i < newTriangles.length; ++i) {
  29599. t = newTriangles[i]; //now get the new referencing point for each vertex
  29600. [0, 1, 2].forEach(function (idx) {
  29601. var id = originalIndices[t.originalOffset + idx];
  29602. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29603. if (offset < 0)
  29604. offset = 0;
  29605. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29606. });
  29607. }
  29608. //overwriting the old vertex buffers and indices.
  29609. this._reconstructedMesh.setIndices(newIndicesArray);
  29610. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29611. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29612. if (newUVsData.length > 0)
  29613. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29614. if (newColorsData.length > 0)
  29615. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29616. //create submesh
  29617. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29618. if (submeshIndex > 0) {
  29619. this._reconstructedMesh.subMeshes = [];
  29620. submeshesArray.forEach(function (submesh) {
  29621. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29622. });
  29623. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29624. }
  29625. };
  29626. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29627. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29628. this._reconstructedMesh.material = this._mesh.material;
  29629. this._reconstructedMesh.parent = this._mesh.parent;
  29630. this._reconstructedMesh.isVisible = false;
  29631. };
  29632. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29633. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29634. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29635. if (t.deleted)
  29636. continue;
  29637. var s = this.references[vertex1.triangleStart + i].vertexId;
  29638. var v1 = t.vertices[(s + 1) % 3];
  29639. var v2 = t.vertices[(s + 2) % 3];
  29640. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29641. deletedArray[i] = true;
  29642. delTr.push(t);
  29643. continue;
  29644. }
  29645. var d1 = v1.position.subtract(point);
  29646. d1 = d1.normalize();
  29647. var d2 = v2.position.subtract(point);
  29648. d2 = d2.normalize();
  29649. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29650. return true;
  29651. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29652. deletedArray[i] = false;
  29653. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29654. return true;
  29655. }
  29656. return false;
  29657. };
  29658. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29659. var newDeleted = deletedTriangles;
  29660. for (var i = 0; i < vertex.triangleCount; ++i) {
  29661. var ref = this.references[vertex.triangleStart + i];
  29662. var t = this.triangles[ref.triangleId];
  29663. if (t.deleted)
  29664. continue;
  29665. if (deletedArray[i] && t.deletePending) {
  29666. t.deleted = true;
  29667. newDeleted++;
  29668. continue;
  29669. }
  29670. t.vertices[ref.vertexId] = origVertex;
  29671. t.isDirty = true;
  29672. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29673. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29674. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29675. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29676. this.references.push(ref);
  29677. }
  29678. return newDeleted;
  29679. };
  29680. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29681. for (var i = 0; i < this.vertices.length; ++i) {
  29682. var vCount = [];
  29683. var vId = [];
  29684. var v = this.vertices[i];
  29685. var j;
  29686. for (j = 0; j < v.triangleCount; ++j) {
  29687. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29688. for (var ii = 0; ii < 3; ii++) {
  29689. var ofs = 0;
  29690. var vv = triangle.vertices[ii];
  29691. while (ofs < vCount.length) {
  29692. if (vId[ofs] === vv.id)
  29693. break;
  29694. ++ofs;
  29695. }
  29696. if (ofs === vCount.length) {
  29697. vCount.push(1);
  29698. vId.push(vv.id);
  29699. }
  29700. else {
  29701. vCount[ofs]++;
  29702. }
  29703. }
  29704. }
  29705. for (j = 0; j < vCount.length; ++j) {
  29706. if (vCount[j] === 1) {
  29707. this.vertices[vId[j]].isBorder = true;
  29708. }
  29709. else {
  29710. this.vertices[vId[j]].isBorder = false;
  29711. }
  29712. }
  29713. }
  29714. };
  29715. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29716. if (identifyBorders === void 0) { identifyBorders = false; }
  29717. var i;
  29718. if (!identifyBorders) {
  29719. var newTrianglesVector = [];
  29720. for (i = 0; i < this.triangles.length; ++i) {
  29721. if (!this.triangles[i].deleted) {
  29722. newTrianglesVector.push(this.triangles[i]);
  29723. }
  29724. }
  29725. this.triangles = newTrianglesVector;
  29726. }
  29727. for (i = 0; i < this.vertices.length; ++i) {
  29728. this.vertices[i].triangleCount = 0;
  29729. this.vertices[i].triangleStart = 0;
  29730. }
  29731. var t;
  29732. var j;
  29733. var v;
  29734. for (i = 0; i < this.triangles.length; ++i) {
  29735. t = this.triangles[i];
  29736. for (j = 0; j < 3; ++j) {
  29737. v = t.vertices[j];
  29738. v.triangleCount++;
  29739. }
  29740. }
  29741. var tStart = 0;
  29742. for (i = 0; i < this.vertices.length; ++i) {
  29743. this.vertices[i].triangleStart = tStart;
  29744. tStart += this.vertices[i].triangleCount;
  29745. this.vertices[i].triangleCount = 0;
  29746. }
  29747. var newReferences = new Array(this.triangles.length * 3);
  29748. for (i = 0; i < this.triangles.length; ++i) {
  29749. t = this.triangles[i];
  29750. for (j = 0; j < 3; ++j) {
  29751. v = t.vertices[j];
  29752. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29753. v.triangleCount++;
  29754. }
  29755. }
  29756. this.references = newReferences;
  29757. if (identifyBorders) {
  29758. this.identifyBorder();
  29759. }
  29760. };
  29761. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29762. var x = point.x;
  29763. var y = point.y;
  29764. var z = point.z;
  29765. 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
  29766. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29767. };
  29768. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29769. var q = vertex1.q.add(vertex2.q);
  29770. var border = vertex1.isBorder && vertex2.isBorder;
  29771. var error = 0;
  29772. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29773. if (qDet !== 0 && !border) {
  29774. if (!pointResult) {
  29775. pointResult = BABYLON.Vector3.Zero();
  29776. }
  29777. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29778. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29779. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29780. error = this.vertexError(q, pointResult);
  29781. }
  29782. else {
  29783. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29784. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29785. var error1 = this.vertexError(q, vertex1.position);
  29786. var error2 = this.vertexError(q, vertex2.position);
  29787. var error3 = this.vertexError(q, p3);
  29788. error = Math.min(error1, error2, error3);
  29789. if (error === error1) {
  29790. if (pointResult) {
  29791. pointResult.copyFrom(vertex1.position);
  29792. }
  29793. }
  29794. else if (error === error2) {
  29795. if (pointResult) {
  29796. pointResult.copyFrom(vertex2.position);
  29797. }
  29798. }
  29799. else {
  29800. if (pointResult) {
  29801. pointResult.copyFrom(p3);
  29802. }
  29803. }
  29804. }
  29805. return error;
  29806. };
  29807. return QuadraticErrorSimplification;
  29808. })();
  29809. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29810. })(BABYLON || (BABYLON = {}));
  29811. var BABYLON;
  29812. (function (BABYLON) {
  29813. var serializedGeometries = [];
  29814. var serializeGeometry = function (geometry, serializationGeometries) {
  29815. if (serializedGeometries[geometry.id]) {
  29816. return;
  29817. }
  29818. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29819. serializationGeometries.boxes.push(geometry.serialize());
  29820. }
  29821. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29822. serializationGeometries.spheres.push(geometry.serialize());
  29823. }
  29824. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29825. serializationGeometries.cylinders.push(geometry.serialize());
  29826. }
  29827. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29828. serializationGeometries.toruses.push(geometry.serialize());
  29829. }
  29830. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29831. serializationGeometries.grounds.push(geometry.serialize());
  29832. }
  29833. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29834. serializationGeometries.planes.push(geometry.serialize());
  29835. }
  29836. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29837. serializationGeometries.torusKnots.push(geometry.serialize());
  29838. }
  29839. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29840. throw new Error("Unknown primitive type");
  29841. }
  29842. else {
  29843. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  29844. }
  29845. serializedGeometries[geometry.id] = true;
  29846. };
  29847. var serializeMesh = function (mesh, serializationScene) {
  29848. var serializationObject = {};
  29849. serializationObject.name = mesh.name;
  29850. serializationObject.id = mesh.id;
  29851. if (BABYLON.Tags.HasTags(mesh)) {
  29852. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29853. }
  29854. serializationObject.position = mesh.position.asArray();
  29855. if (mesh.rotationQuaternion) {
  29856. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29857. }
  29858. else if (mesh.rotation) {
  29859. serializationObject.rotation = mesh.rotation.asArray();
  29860. }
  29861. serializationObject.scaling = mesh.scaling.asArray();
  29862. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29863. serializationObject.isEnabled = mesh.isEnabled();
  29864. serializationObject.isVisible = mesh.isVisible;
  29865. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29866. serializationObject.pickable = mesh.isPickable;
  29867. serializationObject.receiveShadows = mesh.receiveShadows;
  29868. serializationObject.billboardMode = mesh.billboardMode;
  29869. serializationObject.visibility = mesh.visibility;
  29870. serializationObject.checkCollisions = mesh.checkCollisions;
  29871. // Parent
  29872. if (mesh.parent) {
  29873. serializationObject.parentId = mesh.parent.id;
  29874. }
  29875. // Geometry
  29876. var geometry = mesh._geometry;
  29877. if (geometry) {
  29878. var geometryId = geometry.id;
  29879. serializationObject.geometryId = geometryId;
  29880. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29881. // 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
  29882. serializeGeometry(geometry, serializationScene.geometries);
  29883. }
  29884. // SubMeshes
  29885. serializationObject.subMeshes = [];
  29886. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29887. var subMesh = mesh.subMeshes[subIndex];
  29888. serializationObject.subMeshes.push({
  29889. materialIndex: subMesh.materialIndex,
  29890. verticesStart: subMesh.verticesStart,
  29891. verticesCount: subMesh.verticesCount,
  29892. indexStart: subMesh.indexStart,
  29893. indexCount: subMesh.indexCount
  29894. });
  29895. }
  29896. }
  29897. // Material
  29898. if (mesh.material) {
  29899. serializationObject.materialId = mesh.material.id;
  29900. }
  29901. else {
  29902. mesh.material = null;
  29903. }
  29904. // Skeleton
  29905. if (mesh.skeleton) {
  29906. serializationObject.skeletonId = mesh.skeleton.id;
  29907. }
  29908. // Physics
  29909. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29910. serializationObject.physicsMass = mesh.getPhysicsMass();
  29911. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29912. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29913. switch (mesh.getPhysicsImpostor()) {
  29914. case BABYLON.PhysicsEngine.BoxImpostor:
  29915. serializationObject.physicsImpostor = 1;
  29916. break;
  29917. case BABYLON.PhysicsEngine.SphereImpostor:
  29918. serializationObject.physicsImpostor = 2;
  29919. break;
  29920. }
  29921. }
  29922. // Instances
  29923. serializationObject.instances = [];
  29924. for (var index = 0; index < mesh.instances.length; index++) {
  29925. var instance = mesh.instances[index];
  29926. var serializationInstance = {
  29927. name: instance.name,
  29928. position: instance.position.asArray(),
  29929. rotation: instance.rotation.asArray(),
  29930. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29931. scaling: instance.scaling.asArray()
  29932. };
  29933. serializationObject.instances.push(serializationInstance);
  29934. // Animations
  29935. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29936. }
  29937. // Animations
  29938. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  29939. // Layer mask
  29940. serializationObject.layerMask = mesh.layerMask;
  29941. return serializationObject;
  29942. };
  29943. var finalizeSingleMesh = function (mesh, serializationObject) {
  29944. //only works if the mesh is already loaded
  29945. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29946. //serialize material
  29947. if (mesh.material) {
  29948. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29949. serializationObject.materials = serializationObject.materials || [];
  29950. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29951. serializationObject.materials.push(mesh.material.serialize());
  29952. }
  29953. }
  29954. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29955. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29956. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29957. serializationObject.multiMaterials.push(mesh.material.serialize());
  29958. }
  29959. }
  29960. }
  29961. //serialize geometry
  29962. var geometry = mesh._geometry;
  29963. if (geometry) {
  29964. if (!serializationObject.geometries) {
  29965. serializationObject.geometries = {};
  29966. serializationObject.geometries.boxes = [];
  29967. serializationObject.geometries.spheres = [];
  29968. serializationObject.geometries.cylinders = [];
  29969. serializationObject.geometries.toruses = [];
  29970. serializationObject.geometries.grounds = [];
  29971. serializationObject.geometries.planes = [];
  29972. serializationObject.geometries.torusKnots = [];
  29973. serializationObject.geometries.vertexData = [];
  29974. }
  29975. serializeGeometry(geometry, serializationObject.geometries);
  29976. }
  29977. // Skeletons
  29978. if (mesh.skeleton) {
  29979. serializationObject.skeletons = serializationObject.skeletons || [];
  29980. serializationObject.skeletons.push(mesh.skeleton.serialize());
  29981. }
  29982. //serialize the actual mesh
  29983. serializationObject.meshes = serializationObject.meshes || [];
  29984. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29985. }
  29986. };
  29987. var SceneSerializer = (function () {
  29988. function SceneSerializer() {
  29989. }
  29990. SceneSerializer.Serialize = function (scene) {
  29991. var serializationObject = {};
  29992. // Scene
  29993. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29994. serializationObject.autoClear = scene.autoClear;
  29995. serializationObject.clearColor = scene.clearColor.asArray();
  29996. serializationObject.ambientColor = scene.ambientColor.asArray();
  29997. serializationObject.gravity = scene.gravity.asArray();
  29998. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  29999. serializationObject.workerCollisions = scene.workerCollisions;
  30000. // Fog
  30001. if (scene.fogMode && scene.fogMode !== 0) {
  30002. serializationObject.fogMode = scene.fogMode;
  30003. serializationObject.fogColor = scene.fogColor.asArray();
  30004. serializationObject.fogStart = scene.fogStart;
  30005. serializationObject.fogEnd = scene.fogEnd;
  30006. serializationObject.fogDensity = scene.fogDensity;
  30007. }
  30008. //Physics
  30009. if (scene.isPhysicsEnabled()) {
  30010. serializationObject.physicsEnabled = true;
  30011. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30012. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30013. }
  30014. // Lights
  30015. serializationObject.lights = [];
  30016. var index;
  30017. var light;
  30018. for (index = 0; index < scene.lights.length; index++) {
  30019. light = scene.lights[index];
  30020. serializationObject.lights.push(light.serialize());
  30021. }
  30022. // Cameras
  30023. serializationObject.cameras = [];
  30024. for (index = 0; index < scene.cameras.length; index++) {
  30025. var camera = scene.cameras[index];
  30026. serializationObject.cameras.push(camera.serialize());
  30027. }
  30028. if (scene.activeCamera) {
  30029. serializationObject.activeCameraID = scene.activeCamera.id;
  30030. }
  30031. // Materials
  30032. serializationObject.materials = [];
  30033. serializationObject.multiMaterials = [];
  30034. var material;
  30035. for (index = 0; index < scene.materials.length; index++) {
  30036. material = scene.materials[index];
  30037. serializationObject.materials.push(material.serialize());
  30038. }
  30039. // MultiMaterials
  30040. serializationObject.multiMaterials = [];
  30041. for (index = 0; index < scene.multiMaterials.length; index++) {
  30042. var multiMaterial = scene.multiMaterials[index];
  30043. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30044. }
  30045. for (index = 0; index < scene.materials.length; index++) {
  30046. material = scene.materials[index];
  30047. serializationObject.materials.push(material.serialize());
  30048. }
  30049. // Skeletons
  30050. serializationObject.skeletons = [];
  30051. for (index = 0; index < scene.skeletons.length; index++) {
  30052. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30053. }
  30054. // Geometries
  30055. serializationObject.geometries = {};
  30056. serializationObject.geometries.boxes = [];
  30057. serializationObject.geometries.spheres = [];
  30058. serializationObject.geometries.cylinders = [];
  30059. serializationObject.geometries.toruses = [];
  30060. serializationObject.geometries.grounds = [];
  30061. serializationObject.geometries.planes = [];
  30062. serializationObject.geometries.torusKnots = [];
  30063. serializationObject.geometries.vertexData = [];
  30064. serializedGeometries = [];
  30065. var geometries = scene.getGeometries();
  30066. for (index = 0; index < geometries.length; index++) {
  30067. var geometry = geometries[index];
  30068. if (geometry.isReady()) {
  30069. serializeGeometry(geometry, serializationObject.geometries);
  30070. }
  30071. }
  30072. // Meshes
  30073. serializationObject.meshes = [];
  30074. for (index = 0; index < scene.meshes.length; index++) {
  30075. var abstractMesh = scene.meshes[index];
  30076. if (abstractMesh instanceof BABYLON.Mesh) {
  30077. var mesh = abstractMesh;
  30078. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30079. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30080. }
  30081. }
  30082. }
  30083. // Particles Systems
  30084. serializationObject.particleSystems = [];
  30085. for (index = 0; index < scene.particleSystems.length; index++) {
  30086. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30087. }
  30088. // Lens flares
  30089. serializationObject.lensFlareSystems = [];
  30090. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30091. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30092. }
  30093. // Shadows
  30094. serializationObject.shadowGenerators = [];
  30095. for (index = 0; index < scene.lights.length; index++) {
  30096. light = scene.lights[index];
  30097. if (light.getShadowGenerator()) {
  30098. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30099. }
  30100. }
  30101. return serializationObject;
  30102. };
  30103. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30104. if (withParents === void 0) { withParents = false; }
  30105. if (withChildren === void 0) { withChildren = false; }
  30106. var serializationObject = {};
  30107. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30108. if (withParents || withChildren) {
  30109. //deliberate for loop! not for each, appended should be processed as well.
  30110. for (var i = 0; i < toSerialize.length; ++i) {
  30111. if (withChildren) {
  30112. toSerialize[i].getDescendants().forEach(function (node) {
  30113. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30114. toSerialize.push(node);
  30115. }
  30116. });
  30117. }
  30118. //make sure the array doesn't contain the object already
  30119. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30120. toSerialize.push(toSerialize[i].parent);
  30121. }
  30122. }
  30123. }
  30124. toSerialize.forEach(function (mesh) {
  30125. finalizeSingleMesh(mesh, serializationObject);
  30126. });
  30127. return serializationObject;
  30128. };
  30129. return SceneSerializer;
  30130. })();
  30131. BABYLON.SceneSerializer = SceneSerializer;
  30132. })(BABYLON || (BABYLON = {}));
  30133. var BABYLON;
  30134. (function (BABYLON) {
  30135. // Unique ID when we import meshes from Babylon to CSG
  30136. var currentCSGMeshId = 0;
  30137. // # class Vertex
  30138. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30139. // one to provide additional features like texture coordinates and vertex
  30140. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30141. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30142. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30143. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30144. // is not used anywhere else.
  30145. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30146. var Vertex = (function () {
  30147. function Vertex(pos, normal, uv) {
  30148. this.pos = pos;
  30149. this.normal = normal;
  30150. this.uv = uv;
  30151. }
  30152. Vertex.prototype.clone = function () {
  30153. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30154. };
  30155. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30156. // orientation of a polygon is flipped.
  30157. Vertex.prototype.flip = function () {
  30158. this.normal = this.normal.scale(-1);
  30159. };
  30160. // Create a new vertex between this vertex and `other` by linearly
  30161. // interpolating all properties using a parameter of `t`. Subclasses should
  30162. // override this to interpolate additional properties.
  30163. Vertex.prototype.interpolate = function (other, t) {
  30164. 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));
  30165. };
  30166. return Vertex;
  30167. })();
  30168. // # class Plane
  30169. // Represents a plane in 3D space.
  30170. var Plane = (function () {
  30171. function Plane(normal, w) {
  30172. this.normal = normal;
  30173. this.w = w;
  30174. }
  30175. Plane.FromPoints = function (a, b, c) {
  30176. var v0 = c.subtract(a);
  30177. var v1 = b.subtract(a);
  30178. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30179. return null;
  30180. }
  30181. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30182. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30183. };
  30184. Plane.prototype.clone = function () {
  30185. return new Plane(this.normal.clone(), this.w);
  30186. };
  30187. Plane.prototype.flip = function () {
  30188. this.normal.scaleInPlace(-1);
  30189. this.w = -this.w;
  30190. };
  30191. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30192. // fragments in the appropriate lists. Coplanar polygons go into either
  30193. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30194. // respect to this plane. Polygons in front or in back of this plane go into
  30195. // either `front` or `back`.
  30196. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30197. var COPLANAR = 0;
  30198. var FRONT = 1;
  30199. var BACK = 2;
  30200. var SPANNING = 3;
  30201. // Classify each point as well as the entire polygon into one of the above
  30202. // four classes.
  30203. var polygonType = 0;
  30204. var types = [];
  30205. var i;
  30206. var t;
  30207. for (i = 0; i < polygon.vertices.length; i++) {
  30208. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30209. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30210. polygonType |= type;
  30211. types.push(type);
  30212. }
  30213. // Put the polygon in the correct list, splitting it when necessary.
  30214. switch (polygonType) {
  30215. case COPLANAR:
  30216. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30217. break;
  30218. case FRONT:
  30219. front.push(polygon);
  30220. break;
  30221. case BACK:
  30222. back.push(polygon);
  30223. break;
  30224. case SPANNING:
  30225. var f = [], b = [];
  30226. for (i = 0; i < polygon.vertices.length; i++) {
  30227. var j = (i + 1) % polygon.vertices.length;
  30228. var ti = types[i], tj = types[j];
  30229. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30230. if (ti !== BACK)
  30231. f.push(vi);
  30232. if (ti !== FRONT)
  30233. b.push(ti !== BACK ? vi.clone() : vi);
  30234. if ((ti | tj) === SPANNING) {
  30235. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30236. var v = vi.interpolate(vj, t);
  30237. f.push(v);
  30238. b.push(v.clone());
  30239. }
  30240. }
  30241. var poly;
  30242. if (f.length >= 3) {
  30243. poly = new Polygon(f, polygon.shared);
  30244. if (poly.plane)
  30245. front.push(poly);
  30246. }
  30247. if (b.length >= 3) {
  30248. poly = new Polygon(b, polygon.shared);
  30249. if (poly.plane)
  30250. back.push(poly);
  30251. }
  30252. break;
  30253. }
  30254. };
  30255. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30256. // point is on the plane.
  30257. Plane.EPSILON = 1e-5;
  30258. return Plane;
  30259. })();
  30260. // # class Polygon
  30261. // Represents a convex polygon. The vertices used to initialize a polygon must
  30262. // be coplanar and form a convex loop.
  30263. //
  30264. // Each convex polygon has a `shared` property, which is shared between all
  30265. // polygons that are clones of each other or were split from the same polygon.
  30266. // This can be used to define per-polygon properties (such as surface color).
  30267. var Polygon = (function () {
  30268. function Polygon(vertices, shared) {
  30269. this.vertices = vertices;
  30270. this.shared = shared;
  30271. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30272. }
  30273. Polygon.prototype.clone = function () {
  30274. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30275. return new Polygon(vertices, this.shared);
  30276. };
  30277. Polygon.prototype.flip = function () {
  30278. this.vertices.reverse().map(function (v) { v.flip(); });
  30279. this.plane.flip();
  30280. };
  30281. return Polygon;
  30282. })();
  30283. // # class Node
  30284. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30285. // by picking a polygon to split along. That polygon (and all other coplanar
  30286. // polygons) are added directly to that node and the other polygons are added to
  30287. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30288. // no distinction between internal and leaf nodes.
  30289. var Node = (function () {
  30290. function Node(polygons) {
  30291. this.plane = null;
  30292. this.front = null;
  30293. this.back = null;
  30294. this.polygons = [];
  30295. if (polygons) {
  30296. this.build(polygons);
  30297. }
  30298. }
  30299. Node.prototype.clone = function () {
  30300. var node = new Node();
  30301. node.plane = this.plane && this.plane.clone();
  30302. node.front = this.front && this.front.clone();
  30303. node.back = this.back && this.back.clone();
  30304. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30305. return node;
  30306. };
  30307. // Convert solid space to empty space and empty space to solid space.
  30308. Node.prototype.invert = function () {
  30309. for (var i = 0; i < this.polygons.length; i++) {
  30310. this.polygons[i].flip();
  30311. }
  30312. if (this.plane) {
  30313. this.plane.flip();
  30314. }
  30315. if (this.front) {
  30316. this.front.invert();
  30317. }
  30318. if (this.back) {
  30319. this.back.invert();
  30320. }
  30321. var temp = this.front;
  30322. this.front = this.back;
  30323. this.back = temp;
  30324. };
  30325. // Recursively remove all polygons in `polygons` that are inside this BSP
  30326. // tree.
  30327. Node.prototype.clipPolygons = function (polygons) {
  30328. if (!this.plane)
  30329. return polygons.slice();
  30330. var front = [], back = [];
  30331. for (var i = 0; i < polygons.length; i++) {
  30332. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30333. }
  30334. if (this.front) {
  30335. front = this.front.clipPolygons(front);
  30336. }
  30337. if (this.back) {
  30338. back = this.back.clipPolygons(back);
  30339. }
  30340. else {
  30341. back = [];
  30342. }
  30343. return front.concat(back);
  30344. };
  30345. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30346. // `bsp`.
  30347. Node.prototype.clipTo = function (bsp) {
  30348. this.polygons = bsp.clipPolygons(this.polygons);
  30349. if (this.front)
  30350. this.front.clipTo(bsp);
  30351. if (this.back)
  30352. this.back.clipTo(bsp);
  30353. };
  30354. // Return a list of all polygons in this BSP tree.
  30355. Node.prototype.allPolygons = function () {
  30356. var polygons = this.polygons.slice();
  30357. if (this.front)
  30358. polygons = polygons.concat(this.front.allPolygons());
  30359. if (this.back)
  30360. polygons = polygons.concat(this.back.allPolygons());
  30361. return polygons;
  30362. };
  30363. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30364. // new polygons are filtered down to the bottom of the tree and become new
  30365. // nodes there. Each set of polygons is partitioned using the first polygon
  30366. // (no heuristic is used to pick a good split).
  30367. Node.prototype.build = function (polygons) {
  30368. if (!polygons.length)
  30369. return;
  30370. if (!this.plane)
  30371. this.plane = polygons[0].plane.clone();
  30372. var front = [], back = [];
  30373. for (var i = 0; i < polygons.length; i++) {
  30374. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30375. }
  30376. if (front.length) {
  30377. if (!this.front)
  30378. this.front = new Node();
  30379. this.front.build(front);
  30380. }
  30381. if (back.length) {
  30382. if (!this.back)
  30383. this.back = new Node();
  30384. this.back.build(back);
  30385. }
  30386. };
  30387. return Node;
  30388. })();
  30389. var CSG = (function () {
  30390. function CSG() {
  30391. this.polygons = new Array();
  30392. }
  30393. // Convert BABYLON.Mesh to BABYLON.CSG
  30394. CSG.FromMesh = function (mesh) {
  30395. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30396. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30397. if (mesh instanceof BABYLON.Mesh) {
  30398. mesh.computeWorldMatrix(true);
  30399. matrix = mesh.getWorldMatrix();
  30400. meshPosition = mesh.position.clone();
  30401. meshRotation = mesh.rotation.clone();
  30402. if (mesh.rotationQuaternion) {
  30403. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30404. }
  30405. meshScaling = mesh.scaling.clone();
  30406. }
  30407. else {
  30408. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30409. }
  30410. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30411. var subMeshes = mesh.subMeshes;
  30412. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30413. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30414. vertices = [];
  30415. for (var j = 0; j < 3; j++) {
  30416. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30417. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30418. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30419. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30420. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30421. vertex = new Vertex(position, normal, uv);
  30422. vertices.push(vertex);
  30423. }
  30424. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30425. // To handle the case of degenerated triangle
  30426. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30427. if (polygon.plane)
  30428. polygons.push(polygon);
  30429. }
  30430. }
  30431. var csg = CSG.FromPolygons(polygons);
  30432. csg.matrix = matrix;
  30433. csg.position = meshPosition;
  30434. csg.rotation = meshRotation;
  30435. csg.scaling = meshScaling;
  30436. csg.rotationQuaternion = meshRotationQuaternion;
  30437. currentCSGMeshId++;
  30438. return csg;
  30439. };
  30440. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30441. CSG.FromPolygons = function (polygons) {
  30442. var csg = new CSG();
  30443. csg.polygons = polygons;
  30444. return csg;
  30445. };
  30446. CSG.prototype.clone = function () {
  30447. var csg = new CSG();
  30448. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30449. csg.copyTransformAttributes(this);
  30450. return csg;
  30451. };
  30452. CSG.prototype.toPolygons = function () {
  30453. return this.polygons;
  30454. };
  30455. CSG.prototype.union = function (csg) {
  30456. var a = new Node(this.clone().polygons);
  30457. var b = new Node(csg.clone().polygons);
  30458. a.clipTo(b);
  30459. b.clipTo(a);
  30460. b.invert();
  30461. b.clipTo(a);
  30462. b.invert();
  30463. a.build(b.allPolygons());
  30464. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30465. };
  30466. CSG.prototype.unionInPlace = function (csg) {
  30467. var a = new Node(this.polygons);
  30468. var b = new Node(csg.polygons);
  30469. a.clipTo(b);
  30470. b.clipTo(a);
  30471. b.invert();
  30472. b.clipTo(a);
  30473. b.invert();
  30474. a.build(b.allPolygons());
  30475. this.polygons = a.allPolygons();
  30476. };
  30477. CSG.prototype.subtract = function (csg) {
  30478. var a = new Node(this.clone().polygons);
  30479. var b = new Node(csg.clone().polygons);
  30480. a.invert();
  30481. a.clipTo(b);
  30482. b.clipTo(a);
  30483. b.invert();
  30484. b.clipTo(a);
  30485. b.invert();
  30486. a.build(b.allPolygons());
  30487. a.invert();
  30488. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30489. };
  30490. CSG.prototype.subtractInPlace = function (csg) {
  30491. var a = new Node(this.polygons);
  30492. var b = new Node(csg.polygons);
  30493. a.invert();
  30494. a.clipTo(b);
  30495. b.clipTo(a);
  30496. b.invert();
  30497. b.clipTo(a);
  30498. b.invert();
  30499. a.build(b.allPolygons());
  30500. a.invert();
  30501. this.polygons = a.allPolygons();
  30502. };
  30503. CSG.prototype.intersect = function (csg) {
  30504. var a = new Node(this.clone().polygons);
  30505. var b = new Node(csg.clone().polygons);
  30506. a.invert();
  30507. b.clipTo(a);
  30508. b.invert();
  30509. a.clipTo(b);
  30510. b.clipTo(a);
  30511. a.build(b.allPolygons());
  30512. a.invert();
  30513. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30514. };
  30515. CSG.prototype.intersectInPlace = function (csg) {
  30516. var a = new Node(this.polygons);
  30517. var b = new Node(csg.polygons);
  30518. a.invert();
  30519. b.clipTo(a);
  30520. b.invert();
  30521. a.clipTo(b);
  30522. b.clipTo(a);
  30523. a.build(b.allPolygons());
  30524. a.invert();
  30525. this.polygons = a.allPolygons();
  30526. };
  30527. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30528. // not modified.
  30529. CSG.prototype.inverse = function () {
  30530. var csg = this.clone();
  30531. csg.inverseInPlace();
  30532. return csg;
  30533. };
  30534. CSG.prototype.inverseInPlace = function () {
  30535. this.polygons.map(function (p) { p.flip(); });
  30536. };
  30537. // This is used to keep meshes transformations so they can be restored
  30538. // when we build back a Babylon Mesh
  30539. // NB : All CSG operations are performed in world coordinates
  30540. CSG.prototype.copyTransformAttributes = function (csg) {
  30541. this.matrix = csg.matrix;
  30542. this.position = csg.position;
  30543. this.rotation = csg.rotation;
  30544. this.scaling = csg.scaling;
  30545. this.rotationQuaternion = csg.rotationQuaternion;
  30546. return this;
  30547. };
  30548. // Build Raw mesh from CSG
  30549. // Coordinates here are in world space
  30550. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30551. var matrix = this.matrix.clone();
  30552. matrix.invert();
  30553. 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;
  30554. if (keepSubMeshes) {
  30555. // Sort Polygons, since subMeshes are indices range
  30556. polygons.sort(function (a, b) {
  30557. if (a.shared.meshId === b.shared.meshId) {
  30558. return a.shared.subMeshId - b.shared.subMeshId;
  30559. }
  30560. else {
  30561. return a.shared.meshId - b.shared.meshId;
  30562. }
  30563. });
  30564. }
  30565. for (var i = 0, il = polygons.length; i < il; i++) {
  30566. polygon = polygons[i];
  30567. // Building SubMeshes
  30568. if (!subMesh_dict[polygon.shared.meshId]) {
  30569. subMesh_dict[polygon.shared.meshId] = {};
  30570. }
  30571. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30572. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30573. indexStart: +Infinity,
  30574. indexEnd: -Infinity,
  30575. materialIndex: polygon.shared.materialIndex
  30576. };
  30577. }
  30578. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30579. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30580. polygonIndices[0] = 0;
  30581. polygonIndices[1] = j - 1;
  30582. polygonIndices[2] = j;
  30583. for (var k = 0; k < 3; k++) {
  30584. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30585. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30586. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30587. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30588. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30589. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30590. // Check if 2 points can be merged
  30591. if (!(typeof vertex_idx !== 'undefined' &&
  30592. normals[vertex_idx * 3] === localNormal.x &&
  30593. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30594. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30595. uvs[vertex_idx * 2] === uv.x &&
  30596. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30597. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30598. uvs.push(uv.x, uv.y);
  30599. normals.push(normal.x, normal.y, normal.z);
  30600. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30601. }
  30602. indices.push(vertex_idx);
  30603. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30604. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30605. currentIndex++;
  30606. }
  30607. }
  30608. }
  30609. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30610. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30611. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30612. mesh.setIndices(indices);
  30613. if (keepSubMeshes) {
  30614. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30615. var materialIndexOffset = 0, materialMaxIndex;
  30616. mesh.subMeshes = new Array();
  30617. for (var m in subMesh_dict) {
  30618. materialMaxIndex = -1;
  30619. for (var sm in subMesh_dict[m]) {
  30620. subMesh_obj = subMesh_dict[m][sm];
  30621. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30622. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30623. }
  30624. materialIndexOffset += ++materialMaxIndex;
  30625. }
  30626. }
  30627. return mesh;
  30628. };
  30629. // Build Mesh from CSG taking material and transforms into account
  30630. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30631. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30632. mesh.material = material;
  30633. mesh.position.copyFrom(this.position);
  30634. mesh.rotation.copyFrom(this.rotation);
  30635. if (this.rotationQuaternion) {
  30636. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30637. }
  30638. mesh.scaling.copyFrom(this.scaling);
  30639. mesh.computeWorldMatrix(true);
  30640. return mesh;
  30641. };
  30642. return CSG;
  30643. })();
  30644. BABYLON.CSG = CSG;
  30645. })(BABYLON || (BABYLON = {}));
  30646. var BABYLON;
  30647. (function (BABYLON) {
  30648. var VRDistortionCorrectionPostProcess = (function (_super) {
  30649. __extends(VRDistortionCorrectionPostProcess, _super);
  30650. //ANY
  30651. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30652. var _this = this;
  30653. _super.call(this, name, "vrDistortionCorrection", [
  30654. 'LensCenter',
  30655. 'Scale',
  30656. 'ScaleIn',
  30657. 'HmdWarpParam'
  30658. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30659. this._isRightEye = isRightEye;
  30660. this._distortionFactors = vrMetrics.distortionK;
  30661. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30662. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30663. this.onSizeChanged = function () {
  30664. _this.aspectRatio = _this.width * .5 / _this.height;
  30665. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30666. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30667. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30668. };
  30669. this.onApply = function (effect) {
  30670. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30671. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30672. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30673. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30674. };
  30675. }
  30676. return VRDistortionCorrectionPostProcess;
  30677. })(BABYLON.PostProcess);
  30678. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30679. })(BABYLON || (BABYLON = {}));
  30680. // Mainly based on these 2 articles :
  30681. // 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
  30682. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30683. var BABYLON;
  30684. (function (BABYLON) {
  30685. (function (JoystickAxis) {
  30686. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30687. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30688. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30689. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30690. var JoystickAxis = BABYLON.JoystickAxis;
  30691. var VirtualJoystick = (function () {
  30692. function VirtualJoystick(leftJoystick) {
  30693. var _this = this;
  30694. if (leftJoystick) {
  30695. this._leftJoystick = true;
  30696. }
  30697. else {
  30698. this._leftJoystick = false;
  30699. }
  30700. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30701. VirtualJoystick._globalJoystickIndex++;
  30702. // By default left & right arrow keys are moving the X
  30703. // and up & down keys are moving the Y
  30704. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30705. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30706. this.reverseLeftRight = false;
  30707. this.reverseUpDown = false;
  30708. // collections of pointers
  30709. this._touches = new BABYLON.SmartCollection();
  30710. this.deltaPosition = BABYLON.Vector3.Zero();
  30711. this._joystickSensibility = 25;
  30712. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30713. this._rotationSpeed = 25;
  30714. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30715. this._rotateOnAxisRelativeToMesh = false;
  30716. this._onResize = function (evt) {
  30717. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30718. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30719. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30720. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30721. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30722. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30723. };
  30724. // injecting a canvas element on top of the canvas 3D game
  30725. if (!VirtualJoystick.vjCanvas) {
  30726. window.addEventListener("resize", this._onResize, false);
  30727. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30728. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30729. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30730. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30731. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30732. VirtualJoystick.vjCanvas.style.width = "100%";
  30733. VirtualJoystick.vjCanvas.style.height = "100%";
  30734. VirtualJoystick.vjCanvas.style.position = "absolute";
  30735. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30736. VirtualJoystick.vjCanvas.style.top = "0px";
  30737. VirtualJoystick.vjCanvas.style.left = "0px";
  30738. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30739. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30740. // Support for jQuery PEP polyfill
  30741. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30742. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30743. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30744. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30745. document.body.appendChild(VirtualJoystick.vjCanvas);
  30746. }
  30747. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30748. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30749. this.pressed = false;
  30750. // default joystick color
  30751. this._joystickColor = "cyan";
  30752. this._joystickPointerID = -1;
  30753. // current joystick position
  30754. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30755. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30756. // origin joystick position
  30757. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30758. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30759. this._onPointerDownHandlerRef = function (evt) {
  30760. _this._onPointerDown(evt);
  30761. };
  30762. this._onPointerMoveHandlerRef = function (evt) {
  30763. _this._onPointerMove(evt);
  30764. };
  30765. this._onPointerOutHandlerRef = function (evt) {
  30766. _this._onPointerUp(evt);
  30767. };
  30768. this._onPointerUpHandlerRef = function (evt) {
  30769. _this._onPointerUp(evt);
  30770. };
  30771. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30772. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30773. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30774. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30775. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30776. evt.preventDefault(); // Disables system menu
  30777. }, false);
  30778. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30779. }
  30780. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30781. this._joystickSensibility = newJoystickSensibility;
  30782. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30783. };
  30784. VirtualJoystick.prototype._onPointerDown = function (e) {
  30785. var positionOnScreenCondition;
  30786. e.preventDefault();
  30787. if (this._leftJoystick === true) {
  30788. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30789. }
  30790. else {
  30791. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30792. }
  30793. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30794. // First contact will be dedicated to the virtual joystick
  30795. this._joystickPointerID = e.pointerId;
  30796. this._joystickPointerStartPos.x = e.clientX;
  30797. this._joystickPointerStartPos.y = e.clientY;
  30798. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30799. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30800. this._deltaJoystickVector.x = 0;
  30801. this._deltaJoystickVector.y = 0;
  30802. this.pressed = true;
  30803. this._touches.add(e.pointerId.toString(), e);
  30804. }
  30805. else {
  30806. // You can only trigger the action buttons with a joystick declared
  30807. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30808. this._action();
  30809. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30810. }
  30811. }
  30812. };
  30813. VirtualJoystick.prototype._onPointerMove = function (e) {
  30814. // If the current pointer is the one associated to the joystick (first touch contact)
  30815. if (this._joystickPointerID == e.pointerId) {
  30816. this._joystickPointerPos.x = e.clientX;
  30817. this._joystickPointerPos.y = e.clientY;
  30818. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30819. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30820. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30821. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30822. switch (this._axisTargetedByLeftAndRight) {
  30823. case JoystickAxis.X:
  30824. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30825. break;
  30826. case JoystickAxis.Y:
  30827. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30828. break;
  30829. case JoystickAxis.Z:
  30830. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30831. break;
  30832. }
  30833. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30834. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30835. switch (this._axisTargetedByUpAndDown) {
  30836. case JoystickAxis.X:
  30837. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30838. break;
  30839. case JoystickAxis.Y:
  30840. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30841. break;
  30842. case JoystickAxis.Z:
  30843. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30844. break;
  30845. }
  30846. }
  30847. else {
  30848. if (this._touches.item(e.pointerId.toString())) {
  30849. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30850. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30851. }
  30852. }
  30853. };
  30854. VirtualJoystick.prototype._onPointerUp = function (e) {
  30855. if (this._joystickPointerID == e.pointerId) {
  30856. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30857. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30858. this._joystickPointerID = -1;
  30859. this.pressed = false;
  30860. }
  30861. else {
  30862. var touch = this._touches.item(e.pointerId.toString());
  30863. if (touch) {
  30864. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30865. }
  30866. }
  30867. this._deltaJoystickVector.x = 0;
  30868. this._deltaJoystickVector.y = 0;
  30869. this._touches.remove(e.pointerId.toString());
  30870. };
  30871. /**
  30872. * Change the color of the virtual joystick
  30873. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30874. */
  30875. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30876. this._joystickColor = newColor;
  30877. };
  30878. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30879. this._action = action;
  30880. };
  30881. // Define which axis you'd like to control for left & right
  30882. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30883. switch (axis) {
  30884. case JoystickAxis.X:
  30885. case JoystickAxis.Y:
  30886. case JoystickAxis.Z:
  30887. this._axisTargetedByLeftAndRight = axis;
  30888. break;
  30889. default:
  30890. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30891. break;
  30892. }
  30893. };
  30894. // Define which axis you'd like to control for up & down
  30895. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30896. switch (axis) {
  30897. case JoystickAxis.X:
  30898. case JoystickAxis.Y:
  30899. case JoystickAxis.Z:
  30900. this._axisTargetedByUpAndDown = axis;
  30901. break;
  30902. default:
  30903. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30904. break;
  30905. }
  30906. };
  30907. VirtualJoystick.prototype._clearCanvas = function () {
  30908. if (this._leftJoystick) {
  30909. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30910. }
  30911. else {
  30912. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30913. }
  30914. };
  30915. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30916. var _this = this;
  30917. if (this.pressed) {
  30918. this._touches.forEach(function (touch) {
  30919. if (touch.pointerId === _this._joystickPointerID) {
  30920. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30921. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30922. VirtualJoystick.vjCanvasContext.beginPath();
  30923. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30924. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30925. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30926. VirtualJoystick.vjCanvasContext.stroke();
  30927. VirtualJoystick.vjCanvasContext.closePath();
  30928. VirtualJoystick.vjCanvasContext.beginPath();
  30929. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30930. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30931. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30932. VirtualJoystick.vjCanvasContext.stroke();
  30933. VirtualJoystick.vjCanvasContext.closePath();
  30934. VirtualJoystick.vjCanvasContext.beginPath();
  30935. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30936. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30937. VirtualJoystick.vjCanvasContext.stroke();
  30938. VirtualJoystick.vjCanvasContext.closePath();
  30939. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30940. }
  30941. else {
  30942. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30943. VirtualJoystick.vjCanvasContext.beginPath();
  30944. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30945. VirtualJoystick.vjCanvasContext.beginPath();
  30946. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30947. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30948. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30949. VirtualJoystick.vjCanvasContext.stroke();
  30950. VirtualJoystick.vjCanvasContext.closePath();
  30951. touch.prevX = touch.x;
  30952. touch.prevY = touch.y;
  30953. }
  30954. ;
  30955. });
  30956. }
  30957. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30958. };
  30959. VirtualJoystick.prototype.releaseCanvas = function () {
  30960. if (VirtualJoystick.vjCanvas) {
  30961. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30962. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30963. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30964. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30965. window.removeEventListener("resize", this._onResize);
  30966. document.body.removeChild(VirtualJoystick.vjCanvas);
  30967. VirtualJoystick.vjCanvas = null;
  30968. }
  30969. };
  30970. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30971. VirtualJoystick._globalJoystickIndex = 0;
  30972. return VirtualJoystick;
  30973. })();
  30974. BABYLON.VirtualJoystick = VirtualJoystick;
  30975. })(BABYLON || (BABYLON = {}));
  30976. var BABYLON;
  30977. (function (BABYLON) {
  30978. // We're mainly based on the logic defined into the FreeCamera code
  30979. var VirtualJoysticksCamera = (function (_super) {
  30980. __extends(VirtualJoysticksCamera, _super);
  30981. function VirtualJoysticksCamera(name, position, scene) {
  30982. _super.call(this, name, position, scene);
  30983. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30984. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30985. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30986. this._leftjoystick.setJoystickSensibility(0.15);
  30987. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30988. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30989. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30990. this._rightjoystick.reverseUpDown = true;
  30991. this._rightjoystick.setJoystickSensibility(0.05);
  30992. this._rightjoystick.setJoystickColor("yellow");
  30993. }
  30994. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30995. return this._leftjoystick;
  30996. };
  30997. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30998. return this._rightjoystick;
  30999. };
  31000. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31001. var speed = this._computeLocalCameraSpeed() * 50;
  31002. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31003. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31004. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31005. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31006. if (!this._leftjoystick.pressed) {
  31007. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31008. }
  31009. if (!this._rightjoystick.pressed) {
  31010. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31011. }
  31012. _super.prototype._checkInputs.call(this);
  31013. };
  31014. VirtualJoysticksCamera.prototype.dispose = function () {
  31015. this._leftjoystick.releaseCanvas();
  31016. _super.prototype.dispose.call(this);
  31017. };
  31018. return VirtualJoysticksCamera;
  31019. })(BABYLON.FreeCamera);
  31020. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31021. })(BABYLON || (BABYLON = {}));
  31022. var BABYLON;
  31023. (function (BABYLON) {
  31024. var AnaglyphPostProcess = (function (_super) {
  31025. __extends(AnaglyphPostProcess, _super);
  31026. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31027. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31028. }
  31029. return AnaglyphPostProcess;
  31030. })(BABYLON.PostProcess);
  31031. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31032. })(BABYLON || (BABYLON = {}));
  31033. var BABYLON;
  31034. (function (BABYLON) {
  31035. var OutlineRenderer = (function () {
  31036. function OutlineRenderer(scene) {
  31037. this._scene = scene;
  31038. }
  31039. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31040. var _this = this;
  31041. if (useOverlay === void 0) { useOverlay = false; }
  31042. var scene = this._scene;
  31043. var engine = this._scene.getEngine();
  31044. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31045. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31046. return;
  31047. }
  31048. var mesh = subMesh.getRenderingMesh();
  31049. var material = subMesh.getMaterial();
  31050. engine.enableEffect(this._effect);
  31051. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31052. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31053. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31054. // Bones
  31055. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31056. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31057. }
  31058. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31059. // Alpha test
  31060. if (material && material.needAlphaTesting()) {
  31061. var alphaTexture = material.getAlphaTestTexture();
  31062. this._effect.setTexture("diffuseSampler", alphaTexture);
  31063. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31064. }
  31065. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31066. };
  31067. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31068. var defines = [];
  31069. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31070. var mesh = subMesh.getMesh();
  31071. var material = subMesh.getMaterial();
  31072. // Alpha test
  31073. if (material && material.needAlphaTesting()) {
  31074. defines.push("#define ALPHATEST");
  31075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31076. attribs.push(BABYLON.VertexBuffer.UVKind);
  31077. defines.push("#define UV1");
  31078. }
  31079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31080. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31081. defines.push("#define UV2");
  31082. }
  31083. }
  31084. // Bones
  31085. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31086. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31087. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31088. if (mesh.numBoneInfluencers > 4) {
  31089. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31090. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31091. }
  31092. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31093. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31094. }
  31095. else {
  31096. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31097. }
  31098. // Instances
  31099. if (useInstances) {
  31100. defines.push("#define INSTANCES");
  31101. attribs.push("world0");
  31102. attribs.push("world1");
  31103. attribs.push("world2");
  31104. attribs.push("world3");
  31105. }
  31106. // Get correct effect
  31107. var join = defines.join("\n");
  31108. if (this._cachedDefines !== join) {
  31109. this._cachedDefines = join;
  31110. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31111. }
  31112. return this._effect.isReady();
  31113. };
  31114. return OutlineRenderer;
  31115. })();
  31116. BABYLON.OutlineRenderer = OutlineRenderer;
  31117. })(BABYLON || (BABYLON = {}));
  31118. var BABYLON;
  31119. (function (BABYLON) {
  31120. var MeshAssetTask = (function () {
  31121. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31122. this.name = name;
  31123. this.meshesNames = meshesNames;
  31124. this.rootUrl = rootUrl;
  31125. this.sceneFilename = sceneFilename;
  31126. this.isCompleted = false;
  31127. }
  31128. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31129. var _this = this;
  31130. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31131. _this.loadedMeshes = meshes;
  31132. _this.loadedParticleSystems = particleSystems;
  31133. _this.loadedSkeletons = skeletons;
  31134. _this.isCompleted = true;
  31135. if (_this.onSuccess) {
  31136. _this.onSuccess(_this);
  31137. }
  31138. onSuccess();
  31139. }, null, function () {
  31140. if (_this.onError) {
  31141. _this.onError(_this);
  31142. }
  31143. onError();
  31144. });
  31145. };
  31146. return MeshAssetTask;
  31147. })();
  31148. BABYLON.MeshAssetTask = MeshAssetTask;
  31149. var TextFileAssetTask = (function () {
  31150. function TextFileAssetTask(name, url) {
  31151. this.name = name;
  31152. this.url = url;
  31153. this.isCompleted = false;
  31154. }
  31155. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31156. var _this = this;
  31157. BABYLON.Tools.LoadFile(this.url, function (data) {
  31158. _this.text = data;
  31159. _this.isCompleted = true;
  31160. if (_this.onSuccess) {
  31161. _this.onSuccess(_this);
  31162. }
  31163. onSuccess();
  31164. }, null, scene.database, false, function () {
  31165. if (_this.onError) {
  31166. _this.onError(_this);
  31167. }
  31168. onError();
  31169. });
  31170. };
  31171. return TextFileAssetTask;
  31172. })();
  31173. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31174. var BinaryFileAssetTask = (function () {
  31175. function BinaryFileAssetTask(name, url) {
  31176. this.name = name;
  31177. this.url = url;
  31178. this.isCompleted = false;
  31179. }
  31180. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31181. var _this = this;
  31182. BABYLON.Tools.LoadFile(this.url, function (data) {
  31183. _this.data = data;
  31184. _this.isCompleted = true;
  31185. if (_this.onSuccess) {
  31186. _this.onSuccess(_this);
  31187. }
  31188. onSuccess();
  31189. }, null, scene.database, true, function () {
  31190. if (_this.onError) {
  31191. _this.onError(_this);
  31192. }
  31193. onError();
  31194. });
  31195. };
  31196. return BinaryFileAssetTask;
  31197. })();
  31198. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31199. var ImageAssetTask = (function () {
  31200. function ImageAssetTask(name, url) {
  31201. this.name = name;
  31202. this.url = url;
  31203. this.isCompleted = false;
  31204. }
  31205. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31206. var _this = this;
  31207. var img = new Image();
  31208. img.onload = function () {
  31209. _this.image = img;
  31210. _this.isCompleted = true;
  31211. if (_this.onSuccess) {
  31212. _this.onSuccess(_this);
  31213. }
  31214. onSuccess();
  31215. };
  31216. img.onerror = function () {
  31217. if (_this.onError) {
  31218. _this.onError(_this);
  31219. }
  31220. onError();
  31221. };
  31222. img.src = this.url;
  31223. };
  31224. return ImageAssetTask;
  31225. })();
  31226. BABYLON.ImageAssetTask = ImageAssetTask;
  31227. var TextureAssetTask = (function () {
  31228. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31230. this.name = name;
  31231. this.url = url;
  31232. this.noMipmap = noMipmap;
  31233. this.invertY = invertY;
  31234. this.samplingMode = samplingMode;
  31235. this.isCompleted = false;
  31236. }
  31237. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31238. var _this = this;
  31239. var onload = function () {
  31240. _this.isCompleted = true;
  31241. if (_this.onSuccess) {
  31242. _this.onSuccess(_this);
  31243. }
  31244. onSuccess();
  31245. };
  31246. var onerror = function () {
  31247. if (_this.onError) {
  31248. _this.onError(_this);
  31249. }
  31250. onError();
  31251. };
  31252. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31253. };
  31254. return TextureAssetTask;
  31255. })();
  31256. BABYLON.TextureAssetTask = TextureAssetTask;
  31257. var AssetsManager = (function () {
  31258. function AssetsManager(scene) {
  31259. this._tasks = new Array();
  31260. this._waitingTasksCount = 0;
  31261. this.useDefaultLoadingScreen = true;
  31262. this._scene = scene;
  31263. }
  31264. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31265. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31266. this._tasks.push(task);
  31267. return task;
  31268. };
  31269. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31270. var task = new TextFileAssetTask(taskName, url);
  31271. this._tasks.push(task);
  31272. return task;
  31273. };
  31274. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31275. var task = new BinaryFileAssetTask(taskName, url);
  31276. this._tasks.push(task);
  31277. return task;
  31278. };
  31279. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31280. var task = new ImageAssetTask(taskName, url);
  31281. this._tasks.push(task);
  31282. return task;
  31283. };
  31284. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31286. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31287. this._tasks.push(task);
  31288. return task;
  31289. };
  31290. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31291. this._waitingTasksCount--;
  31292. if (this._waitingTasksCount === 0) {
  31293. if (this.onFinish) {
  31294. this.onFinish(this._tasks);
  31295. }
  31296. this._scene.getEngine().hideLoadingUI();
  31297. }
  31298. };
  31299. AssetsManager.prototype._runTask = function (task) {
  31300. var _this = this;
  31301. task.run(this._scene, function () {
  31302. if (_this.onTaskSuccess) {
  31303. _this.onTaskSuccess(task);
  31304. }
  31305. _this._decreaseWaitingTasksCount();
  31306. }, function () {
  31307. if (_this.onTaskError) {
  31308. _this.onTaskError(task);
  31309. }
  31310. _this._decreaseWaitingTasksCount();
  31311. });
  31312. };
  31313. AssetsManager.prototype.reset = function () {
  31314. this._tasks = new Array();
  31315. return this;
  31316. };
  31317. AssetsManager.prototype.load = function () {
  31318. this._waitingTasksCount = this._tasks.length;
  31319. if (this._waitingTasksCount === 0) {
  31320. if (this.onFinish) {
  31321. this.onFinish(this._tasks);
  31322. }
  31323. return this;
  31324. }
  31325. if (this.useDefaultLoadingScreen) {
  31326. this._scene.getEngine().displayLoadingUI();
  31327. }
  31328. for (var index = 0; index < this._tasks.length; index++) {
  31329. var task = this._tasks[index];
  31330. this._runTask(task);
  31331. }
  31332. return this;
  31333. };
  31334. return AssetsManager;
  31335. })();
  31336. BABYLON.AssetsManager = AssetsManager;
  31337. })(BABYLON || (BABYLON = {}));
  31338. var BABYLON;
  31339. (function (BABYLON) {
  31340. var VRDeviceOrientationFreeCamera = (function (_super) {
  31341. __extends(VRDeviceOrientationFreeCamera, _super);
  31342. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31343. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31344. _super.call(this, name, position, scene);
  31345. this._alpha = 0;
  31346. this._beta = 0;
  31347. this._gamma = 0;
  31348. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31349. metrics.compensateDistortion = compensateDistortion;
  31350. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31351. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31352. }
  31353. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31354. this._alpha = +evt.alpha | 0;
  31355. this._beta = +evt.beta | 0;
  31356. this._gamma = +evt.gamma | 0;
  31357. if (this._gamma < 0) {
  31358. this._gamma = 90 + this._gamma;
  31359. }
  31360. else {
  31361. // Incline it in the correct angle.
  31362. this._gamma = 270 - this._gamma;
  31363. }
  31364. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31365. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31366. this.rotation.z = this._beta / 180.0 * Math.PI;
  31367. };
  31368. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31369. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31370. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31371. };
  31372. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31373. _super.prototype.detachControl.call(this, element);
  31374. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31375. };
  31376. return VRDeviceOrientationFreeCamera;
  31377. })(BABYLON.FreeCamera);
  31378. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31379. })(BABYLON || (BABYLON = {}));
  31380. var BABYLON;
  31381. (function (BABYLON) {
  31382. var WebVRFreeCamera = (function (_super) {
  31383. __extends(WebVRFreeCamera, _super);
  31384. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31385. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31386. _super.call(this, name, position, scene);
  31387. this._hmdDevice = null;
  31388. this._sensorDevice = null;
  31389. this._cacheState = null;
  31390. this._cacheQuaternion = new BABYLON.Quaternion();
  31391. this._cacheRotation = BABYLON.Vector3.Zero();
  31392. this._vrEnabled = false;
  31393. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31394. metrics.compensateDistortion = compensateDistortion;
  31395. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31396. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31397. }
  31398. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31399. var size = devices.length;
  31400. var i = 0;
  31401. // Reset devices.
  31402. this._sensorDevice = null;
  31403. this._hmdDevice = null;
  31404. // Search for a HmdDevice.
  31405. while (i < size && this._hmdDevice === null) {
  31406. if (devices[i] instanceof HMDVRDevice) {
  31407. this._hmdDevice = devices[i];
  31408. }
  31409. i++;
  31410. }
  31411. i = 0;
  31412. while (i < size && this._sensorDevice === null) {
  31413. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31414. this._sensorDevice = devices[i];
  31415. }
  31416. i++;
  31417. }
  31418. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31419. };
  31420. WebVRFreeCamera.prototype._checkInputs = function () {
  31421. if (this._vrEnabled) {
  31422. this._cacheState = this._sensorDevice.getState();
  31423. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31424. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31425. this.rotation.x = -this._cacheRotation.z;
  31426. this.rotation.y = -this._cacheRotation.y;
  31427. this.rotation.z = this._cacheRotation.x;
  31428. }
  31429. _super.prototype._checkInputs.call(this);
  31430. };
  31431. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31432. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31433. if (navigator.getVRDevices) {
  31434. navigator.getVRDevices().then(this._getWebVRDevices);
  31435. }
  31436. else if (navigator.mozGetVRDevices) {
  31437. navigator.mozGetVRDevices(this._getWebVRDevices);
  31438. }
  31439. };
  31440. WebVRFreeCamera.prototype.detachControl = function (element) {
  31441. _super.prototype.detachControl.call(this, element);
  31442. this._vrEnabled = false;
  31443. };
  31444. return WebVRFreeCamera;
  31445. })(BABYLON.FreeCamera);
  31446. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31447. })(BABYLON || (BABYLON = {}));
  31448. var BABYLON;
  31449. (function (BABYLON) {
  31450. // Standard optimizations
  31451. var SceneOptimization = (function () {
  31452. function SceneOptimization(priority) {
  31453. if (priority === void 0) { priority = 0; }
  31454. this.priority = priority;
  31455. this.apply = function (scene) {
  31456. return true; // Return true if everything that can be done was applied
  31457. };
  31458. }
  31459. return SceneOptimization;
  31460. })();
  31461. BABYLON.SceneOptimization = SceneOptimization;
  31462. var TextureOptimization = (function (_super) {
  31463. __extends(TextureOptimization, _super);
  31464. function TextureOptimization(priority, maximumSize) {
  31465. var _this = this;
  31466. if (priority === void 0) { priority = 0; }
  31467. if (maximumSize === void 0) { maximumSize = 1024; }
  31468. _super.call(this, priority);
  31469. this.priority = priority;
  31470. this.maximumSize = maximumSize;
  31471. this.apply = function (scene) {
  31472. var allDone = true;
  31473. for (var index = 0; index < scene.textures.length; index++) {
  31474. var texture = scene.textures[index];
  31475. if (!texture.canRescale) {
  31476. continue;
  31477. }
  31478. var currentSize = texture.getSize();
  31479. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31480. if (maxDimension > _this.maximumSize) {
  31481. texture.scale(0.5);
  31482. allDone = false;
  31483. }
  31484. }
  31485. return allDone;
  31486. };
  31487. }
  31488. return TextureOptimization;
  31489. })(SceneOptimization);
  31490. BABYLON.TextureOptimization = TextureOptimization;
  31491. var HardwareScalingOptimization = (function (_super) {
  31492. __extends(HardwareScalingOptimization, _super);
  31493. function HardwareScalingOptimization(priority, maximumScale) {
  31494. var _this = this;
  31495. if (priority === void 0) { priority = 0; }
  31496. if (maximumScale === void 0) { maximumScale = 2; }
  31497. _super.call(this, priority);
  31498. this.priority = priority;
  31499. this.maximumScale = maximumScale;
  31500. this._currentScale = 1;
  31501. this.apply = function (scene) {
  31502. _this._currentScale++;
  31503. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31504. return _this._currentScale >= _this.maximumScale;
  31505. };
  31506. }
  31507. return HardwareScalingOptimization;
  31508. })(SceneOptimization);
  31509. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31510. var ShadowsOptimization = (function (_super) {
  31511. __extends(ShadowsOptimization, _super);
  31512. function ShadowsOptimization() {
  31513. _super.apply(this, arguments);
  31514. this.apply = function (scene) {
  31515. scene.shadowsEnabled = false;
  31516. return true;
  31517. };
  31518. }
  31519. return ShadowsOptimization;
  31520. })(SceneOptimization);
  31521. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31522. var PostProcessesOptimization = (function (_super) {
  31523. __extends(PostProcessesOptimization, _super);
  31524. function PostProcessesOptimization() {
  31525. _super.apply(this, arguments);
  31526. this.apply = function (scene) {
  31527. scene.postProcessesEnabled = false;
  31528. return true;
  31529. };
  31530. }
  31531. return PostProcessesOptimization;
  31532. })(SceneOptimization);
  31533. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31534. var LensFlaresOptimization = (function (_super) {
  31535. __extends(LensFlaresOptimization, _super);
  31536. function LensFlaresOptimization() {
  31537. _super.apply(this, arguments);
  31538. this.apply = function (scene) {
  31539. scene.lensFlaresEnabled = false;
  31540. return true;
  31541. };
  31542. }
  31543. return LensFlaresOptimization;
  31544. })(SceneOptimization);
  31545. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31546. var ParticlesOptimization = (function (_super) {
  31547. __extends(ParticlesOptimization, _super);
  31548. function ParticlesOptimization() {
  31549. _super.apply(this, arguments);
  31550. this.apply = function (scene) {
  31551. scene.particlesEnabled = false;
  31552. return true;
  31553. };
  31554. }
  31555. return ParticlesOptimization;
  31556. })(SceneOptimization);
  31557. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31558. var RenderTargetsOptimization = (function (_super) {
  31559. __extends(RenderTargetsOptimization, _super);
  31560. function RenderTargetsOptimization() {
  31561. _super.apply(this, arguments);
  31562. this.apply = function (scene) {
  31563. scene.renderTargetsEnabled = false;
  31564. return true;
  31565. };
  31566. }
  31567. return RenderTargetsOptimization;
  31568. })(SceneOptimization);
  31569. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31570. var MergeMeshesOptimization = (function (_super) {
  31571. __extends(MergeMeshesOptimization, _super);
  31572. function MergeMeshesOptimization() {
  31573. var _this = this;
  31574. _super.apply(this, arguments);
  31575. this._canBeMerged = function (abstractMesh) {
  31576. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31577. return false;
  31578. }
  31579. var mesh = abstractMesh;
  31580. if (!mesh.isVisible || !mesh.isEnabled()) {
  31581. return false;
  31582. }
  31583. if (mesh.instances.length > 0) {
  31584. return false;
  31585. }
  31586. if (mesh.skeleton || mesh.hasLODLevels) {
  31587. return false;
  31588. }
  31589. if (mesh.parent) {
  31590. return false;
  31591. }
  31592. return true;
  31593. };
  31594. this.apply = function (scene, updateSelectionTree) {
  31595. var globalPool = scene.meshes.slice(0);
  31596. var globalLength = globalPool.length;
  31597. for (var index = 0; index < globalLength; index++) {
  31598. var currentPool = new Array();
  31599. var current = globalPool[index];
  31600. // Checks
  31601. if (!_this._canBeMerged(current)) {
  31602. continue;
  31603. }
  31604. currentPool.push(current);
  31605. // Find compatible meshes
  31606. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31607. var otherMesh = globalPool[subIndex];
  31608. if (!_this._canBeMerged(otherMesh)) {
  31609. continue;
  31610. }
  31611. if (otherMesh.material !== current.material) {
  31612. continue;
  31613. }
  31614. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31615. continue;
  31616. }
  31617. currentPool.push(otherMesh);
  31618. globalLength--;
  31619. globalPool.splice(subIndex, 1);
  31620. subIndex--;
  31621. }
  31622. if (currentPool.length < 2) {
  31623. continue;
  31624. }
  31625. // Merge meshes
  31626. BABYLON.Mesh.MergeMeshes(currentPool);
  31627. }
  31628. if (updateSelectionTree != undefined) {
  31629. if (updateSelectionTree) {
  31630. scene.createOrUpdateSelectionOctree();
  31631. }
  31632. }
  31633. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31634. scene.createOrUpdateSelectionOctree();
  31635. }
  31636. return true;
  31637. };
  31638. }
  31639. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31640. get: function () {
  31641. return MergeMeshesOptimization._UpdateSelectionTree;
  31642. },
  31643. set: function (value) {
  31644. MergeMeshesOptimization._UpdateSelectionTree = value;
  31645. },
  31646. enumerable: true,
  31647. configurable: true
  31648. });
  31649. MergeMeshesOptimization._UpdateSelectionTree = false;
  31650. return MergeMeshesOptimization;
  31651. })(SceneOptimization);
  31652. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31653. // Options
  31654. var SceneOptimizerOptions = (function () {
  31655. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31656. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31657. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31658. this.targetFrameRate = targetFrameRate;
  31659. this.trackerDuration = trackerDuration;
  31660. this.optimizations = new Array();
  31661. }
  31662. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31663. var result = new SceneOptimizerOptions(targetFrameRate);
  31664. var priority = 0;
  31665. result.optimizations.push(new MergeMeshesOptimization(priority));
  31666. result.optimizations.push(new ShadowsOptimization(priority));
  31667. result.optimizations.push(new LensFlaresOptimization(priority));
  31668. // Next priority
  31669. priority++;
  31670. result.optimizations.push(new PostProcessesOptimization(priority));
  31671. result.optimizations.push(new ParticlesOptimization(priority));
  31672. // Next priority
  31673. priority++;
  31674. result.optimizations.push(new TextureOptimization(priority, 1024));
  31675. return result;
  31676. };
  31677. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31678. var result = new SceneOptimizerOptions(targetFrameRate);
  31679. var priority = 0;
  31680. result.optimizations.push(new MergeMeshesOptimization(priority));
  31681. result.optimizations.push(new ShadowsOptimization(priority));
  31682. result.optimizations.push(new LensFlaresOptimization(priority));
  31683. // Next priority
  31684. priority++;
  31685. result.optimizations.push(new PostProcessesOptimization(priority));
  31686. result.optimizations.push(new ParticlesOptimization(priority));
  31687. // Next priority
  31688. priority++;
  31689. result.optimizations.push(new TextureOptimization(priority, 512));
  31690. // Next priority
  31691. priority++;
  31692. result.optimizations.push(new RenderTargetsOptimization(priority));
  31693. // Next priority
  31694. priority++;
  31695. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31696. return result;
  31697. };
  31698. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31699. var result = new SceneOptimizerOptions(targetFrameRate);
  31700. var priority = 0;
  31701. result.optimizations.push(new MergeMeshesOptimization(priority));
  31702. result.optimizations.push(new ShadowsOptimization(priority));
  31703. result.optimizations.push(new LensFlaresOptimization(priority));
  31704. // Next priority
  31705. priority++;
  31706. result.optimizations.push(new PostProcessesOptimization(priority));
  31707. result.optimizations.push(new ParticlesOptimization(priority));
  31708. // Next priority
  31709. priority++;
  31710. result.optimizations.push(new TextureOptimization(priority, 256));
  31711. // Next priority
  31712. priority++;
  31713. result.optimizations.push(new RenderTargetsOptimization(priority));
  31714. // Next priority
  31715. priority++;
  31716. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31717. return result;
  31718. };
  31719. return SceneOptimizerOptions;
  31720. })();
  31721. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31722. // Scene optimizer tool
  31723. var SceneOptimizer = (function () {
  31724. function SceneOptimizer() {
  31725. }
  31726. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31727. // TODO: add an epsilon
  31728. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31729. if (onSuccess) {
  31730. onSuccess();
  31731. }
  31732. return;
  31733. }
  31734. // Apply current level of optimizations
  31735. var allDone = true;
  31736. var noOptimizationApplied = true;
  31737. for (var index = 0; index < options.optimizations.length; index++) {
  31738. var optimization = options.optimizations[index];
  31739. if (optimization.priority === currentPriorityLevel) {
  31740. noOptimizationApplied = false;
  31741. allDone = allDone && optimization.apply(scene);
  31742. }
  31743. }
  31744. // If no optimization was applied, this is a failure :(
  31745. if (noOptimizationApplied) {
  31746. if (onFailure) {
  31747. onFailure();
  31748. }
  31749. return;
  31750. }
  31751. // If all optimizations were done, move to next level
  31752. if (allDone) {
  31753. currentPriorityLevel++;
  31754. }
  31755. // Let's the system running for a specific amount of time before checking FPS
  31756. scene.executeWhenReady(function () {
  31757. setTimeout(function () {
  31758. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31759. }, options.trackerDuration);
  31760. });
  31761. };
  31762. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31763. if (!options) {
  31764. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31765. }
  31766. // Let's the system running for a specific amount of time before checking FPS
  31767. scene.executeWhenReady(function () {
  31768. setTimeout(function () {
  31769. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31770. }, options.trackerDuration);
  31771. });
  31772. };
  31773. return SceneOptimizer;
  31774. })();
  31775. BABYLON.SceneOptimizer = SceneOptimizer;
  31776. })(BABYLON || (BABYLON = {}));
  31777. var BABYLON;
  31778. (function (BABYLON) {
  31779. var Internals;
  31780. (function (Internals) {
  31781. var MeshLODLevel = (function () {
  31782. function MeshLODLevel(distance, mesh) {
  31783. this.distance = distance;
  31784. this.mesh = mesh;
  31785. }
  31786. return MeshLODLevel;
  31787. })();
  31788. Internals.MeshLODLevel = MeshLODLevel;
  31789. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31790. })(BABYLON || (BABYLON = {}));
  31791. var BABYLON;
  31792. (function (BABYLON) {
  31793. var RawTexture = (function (_super) {
  31794. __extends(RawTexture, _super);
  31795. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31796. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31797. if (invertY === void 0) { invertY = false; }
  31798. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31799. _super.call(this, null, scene, !generateMipMaps, invertY);
  31800. this.format = format;
  31801. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31802. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31803. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31804. }
  31805. RawTexture.prototype.update = function (data) {
  31806. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31807. };
  31808. // Statics
  31809. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31811. if (invertY === void 0) { invertY = false; }
  31812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31813. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31814. };
  31815. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31816. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31817. if (invertY === void 0) { invertY = false; }
  31818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31819. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31820. };
  31821. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31822. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31823. if (invertY === void 0) { invertY = false; }
  31824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31825. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31826. };
  31827. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31828. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31829. if (invertY === void 0) { invertY = false; }
  31830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31831. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31832. };
  31833. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31834. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31835. if (invertY === void 0) { invertY = false; }
  31836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31837. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31838. };
  31839. return RawTexture;
  31840. })(BABYLON.Texture);
  31841. BABYLON.RawTexture = RawTexture;
  31842. })(BABYLON || (BABYLON = {}));
  31843. var BABYLON;
  31844. (function (BABYLON) {
  31845. var IndexedVector2 = (function (_super) {
  31846. __extends(IndexedVector2, _super);
  31847. function IndexedVector2(original, index) {
  31848. _super.call(this, original.x, original.y);
  31849. this.index = index;
  31850. }
  31851. return IndexedVector2;
  31852. })(BABYLON.Vector2);
  31853. var PolygonPoints = (function () {
  31854. function PolygonPoints() {
  31855. this.elements = new Array();
  31856. }
  31857. PolygonPoints.prototype.add = function (originalPoints) {
  31858. var _this = this;
  31859. var result = new Array();
  31860. originalPoints.forEach(function (point) {
  31861. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31862. var newPoint = new IndexedVector2(point, _this.elements.length);
  31863. result.push(newPoint);
  31864. _this.elements.push(newPoint);
  31865. }
  31866. });
  31867. return result;
  31868. };
  31869. PolygonPoints.prototype.computeBounds = function () {
  31870. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31871. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31872. this.elements.forEach(function (point) {
  31873. // x
  31874. if (point.x < lmin.x) {
  31875. lmin.x = point.x;
  31876. }
  31877. else if (point.x > lmax.x) {
  31878. lmax.x = point.x;
  31879. }
  31880. // y
  31881. if (point.y < lmin.y) {
  31882. lmin.y = point.y;
  31883. }
  31884. else if (point.y > lmax.y) {
  31885. lmax.y = point.y;
  31886. }
  31887. });
  31888. return {
  31889. min: lmin,
  31890. max: lmax,
  31891. width: lmax.x - lmin.x,
  31892. height: lmax.y - lmin.y
  31893. };
  31894. };
  31895. return PolygonPoints;
  31896. })();
  31897. var Polygon = (function () {
  31898. function Polygon() {
  31899. }
  31900. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31901. return [
  31902. new BABYLON.Vector2(xmin, ymin),
  31903. new BABYLON.Vector2(xmax, ymin),
  31904. new BABYLON.Vector2(xmax, ymax),
  31905. new BABYLON.Vector2(xmin, ymax)
  31906. ];
  31907. };
  31908. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31909. if (cx === void 0) { cx = 0; }
  31910. if (cy === void 0) { cy = 0; }
  31911. if (numberOfSides === void 0) { numberOfSides = 32; }
  31912. var result = new Array();
  31913. var angle = 0;
  31914. var increment = (Math.PI * 2) / numberOfSides;
  31915. for (var i = 0; i < numberOfSides; i++) {
  31916. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31917. angle -= increment;
  31918. }
  31919. return result;
  31920. };
  31921. Polygon.Parse = function (input) {
  31922. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31923. var i, result = [];
  31924. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31925. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31926. }
  31927. return result;
  31928. };
  31929. Polygon.StartingAt = function (x, y) {
  31930. return BABYLON.Path2.StartingAt(x, y);
  31931. };
  31932. return Polygon;
  31933. })();
  31934. BABYLON.Polygon = Polygon;
  31935. var PolygonMeshBuilder = (function () {
  31936. function PolygonMeshBuilder(name, contours, scene) {
  31937. this._points = new PolygonPoints();
  31938. this._outlinepoints = new PolygonPoints();
  31939. this._holes = [];
  31940. if (!("poly2tri" in window)) {
  31941. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31942. }
  31943. this._name = name;
  31944. this._scene = scene;
  31945. var points;
  31946. if (contours instanceof BABYLON.Path2) {
  31947. points = contours.getPoints();
  31948. }
  31949. else {
  31950. points = contours;
  31951. }
  31952. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31953. this._outlinepoints.add(points);
  31954. }
  31955. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31956. this._swctx.addHole(this._points.add(hole));
  31957. var holepoints = new PolygonPoints();
  31958. holepoints.add(hole);
  31959. this._holes.push(holepoints);
  31960. return this;
  31961. };
  31962. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31963. var _this = this;
  31964. if (updatable === void 0) { updatable = false; }
  31965. var result = new BABYLON.Mesh(this._name, this._scene);
  31966. var normals = [];
  31967. var positions = [];
  31968. var uvs = [];
  31969. var bounds = this._points.computeBounds();
  31970. this._points.elements.forEach(function (p) {
  31971. normals.push(0, 1.0, 0);
  31972. positions.push(p.x, 0, p.y);
  31973. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31974. });
  31975. var indices = [];
  31976. this._swctx.triangulate();
  31977. this._swctx.getTriangles().forEach(function (triangle) {
  31978. triangle.getPoints().forEach(function (point) {
  31979. indices.push(point.index);
  31980. });
  31981. });
  31982. if (depth > 0) {
  31983. var positionscount = (positions.length / 3); //get the current pointcount
  31984. this._points.elements.forEach(function (p) {
  31985. normals.push(0, -1.0, 0);
  31986. positions.push(p.x, -depth, p.y);
  31987. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31988. });
  31989. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31990. var p2;
  31991. var poscounter = 0;
  31992. this._swctx.getTriangles().forEach(function (triangle) {
  31993. triangle.getPoints().forEach(function (point) {
  31994. switch (poscounter) {
  31995. case 0:
  31996. p1 = point;
  31997. break;
  31998. case 1:
  31999. p2 = point;
  32000. break;
  32001. case 2:
  32002. indices.push(point.index + positionscount);
  32003. indices.push(p2.index + positionscount);
  32004. indices.push(p1.index + positionscount);
  32005. poscounter = -1;
  32006. break;
  32007. }
  32008. poscounter++;
  32009. //indices.push((<IndexedVector2>point).index + positionscount);
  32010. });
  32011. });
  32012. //Add the sides
  32013. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32014. this._holes.forEach(function (hole) {
  32015. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32016. });
  32017. }
  32018. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32019. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32020. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32021. result.setIndices(indices);
  32022. return result;
  32023. };
  32024. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32025. var StartIndex = positions.length / 3;
  32026. var ulength = 0;
  32027. for (var i = 0; i < points.elements.length; i++) {
  32028. var p = points.elements[i];
  32029. var p1;
  32030. if ((i + 1) > points.elements.length - 1) {
  32031. p1 = points.elements[0];
  32032. }
  32033. else {
  32034. p1 = points.elements[i + 1];
  32035. }
  32036. positions.push(p.x, 0, p.y);
  32037. positions.push(p.x, -depth, p.y);
  32038. positions.push(p1.x, 0, p1.y);
  32039. positions.push(p1.x, -depth, p1.y);
  32040. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32041. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32042. var v3 = v2.subtract(v1);
  32043. var v4 = new BABYLON.Vector3(0, 1, 0);
  32044. var vn = BABYLON.Vector3.Cross(v3, v4);
  32045. vn = vn.normalize();
  32046. uvs.push(ulength / bounds.width, 0);
  32047. uvs.push(ulength / bounds.width, 1);
  32048. ulength += v3.length();
  32049. uvs.push((ulength / bounds.width), 0);
  32050. uvs.push((ulength / bounds.width), 1);
  32051. if (!flip) {
  32052. normals.push(-vn.x, -vn.y, -vn.z);
  32053. normals.push(-vn.x, -vn.y, -vn.z);
  32054. normals.push(-vn.x, -vn.y, -vn.z);
  32055. normals.push(-vn.x, -vn.y, -vn.z);
  32056. indices.push(StartIndex);
  32057. indices.push(StartIndex + 1);
  32058. indices.push(StartIndex + 2);
  32059. indices.push(StartIndex + 1);
  32060. indices.push(StartIndex + 3);
  32061. indices.push(StartIndex + 2);
  32062. }
  32063. else {
  32064. normals.push(vn.x, vn.y, vn.z);
  32065. normals.push(vn.x, vn.y, vn.z);
  32066. normals.push(vn.x, vn.y, vn.z);
  32067. normals.push(vn.x, vn.y, vn.z);
  32068. indices.push(StartIndex);
  32069. indices.push(StartIndex + 2);
  32070. indices.push(StartIndex + 1);
  32071. indices.push(StartIndex + 1);
  32072. indices.push(StartIndex + 2);
  32073. indices.push(StartIndex + 3);
  32074. }
  32075. StartIndex += 4;
  32076. }
  32077. ;
  32078. };
  32079. return PolygonMeshBuilder;
  32080. })();
  32081. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32082. })(BABYLON || (BABYLON = {}));
  32083. var BABYLON;
  32084. (function (BABYLON) {
  32085. var Octree = (function () {
  32086. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32087. if (maxDepth === void 0) { maxDepth = 2; }
  32088. this.maxDepth = maxDepth;
  32089. this.dynamicContent = new Array();
  32090. this._maxBlockCapacity = maxBlockCapacity || 64;
  32091. this._selectionContent = new BABYLON.SmartArray(1024);
  32092. this._creationFunc = creationFunc;
  32093. }
  32094. // Methods
  32095. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32096. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32097. };
  32098. Octree.prototype.addMesh = function (entry) {
  32099. for (var index = 0; index < this.blocks.length; index++) {
  32100. var block = this.blocks[index];
  32101. block.addEntry(entry);
  32102. }
  32103. };
  32104. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32105. this._selectionContent.reset();
  32106. for (var index = 0; index < this.blocks.length; index++) {
  32107. var block = this.blocks[index];
  32108. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32109. }
  32110. if (allowDuplicate) {
  32111. this._selectionContent.concat(this.dynamicContent);
  32112. }
  32113. else {
  32114. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32115. }
  32116. return this._selectionContent;
  32117. };
  32118. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32119. this._selectionContent.reset();
  32120. for (var index = 0; index < this.blocks.length; index++) {
  32121. var block = this.blocks[index];
  32122. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32123. }
  32124. if (allowDuplicate) {
  32125. this._selectionContent.concat(this.dynamicContent);
  32126. }
  32127. else {
  32128. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32129. }
  32130. return this._selectionContent;
  32131. };
  32132. Octree.prototype.intersectsRay = function (ray) {
  32133. this._selectionContent.reset();
  32134. for (var index = 0; index < this.blocks.length; index++) {
  32135. var block = this.blocks[index];
  32136. block.intersectsRay(ray, this._selectionContent);
  32137. }
  32138. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32139. return this._selectionContent;
  32140. };
  32141. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32142. target.blocks = new Array();
  32143. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32144. // Segmenting space
  32145. for (var x = 0; x < 2; x++) {
  32146. for (var y = 0; y < 2; y++) {
  32147. for (var z = 0; z < 2; z++) {
  32148. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32149. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32150. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32151. block.addEntries(entries);
  32152. target.blocks.push(block);
  32153. }
  32154. }
  32155. }
  32156. };
  32157. Octree.CreationFuncForMeshes = function (entry, block) {
  32158. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32159. block.entries.push(entry);
  32160. }
  32161. };
  32162. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32163. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32164. block.entries.push(entry);
  32165. }
  32166. };
  32167. return Octree;
  32168. })();
  32169. BABYLON.Octree = Octree;
  32170. })(BABYLON || (BABYLON = {}));
  32171. var BABYLON;
  32172. (function (BABYLON) {
  32173. var OctreeBlock = (function () {
  32174. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32175. this.entries = new Array();
  32176. this._boundingVectors = new Array();
  32177. this._capacity = capacity;
  32178. this._depth = depth;
  32179. this._maxDepth = maxDepth;
  32180. this._creationFunc = creationFunc;
  32181. this._minPoint = minPoint;
  32182. this._maxPoint = maxPoint;
  32183. this._boundingVectors.push(minPoint.clone());
  32184. this._boundingVectors.push(maxPoint.clone());
  32185. this._boundingVectors.push(minPoint.clone());
  32186. this._boundingVectors[2].x = maxPoint.x;
  32187. this._boundingVectors.push(minPoint.clone());
  32188. this._boundingVectors[3].y = maxPoint.y;
  32189. this._boundingVectors.push(minPoint.clone());
  32190. this._boundingVectors[4].z = maxPoint.z;
  32191. this._boundingVectors.push(maxPoint.clone());
  32192. this._boundingVectors[5].z = minPoint.z;
  32193. this._boundingVectors.push(maxPoint.clone());
  32194. this._boundingVectors[6].x = minPoint.x;
  32195. this._boundingVectors.push(maxPoint.clone());
  32196. this._boundingVectors[7].y = minPoint.y;
  32197. }
  32198. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32199. // Property
  32200. get: function () {
  32201. return this._capacity;
  32202. },
  32203. enumerable: true,
  32204. configurable: true
  32205. });
  32206. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32207. get: function () {
  32208. return this._minPoint;
  32209. },
  32210. enumerable: true,
  32211. configurable: true
  32212. });
  32213. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32214. get: function () {
  32215. return this._maxPoint;
  32216. },
  32217. enumerable: true,
  32218. configurable: true
  32219. });
  32220. // Methods
  32221. OctreeBlock.prototype.addEntry = function (entry) {
  32222. if (this.blocks) {
  32223. for (var index = 0; index < this.blocks.length; index++) {
  32224. var block = this.blocks[index];
  32225. block.addEntry(entry);
  32226. }
  32227. return;
  32228. }
  32229. this._creationFunc(entry, this);
  32230. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32231. this.createInnerBlocks();
  32232. }
  32233. };
  32234. OctreeBlock.prototype.addEntries = function (entries) {
  32235. for (var index = 0; index < entries.length; index++) {
  32236. var mesh = entries[index];
  32237. this.addEntry(mesh);
  32238. }
  32239. };
  32240. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32241. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32242. if (this.blocks) {
  32243. for (var index = 0; index < this.blocks.length; index++) {
  32244. var block = this.blocks[index];
  32245. block.select(frustumPlanes, selection, allowDuplicate);
  32246. }
  32247. return;
  32248. }
  32249. if (allowDuplicate) {
  32250. selection.concat(this.entries);
  32251. }
  32252. else {
  32253. selection.concatWithNoDuplicate(this.entries);
  32254. }
  32255. }
  32256. };
  32257. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32258. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32259. if (this.blocks) {
  32260. for (var index = 0; index < this.blocks.length; index++) {
  32261. var block = this.blocks[index];
  32262. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32263. }
  32264. return;
  32265. }
  32266. if (allowDuplicate) {
  32267. selection.concat(this.entries);
  32268. }
  32269. else {
  32270. selection.concatWithNoDuplicate(this.entries);
  32271. }
  32272. }
  32273. };
  32274. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32275. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32276. if (this.blocks) {
  32277. for (var index = 0; index < this.blocks.length; index++) {
  32278. var block = this.blocks[index];
  32279. block.intersectsRay(ray, selection);
  32280. }
  32281. return;
  32282. }
  32283. selection.concatWithNoDuplicate(this.entries);
  32284. }
  32285. };
  32286. OctreeBlock.prototype.createInnerBlocks = function () {
  32287. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32288. };
  32289. return OctreeBlock;
  32290. })();
  32291. BABYLON.OctreeBlock = OctreeBlock;
  32292. })(BABYLON || (BABYLON = {}));
  32293. var BABYLON;
  32294. (function (BABYLON) {
  32295. var BlurPostProcess = (function (_super) {
  32296. __extends(BlurPostProcess, _super);
  32297. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32298. var _this = this;
  32299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32300. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32301. this.direction = direction;
  32302. this.blurWidth = blurWidth;
  32303. this.onApply = function (effect) {
  32304. effect.setFloat2("screenSize", _this.width, _this.height);
  32305. effect.setVector2("direction", _this.direction);
  32306. effect.setFloat("blurWidth", _this.blurWidth);
  32307. };
  32308. }
  32309. return BlurPostProcess;
  32310. })(BABYLON.PostProcess);
  32311. BABYLON.BlurPostProcess = BlurPostProcess;
  32312. })(BABYLON || (BABYLON = {}));
  32313. var BABYLON;
  32314. (function (BABYLON) {
  32315. var RefractionPostProcess = (function (_super) {
  32316. __extends(RefractionPostProcess, _super);
  32317. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32318. var _this = this;
  32319. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32320. this.color = color;
  32321. this.depth = depth;
  32322. this.colorLevel = colorLevel;
  32323. this.onActivate = function (cam) {
  32324. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32325. };
  32326. this.onApply = function (effect) {
  32327. effect.setColor3("baseColor", _this.color);
  32328. effect.setFloat("depth", _this.depth);
  32329. effect.setFloat("colorLevel", _this.colorLevel);
  32330. effect.setTexture("refractionSampler", _this._refRexture);
  32331. };
  32332. }
  32333. // Methods
  32334. RefractionPostProcess.prototype.dispose = function (camera) {
  32335. if (this._refRexture) {
  32336. this._refRexture.dispose();
  32337. }
  32338. _super.prototype.dispose.call(this, camera);
  32339. };
  32340. return RefractionPostProcess;
  32341. })(BABYLON.PostProcess);
  32342. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32343. })(BABYLON || (BABYLON = {}));
  32344. var BABYLON;
  32345. (function (BABYLON) {
  32346. var BlackAndWhitePostProcess = (function (_super) {
  32347. __extends(BlackAndWhitePostProcess, _super);
  32348. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32349. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32350. }
  32351. return BlackAndWhitePostProcess;
  32352. })(BABYLON.PostProcess);
  32353. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32354. })(BABYLON || (BABYLON = {}));
  32355. var BABYLON;
  32356. (function (BABYLON) {
  32357. var ConvolutionPostProcess = (function (_super) {
  32358. __extends(ConvolutionPostProcess, _super);
  32359. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32360. var _this = this;
  32361. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32362. this.kernel = kernel;
  32363. this.onApply = function (effect) {
  32364. effect.setFloat2("screenSize", _this.width, _this.height);
  32365. effect.setArray("kernel", _this.kernel);
  32366. };
  32367. }
  32368. // Statics
  32369. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32370. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32371. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32372. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32373. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32374. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32375. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32376. return ConvolutionPostProcess;
  32377. })(BABYLON.PostProcess);
  32378. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32379. })(BABYLON || (BABYLON = {}));
  32380. var BABYLON;
  32381. (function (BABYLON) {
  32382. var FilterPostProcess = (function (_super) {
  32383. __extends(FilterPostProcess, _super);
  32384. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32385. var _this = this;
  32386. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32387. this.kernelMatrix = kernelMatrix;
  32388. this.onApply = function (effect) {
  32389. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32390. };
  32391. }
  32392. return FilterPostProcess;
  32393. })(BABYLON.PostProcess);
  32394. BABYLON.FilterPostProcess = FilterPostProcess;
  32395. })(BABYLON || (BABYLON = {}));
  32396. var BABYLON;
  32397. (function (BABYLON) {
  32398. var FxaaPostProcess = (function (_super) {
  32399. __extends(FxaaPostProcess, _super);
  32400. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32401. var _this = this;
  32402. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32403. this.onSizeChanged = function () {
  32404. _this.texelWidth = 1.0 / _this.width;
  32405. _this.texelHeight = 1.0 / _this.height;
  32406. };
  32407. this.onApply = function (effect) {
  32408. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32409. };
  32410. }
  32411. return FxaaPostProcess;
  32412. })(BABYLON.PostProcess);
  32413. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32414. })(BABYLON || (BABYLON = {}));
  32415. var BABYLON;
  32416. (function (BABYLON) {
  32417. var StereoscopicInterlacePostProcess = (function (_super) {
  32418. __extends(StereoscopicInterlacePostProcess, _super);
  32419. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32420. var _this = this;
  32421. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32422. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32423. this.onSizeChanged = function () {
  32424. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32425. };
  32426. this.onApply = function (effect) {
  32427. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32428. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32429. };
  32430. }
  32431. return StereoscopicInterlacePostProcess;
  32432. })(BABYLON.PostProcess);
  32433. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32434. })(BABYLON || (BABYLON = {}));
  32435. var BABYLON;
  32436. (function (BABYLON) {
  32437. var LensFlare = (function () {
  32438. function LensFlare(size, position, color, imgUrl, system) {
  32439. this.size = size;
  32440. this.position = position;
  32441. this.dispose = function () {
  32442. if (this.texture) {
  32443. this.texture.dispose();
  32444. }
  32445. // Remove from scene
  32446. var index = this._system.lensFlares.indexOf(this);
  32447. this._system.lensFlares.splice(index, 1);
  32448. };
  32449. this.color = color || new BABYLON.Color3(1, 1, 1);
  32450. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32451. this._system = system;
  32452. system.lensFlares.push(this);
  32453. }
  32454. return LensFlare;
  32455. })();
  32456. BABYLON.LensFlare = LensFlare;
  32457. })(BABYLON || (BABYLON = {}));
  32458. var BABYLON;
  32459. (function (BABYLON) {
  32460. var LensFlareSystem = (function () {
  32461. function LensFlareSystem(name, emitter, scene) {
  32462. this.name = name;
  32463. this.lensFlares = new Array();
  32464. this.borderLimit = 300;
  32465. this.layerMask = 0x0FFFFFFF;
  32466. this._vertexDeclaration = [2];
  32467. this._vertexStrideSize = 2 * 4;
  32468. this._isEnabled = true;
  32469. this._scene = scene;
  32470. this._emitter = emitter;
  32471. scene.lensFlareSystems.push(this);
  32472. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32473. // VBO
  32474. var vertices = [];
  32475. vertices.push(1, 1);
  32476. vertices.push(-1, 1);
  32477. vertices.push(-1, -1);
  32478. vertices.push(1, -1);
  32479. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32480. // Indices
  32481. var indices = [];
  32482. indices.push(0);
  32483. indices.push(1);
  32484. indices.push(2);
  32485. indices.push(0);
  32486. indices.push(2);
  32487. indices.push(3);
  32488. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32489. // Effects
  32490. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32491. }
  32492. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32493. get: function () {
  32494. return this._isEnabled;
  32495. },
  32496. set: function (value) {
  32497. this._isEnabled = value;
  32498. },
  32499. enumerable: true,
  32500. configurable: true
  32501. });
  32502. LensFlareSystem.prototype.getScene = function () {
  32503. return this._scene;
  32504. };
  32505. LensFlareSystem.prototype.getEmitter = function () {
  32506. return this._emitter;
  32507. };
  32508. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32509. this._emitter = newEmitter;
  32510. };
  32511. LensFlareSystem.prototype.getEmitterPosition = function () {
  32512. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32513. };
  32514. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32515. var position = this.getEmitterPosition();
  32516. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32517. this._positionX = position.x;
  32518. this._positionY = position.y;
  32519. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32520. if (position.z > 0) {
  32521. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32522. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32523. return true;
  32524. }
  32525. }
  32526. return false;
  32527. };
  32528. LensFlareSystem.prototype._isVisible = function () {
  32529. if (!this._isEnabled) {
  32530. return false;
  32531. }
  32532. var emitterPosition = this.getEmitterPosition();
  32533. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32534. var distance = direction.length();
  32535. direction.normalize();
  32536. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32537. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32538. return !pickInfo.hit || pickInfo.distance > distance;
  32539. };
  32540. LensFlareSystem.prototype.render = function () {
  32541. if (!this._effect.isReady())
  32542. return false;
  32543. var engine = this._scene.getEngine();
  32544. var viewport = this._scene.activeCamera.viewport;
  32545. var globalViewport = viewport.toGlobal(engine);
  32546. // Position
  32547. if (!this.computeEffectivePosition(globalViewport)) {
  32548. return false;
  32549. }
  32550. // Visibility
  32551. if (!this._isVisible()) {
  32552. return false;
  32553. }
  32554. // Intensity
  32555. var awayX;
  32556. var awayY;
  32557. if (this._positionX < this.borderLimit + globalViewport.x) {
  32558. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32559. }
  32560. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32561. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32562. }
  32563. else {
  32564. awayX = 0;
  32565. }
  32566. if (this._positionY < this.borderLimit + globalViewport.y) {
  32567. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32568. }
  32569. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32570. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32571. }
  32572. else {
  32573. awayY = 0;
  32574. }
  32575. var away = (awayX > awayY) ? awayX : awayY;
  32576. if (away > this.borderLimit) {
  32577. away = this.borderLimit;
  32578. }
  32579. var intensity = 1.0 - (away / this.borderLimit);
  32580. if (intensity < 0) {
  32581. return false;
  32582. }
  32583. if (intensity > 1.0) {
  32584. intensity = 1.0;
  32585. }
  32586. // Position
  32587. var centerX = globalViewport.x + globalViewport.width / 2;
  32588. var centerY = globalViewport.y + globalViewport.height / 2;
  32589. var distX = centerX - this._positionX;
  32590. var distY = centerY - this._positionY;
  32591. // Effects
  32592. engine.enableEffect(this._effect);
  32593. engine.setState(false);
  32594. engine.setDepthBuffer(false);
  32595. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32596. // VBOs
  32597. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32598. // Flares
  32599. for (var index = 0; index < this.lensFlares.length; index++) {
  32600. var flare = this.lensFlares[index];
  32601. var x = centerX - (distX * flare.position);
  32602. var y = centerY - (distY * flare.position);
  32603. var cw = flare.size;
  32604. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32605. var cx = 2 * (x / globalViewport.width) - 1.0;
  32606. var cy = 1.0 - 2 * (y / globalViewport.height);
  32607. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32608. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32609. // Texture
  32610. this._effect.setTexture("textureSampler", flare.texture);
  32611. // Color
  32612. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32613. // Draw order
  32614. engine.draw(true, 0, 6);
  32615. }
  32616. engine.setDepthBuffer(true);
  32617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32618. return true;
  32619. };
  32620. LensFlareSystem.prototype.dispose = function () {
  32621. if (this._vertexBuffer) {
  32622. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32623. this._vertexBuffer = null;
  32624. }
  32625. if (this._indexBuffer) {
  32626. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32627. this._indexBuffer = null;
  32628. }
  32629. while (this.lensFlares.length) {
  32630. this.lensFlares[0].dispose();
  32631. }
  32632. // Remove from scene
  32633. var index = this._scene.lensFlareSystems.indexOf(this);
  32634. this._scene.lensFlareSystems.splice(index, 1);
  32635. };
  32636. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  32637. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32638. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32639. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32640. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32641. var parsedFlare = parsedLensFlareSystem.flares[index];
  32642. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32643. }
  32644. return lensFlareSystem;
  32645. };
  32646. LensFlareSystem.prototype.serialize = function () {
  32647. var serializationObject = {};
  32648. serializationObject.emitterId = this.getEmitter().id;
  32649. serializationObject.borderLimit = this.borderLimit;
  32650. serializationObject.flares = [];
  32651. for (var index = 0; index < this.lensFlares.length; index++) {
  32652. var flare = this.lensFlares[index];
  32653. serializationObject.flares.push({
  32654. size: flare.size,
  32655. position: flare.position,
  32656. color: flare.color.asArray(),
  32657. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32658. });
  32659. }
  32660. return serializationObject;
  32661. };
  32662. return LensFlareSystem;
  32663. })();
  32664. BABYLON.LensFlareSystem = LensFlareSystem;
  32665. })(BABYLON || (BABYLON = {}));
  32666. var BABYLON;
  32667. (function (BABYLON) {
  32668. // We're mainly based on the logic defined into the FreeCamera code
  32669. var DeviceOrientationCamera = (function (_super) {
  32670. __extends(DeviceOrientationCamera, _super);
  32671. function DeviceOrientationCamera(name, position, scene) {
  32672. var _this = this;
  32673. _super.call(this, name, position, scene);
  32674. this._offsetX = null;
  32675. this._offsetY = null;
  32676. this._orientationGamma = 0;
  32677. this._orientationBeta = 0;
  32678. this._initialOrientationGamma = 0;
  32679. this._initialOrientationBeta = 0;
  32680. this.angularSensibility = 10000.0;
  32681. this.moveSensibility = 50.0;
  32682. window.addEventListener("resize", function () {
  32683. _this._initialOrientationGamma = null;
  32684. }, false);
  32685. }
  32686. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32687. var _this = this;
  32688. if (this._attachedCanvas) {
  32689. return;
  32690. }
  32691. this._attachedCanvas = canvas;
  32692. if (!this._orientationChanged) {
  32693. this._orientationChanged = function (evt) {
  32694. if (!_this._initialOrientationGamma) {
  32695. _this._initialOrientationGamma = evt.gamma;
  32696. _this._initialOrientationBeta = evt.beta;
  32697. }
  32698. _this._orientationGamma = evt.gamma;
  32699. _this._orientationBeta = evt.beta;
  32700. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32701. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32702. };
  32703. }
  32704. window.addEventListener("deviceorientation", this._orientationChanged);
  32705. };
  32706. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32707. if (this._attachedCanvas !== canvas) {
  32708. return;
  32709. }
  32710. window.removeEventListener("deviceorientation", this._orientationChanged);
  32711. this._attachedCanvas = null;
  32712. this._orientationGamma = 0;
  32713. this._orientationBeta = 0;
  32714. this._initialOrientationGamma = 0;
  32715. this._initialOrientationBeta = 0;
  32716. };
  32717. DeviceOrientationCamera.prototype._checkInputs = function () {
  32718. if (!this._offsetX) {
  32719. return;
  32720. }
  32721. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32722. var speed = this._computeLocalCameraSpeed();
  32723. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32724. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32725. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32726. _super.prototype._checkInputs.call(this);
  32727. };
  32728. return DeviceOrientationCamera;
  32729. })(BABYLON.FreeCamera);
  32730. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32731. })(BABYLON || (BABYLON = {}));
  32732. var BABYLON;
  32733. (function (BABYLON) {
  32734. var Gamepads = (function () {
  32735. function Gamepads(ongamedpadconnected) {
  32736. var _this = this;
  32737. this.babylonGamepads = [];
  32738. this.oneGamepadConnected = false;
  32739. this.isMonitoring = false;
  32740. this.gamepadEventSupported = 'GamepadEvent' in window;
  32741. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32742. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32743. 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=";
  32744. this._callbackGamepadConnected = ongamedpadconnected;
  32745. if (this.gamepadSupportAvailable) {
  32746. // Checking if the gamepad connected event is supported (like in Firefox)
  32747. if (this.gamepadEventSupported) {
  32748. window.addEventListener('gamepadconnected', function (evt) {
  32749. _this._onGamepadConnected(evt);
  32750. }, false);
  32751. window.addEventListener('gamepaddisconnected', function (evt) {
  32752. _this._onGamepadDisconnected(evt);
  32753. }, false);
  32754. }
  32755. else {
  32756. this._startMonitoringGamepads();
  32757. }
  32758. if (!this.oneGamepadConnected) {
  32759. this._insertGamepadDOMInstructions();
  32760. }
  32761. }
  32762. else {
  32763. this._insertGamepadDOMNotSupported();
  32764. }
  32765. }
  32766. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32767. Gamepads.gamepadDOMInfo = document.createElement("div");
  32768. var buttonAImage = document.createElement("img");
  32769. buttonAImage.src = this.buttonADataURL;
  32770. var spanMessage = document.createElement("span");
  32771. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32772. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32773. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32774. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32775. Gamepads.gamepadDOMInfo.style.width = "100%";
  32776. Gamepads.gamepadDOMInfo.style.height = "48px";
  32777. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32778. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32779. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32780. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32781. buttonAImage.style.position = "relative";
  32782. buttonAImage.style.bottom = "8px";
  32783. spanMessage.style.position = "relative";
  32784. spanMessage.style.fontSize = "32px";
  32785. spanMessage.style.bottom = "32px";
  32786. spanMessage.style.color = "green";
  32787. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32788. };
  32789. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32790. Gamepads.gamepadDOMInfo = document.createElement("div");
  32791. var spanMessage = document.createElement("span");
  32792. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32793. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32794. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32795. Gamepads.gamepadDOMInfo.style.width = "100%";
  32796. Gamepads.gamepadDOMInfo.style.height = "40px";
  32797. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32798. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32799. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32800. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32801. spanMessage.style.position = "relative";
  32802. spanMessage.style.fontSize = "32px";
  32803. spanMessage.style.color = "red";
  32804. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32805. };
  32806. Gamepads.prototype.dispose = function () {
  32807. if (Gamepads.gamepadDOMInfo) {
  32808. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32809. }
  32810. };
  32811. Gamepads.prototype._onGamepadConnected = function (evt) {
  32812. var newGamepad = this._addNewGamepad(evt.gamepad);
  32813. if (this._callbackGamepadConnected)
  32814. this._callbackGamepadConnected(newGamepad);
  32815. this._startMonitoringGamepads();
  32816. };
  32817. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32818. if (!this.oneGamepadConnected) {
  32819. this.oneGamepadConnected = true;
  32820. if (Gamepads.gamepadDOMInfo) {
  32821. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32822. Gamepads.gamepadDOMInfo = null;
  32823. }
  32824. }
  32825. var newGamepad;
  32826. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32827. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32828. }
  32829. else {
  32830. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32831. }
  32832. this.babylonGamepads.push(newGamepad);
  32833. return newGamepad;
  32834. };
  32835. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32836. // Remove the gamepad from the list of gamepads to monitor.
  32837. for (var i in this.babylonGamepads) {
  32838. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32839. this.babylonGamepads.splice(i, 1);
  32840. break;
  32841. }
  32842. }
  32843. // If no gamepads are left, stop the polling loop.
  32844. if (this.babylonGamepads.length == 0) {
  32845. this._stopMonitoringGamepads();
  32846. }
  32847. };
  32848. Gamepads.prototype._startMonitoringGamepads = function () {
  32849. if (!this.isMonitoring) {
  32850. this.isMonitoring = true;
  32851. this._checkGamepadsStatus();
  32852. }
  32853. };
  32854. Gamepads.prototype._stopMonitoringGamepads = function () {
  32855. this.isMonitoring = false;
  32856. };
  32857. Gamepads.prototype._checkGamepadsStatus = function () {
  32858. var _this = this;
  32859. // updating gamepad objects
  32860. this._updateGamepadObjects();
  32861. for (var i in this.babylonGamepads) {
  32862. this.babylonGamepads[i].update();
  32863. }
  32864. if (this.isMonitoring) {
  32865. if (window.requestAnimationFrame) {
  32866. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32867. }
  32868. else if (window.mozRequestAnimationFrame) {
  32869. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32870. }
  32871. else if (window.webkitRequestAnimationFrame) {
  32872. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32873. }
  32874. }
  32875. };
  32876. // This function is called only on Chrome, which does not yet support
  32877. // connection/disconnection events, but requires you to monitor
  32878. // an array for changes.
  32879. Gamepads.prototype._updateGamepadObjects = function () {
  32880. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32881. for (var i = 0; i < gamepads.length; i++) {
  32882. if (gamepads[i]) {
  32883. if (!(gamepads[i].index in this.babylonGamepads)) {
  32884. var newGamepad = this._addNewGamepad(gamepads[i]);
  32885. if (this._callbackGamepadConnected) {
  32886. this._callbackGamepadConnected(newGamepad);
  32887. }
  32888. }
  32889. else {
  32890. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32891. }
  32892. }
  32893. }
  32894. };
  32895. return Gamepads;
  32896. })();
  32897. BABYLON.Gamepads = Gamepads;
  32898. var StickValues = (function () {
  32899. function StickValues(x, y) {
  32900. this.x = x;
  32901. this.y = y;
  32902. }
  32903. return StickValues;
  32904. })();
  32905. BABYLON.StickValues = StickValues;
  32906. var Gamepad = (function () {
  32907. function Gamepad(id, index, browserGamepad) {
  32908. this.id = id;
  32909. this.index = index;
  32910. this.browserGamepad = browserGamepad;
  32911. if (this.browserGamepad.axes.length >= 2) {
  32912. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32913. }
  32914. if (this.browserGamepad.axes.length >= 4) {
  32915. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32916. }
  32917. }
  32918. Gamepad.prototype.onleftstickchanged = function (callback) {
  32919. this._onleftstickchanged = callback;
  32920. };
  32921. Gamepad.prototype.onrightstickchanged = function (callback) {
  32922. this._onrightstickchanged = callback;
  32923. };
  32924. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32925. get: function () {
  32926. return this._leftStick;
  32927. },
  32928. set: function (newValues) {
  32929. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32930. this._onleftstickchanged(newValues);
  32931. }
  32932. this._leftStick = newValues;
  32933. },
  32934. enumerable: true,
  32935. configurable: true
  32936. });
  32937. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32938. get: function () {
  32939. return this._rightStick;
  32940. },
  32941. set: function (newValues) {
  32942. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32943. this._onrightstickchanged(newValues);
  32944. }
  32945. this._rightStick = newValues;
  32946. },
  32947. enumerable: true,
  32948. configurable: true
  32949. });
  32950. Gamepad.prototype.update = function () {
  32951. if (this._leftStick) {
  32952. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32953. }
  32954. if (this._rightStick) {
  32955. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32956. }
  32957. };
  32958. return Gamepad;
  32959. })();
  32960. BABYLON.Gamepad = Gamepad;
  32961. var GenericPad = (function (_super) {
  32962. __extends(GenericPad, _super);
  32963. function GenericPad(id, index, gamepad) {
  32964. _super.call(this, id, index, gamepad);
  32965. this.id = id;
  32966. this.index = index;
  32967. this.gamepad = gamepad;
  32968. this._buttons = new Array(gamepad.buttons.length);
  32969. }
  32970. GenericPad.prototype.onbuttondown = function (callback) {
  32971. this._onbuttondown = callback;
  32972. };
  32973. GenericPad.prototype.onbuttonup = function (callback) {
  32974. this._onbuttonup = callback;
  32975. };
  32976. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32977. if (newValue !== currentValue) {
  32978. if (this._onbuttondown && newValue === 1) {
  32979. this._onbuttondown(buttonIndex);
  32980. }
  32981. if (this._onbuttonup && newValue === 0) {
  32982. this._onbuttonup(buttonIndex);
  32983. }
  32984. }
  32985. return newValue;
  32986. };
  32987. GenericPad.prototype.update = function () {
  32988. _super.prototype.update.call(this);
  32989. for (var index = 0; index < this._buttons.length; index++) {
  32990. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32991. }
  32992. };
  32993. return GenericPad;
  32994. })(Gamepad);
  32995. BABYLON.GenericPad = GenericPad;
  32996. (function (Xbox360Button) {
  32997. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32998. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32999. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33000. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33001. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33002. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33003. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33004. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33005. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33006. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33007. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33008. var Xbox360Button = BABYLON.Xbox360Button;
  33009. (function (Xbox360Dpad) {
  33010. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33011. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33012. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33013. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33014. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33015. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33016. var Xbox360Pad = (function (_super) {
  33017. __extends(Xbox360Pad, _super);
  33018. function Xbox360Pad() {
  33019. _super.apply(this, arguments);
  33020. this._leftTrigger = 0;
  33021. this._rightTrigger = 0;
  33022. this._buttonA = 0;
  33023. this._buttonB = 0;
  33024. this._buttonX = 0;
  33025. this._buttonY = 0;
  33026. this._buttonBack = 0;
  33027. this._buttonStart = 0;
  33028. this._buttonLB = 0;
  33029. this._buttonRB = 0;
  33030. this._buttonLeftStick = 0;
  33031. this._buttonRightStick = 0;
  33032. this._dPadUp = 0;
  33033. this._dPadDown = 0;
  33034. this._dPadLeft = 0;
  33035. this._dPadRight = 0;
  33036. }
  33037. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33038. this._onlefttriggerchanged = callback;
  33039. };
  33040. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33041. this._onrighttriggerchanged = callback;
  33042. };
  33043. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33044. get: function () {
  33045. return this._leftTrigger;
  33046. },
  33047. set: function (newValue) {
  33048. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33049. this._onlefttriggerchanged(newValue);
  33050. }
  33051. this._leftTrigger = newValue;
  33052. },
  33053. enumerable: true,
  33054. configurable: true
  33055. });
  33056. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33057. get: function () {
  33058. return this._rightTrigger;
  33059. },
  33060. set: function (newValue) {
  33061. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33062. this._onrighttriggerchanged(newValue);
  33063. }
  33064. this._rightTrigger = newValue;
  33065. },
  33066. enumerable: true,
  33067. configurable: true
  33068. });
  33069. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33070. this._onbuttondown = callback;
  33071. };
  33072. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33073. this._onbuttonup = callback;
  33074. };
  33075. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33076. this._ondpaddown = callback;
  33077. };
  33078. Xbox360Pad.prototype.ondpadup = function (callback) {
  33079. this._ondpadup = callback;
  33080. };
  33081. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33082. if (newValue !== currentValue) {
  33083. if (this._onbuttondown && newValue === 1) {
  33084. this._onbuttondown(buttonType);
  33085. }
  33086. if (this._onbuttonup && newValue === 0) {
  33087. this._onbuttonup(buttonType);
  33088. }
  33089. }
  33090. return newValue;
  33091. };
  33092. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33093. if (newValue !== currentValue) {
  33094. if (this._ondpaddown && newValue === 1) {
  33095. this._ondpaddown(buttonType);
  33096. }
  33097. if (this._ondpadup && newValue === 0) {
  33098. this._ondpadup(buttonType);
  33099. }
  33100. }
  33101. return newValue;
  33102. };
  33103. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33104. get: function () {
  33105. return this._buttonA;
  33106. },
  33107. set: function (value) {
  33108. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33109. },
  33110. enumerable: true,
  33111. configurable: true
  33112. });
  33113. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33114. get: function () {
  33115. return this._buttonB;
  33116. },
  33117. set: function (value) {
  33118. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33119. },
  33120. enumerable: true,
  33121. configurable: true
  33122. });
  33123. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33124. get: function () {
  33125. return this._buttonX;
  33126. },
  33127. set: function (value) {
  33128. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33129. },
  33130. enumerable: true,
  33131. configurable: true
  33132. });
  33133. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33134. get: function () {
  33135. return this._buttonY;
  33136. },
  33137. set: function (value) {
  33138. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33139. },
  33140. enumerable: true,
  33141. configurable: true
  33142. });
  33143. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33144. get: function () {
  33145. return this._buttonStart;
  33146. },
  33147. set: function (value) {
  33148. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33149. },
  33150. enumerable: true,
  33151. configurable: true
  33152. });
  33153. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33154. get: function () {
  33155. return this._buttonBack;
  33156. },
  33157. set: function (value) {
  33158. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33159. },
  33160. enumerable: true,
  33161. configurable: true
  33162. });
  33163. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33164. get: function () {
  33165. return this._buttonLB;
  33166. },
  33167. set: function (value) {
  33168. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33169. },
  33170. enumerable: true,
  33171. configurable: true
  33172. });
  33173. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33174. get: function () {
  33175. return this._buttonRB;
  33176. },
  33177. set: function (value) {
  33178. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33179. },
  33180. enumerable: true,
  33181. configurable: true
  33182. });
  33183. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33184. get: function () {
  33185. return this._buttonLeftStick;
  33186. },
  33187. set: function (value) {
  33188. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33189. },
  33190. enumerable: true,
  33191. configurable: true
  33192. });
  33193. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33194. get: function () {
  33195. return this._buttonRightStick;
  33196. },
  33197. set: function (value) {
  33198. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33204. get: function () {
  33205. return this._dPadUp;
  33206. },
  33207. set: function (value) {
  33208. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33209. },
  33210. enumerable: true,
  33211. configurable: true
  33212. });
  33213. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33214. get: function () {
  33215. return this._dPadDown;
  33216. },
  33217. set: function (value) {
  33218. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33219. },
  33220. enumerable: true,
  33221. configurable: true
  33222. });
  33223. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33224. get: function () {
  33225. return this._dPadLeft;
  33226. },
  33227. set: function (value) {
  33228. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33229. },
  33230. enumerable: true,
  33231. configurable: true
  33232. });
  33233. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33234. get: function () {
  33235. return this._dPadRight;
  33236. },
  33237. set: function (value) {
  33238. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33239. },
  33240. enumerable: true,
  33241. configurable: true
  33242. });
  33243. Xbox360Pad.prototype.update = function () {
  33244. _super.prototype.update.call(this);
  33245. this.buttonA = this.browserGamepad.buttons[0].value;
  33246. this.buttonB = this.browserGamepad.buttons[1].value;
  33247. this.buttonX = this.browserGamepad.buttons[2].value;
  33248. this.buttonY = this.browserGamepad.buttons[3].value;
  33249. this.buttonLB = this.browserGamepad.buttons[4].value;
  33250. this.buttonRB = this.browserGamepad.buttons[5].value;
  33251. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33252. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33253. this.buttonBack = this.browserGamepad.buttons[8].value;
  33254. this.buttonStart = this.browserGamepad.buttons[9].value;
  33255. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33256. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33257. this.dPadUp = this.browserGamepad.buttons[12].value;
  33258. this.dPadDown = this.browserGamepad.buttons[13].value;
  33259. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33260. this.dPadRight = this.browserGamepad.buttons[15].value;
  33261. };
  33262. return Xbox360Pad;
  33263. })(Gamepad);
  33264. BABYLON.Xbox360Pad = Xbox360Pad;
  33265. })(BABYLON || (BABYLON = {}));
  33266. var BABYLON;
  33267. (function (BABYLON) {
  33268. // We're mainly based on the logic defined into the FreeCamera code
  33269. var GamepadCamera = (function (_super) {
  33270. __extends(GamepadCamera, _super);
  33271. function GamepadCamera(name, position, scene) {
  33272. var _this = this;
  33273. _super.call(this, name, position, scene);
  33274. this.angularSensibility = 200;
  33275. this.moveSensibility = 75;
  33276. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33277. }
  33278. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33279. // Only the first gamepad can control the camera
  33280. if (gamepad.index === 0) {
  33281. this._gamepad = gamepad;
  33282. }
  33283. };
  33284. GamepadCamera.prototype._checkInputs = function () {
  33285. if (this._gamepad) {
  33286. var LSValues = this._gamepad.leftStick;
  33287. var normalizedLX = LSValues.x / this.moveSensibility;
  33288. var normalizedLY = LSValues.y / this.moveSensibility;
  33289. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33290. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33291. var RSValues = this._gamepad.rightStick;
  33292. var normalizedRX = RSValues.x / this.angularSensibility;
  33293. var normalizedRY = RSValues.y / this.angularSensibility;
  33294. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33295. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33296. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33297. var speed = this._computeLocalCameraSpeed() * 50.0;
  33298. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33299. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33300. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33301. }
  33302. _super.prototype._checkInputs.call(this);
  33303. };
  33304. GamepadCamera.prototype.dispose = function () {
  33305. this._gamepads.dispose();
  33306. _super.prototype.dispose.call(this);
  33307. };
  33308. return GamepadCamera;
  33309. })(BABYLON.FreeCamera);
  33310. BABYLON.GamepadCamera = GamepadCamera;
  33311. })(BABYLON || (BABYLON = {}));
  33312. var BABYLON;
  33313. (function (BABYLON) {
  33314. var Analyser = (function () {
  33315. function Analyser(scene) {
  33316. this.SMOOTHING = 0.75;
  33317. this.FFT_SIZE = 512;
  33318. this.BARGRAPHAMPLITUDE = 256;
  33319. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33320. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33321. this._scene = scene;
  33322. this._audioEngine = BABYLON.Engine.audioEngine;
  33323. if (this._audioEngine.canUseWebAudio) {
  33324. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33325. this._webAudioAnalyser.minDecibels = -140;
  33326. this._webAudioAnalyser.maxDecibels = 0;
  33327. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33328. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33329. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33330. }
  33331. }
  33332. Analyser.prototype.getFrequencyBinCount = function () {
  33333. if (this._audioEngine.canUseWebAudio) {
  33334. return this._webAudioAnalyser.frequencyBinCount;
  33335. }
  33336. else {
  33337. return 0;
  33338. }
  33339. };
  33340. Analyser.prototype.getByteFrequencyData = function () {
  33341. if (this._audioEngine.canUseWebAudio) {
  33342. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33343. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33344. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33345. }
  33346. return this._byteFreqs;
  33347. };
  33348. Analyser.prototype.getByteTimeDomainData = function () {
  33349. if (this._audioEngine.canUseWebAudio) {
  33350. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33351. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33352. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33353. }
  33354. return this._byteTime;
  33355. };
  33356. Analyser.prototype.getFloatFrequencyData = function () {
  33357. if (this._audioEngine.canUseWebAudio) {
  33358. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33359. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33360. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33361. }
  33362. return this._floatFreqs;
  33363. };
  33364. Analyser.prototype.drawDebugCanvas = function () {
  33365. var _this = this;
  33366. if (this._audioEngine.canUseWebAudio) {
  33367. if (!this._debugCanvas) {
  33368. this._debugCanvas = document.createElement("canvas");
  33369. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33370. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33371. this._debugCanvas.style.position = "absolute";
  33372. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33373. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33374. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33375. document.body.appendChild(this._debugCanvas);
  33376. this._registerFunc = function () {
  33377. _this.drawDebugCanvas();
  33378. };
  33379. this._scene.registerBeforeRender(this._registerFunc);
  33380. }
  33381. if (this._registerFunc) {
  33382. var workingArray = this.getByteFrequencyData();
  33383. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33384. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33385. // Draw the frequency domain chart.
  33386. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33387. var value = workingArray[i];
  33388. var percent = value / this.BARGRAPHAMPLITUDE;
  33389. var height = this.DEBUGCANVASSIZE.height * percent;
  33390. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33391. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33392. var hue = i / this.getFrequencyBinCount() * 360;
  33393. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33394. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33395. }
  33396. }
  33397. }
  33398. };
  33399. Analyser.prototype.stopDebugCanvas = function () {
  33400. if (this._debugCanvas) {
  33401. this._scene.unregisterBeforeRender(this._registerFunc);
  33402. this._registerFunc = null;
  33403. document.body.removeChild(this._debugCanvas);
  33404. this._debugCanvas = null;
  33405. this._debugCanvasContext = null;
  33406. }
  33407. };
  33408. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33409. if (this._audioEngine.canUseWebAudio) {
  33410. inputAudioNode.connect(this._webAudioAnalyser);
  33411. this._webAudioAnalyser.connect(outputAudioNode);
  33412. }
  33413. };
  33414. Analyser.prototype.dispose = function () {
  33415. if (this._audioEngine.canUseWebAudio) {
  33416. this._webAudioAnalyser.disconnect();
  33417. }
  33418. };
  33419. return Analyser;
  33420. })();
  33421. BABYLON.Analyser = Analyser;
  33422. })(BABYLON || (BABYLON = {}));
  33423. var BABYLON;
  33424. (function (BABYLON) {
  33425. var AudioEngine = (function () {
  33426. function AudioEngine() {
  33427. this._audioContext = null;
  33428. this._audioContextInitialized = false;
  33429. this.canUseWebAudio = false;
  33430. this.WarnedWebAudioUnsupported = false;
  33431. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33432. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33433. this.canUseWebAudio = true;
  33434. }
  33435. }
  33436. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33437. get: function () {
  33438. if (!this._audioContextInitialized) {
  33439. this._initializeAudioContext();
  33440. }
  33441. return this._audioContext;
  33442. },
  33443. enumerable: true,
  33444. configurable: true
  33445. });
  33446. AudioEngine.prototype._initializeAudioContext = function () {
  33447. try {
  33448. if (this.canUseWebAudio) {
  33449. this._audioContext = new AudioContext();
  33450. // create a global volume gain node
  33451. this.masterGain = this._audioContext.createGain();
  33452. this.masterGain.gain.value = 1;
  33453. this.masterGain.connect(this._audioContext.destination);
  33454. this._audioContextInitialized = true;
  33455. }
  33456. }
  33457. catch (e) {
  33458. this.canUseWebAudio = false;
  33459. BABYLON.Tools.Error("Web Audio: " + e.message);
  33460. }
  33461. };
  33462. AudioEngine.prototype.dispose = function () {
  33463. if (this.canUseWebAudio && this._audioContextInitialized) {
  33464. if (this._connectedAnalyser) {
  33465. this._connectedAnalyser.stopDebugCanvas();
  33466. this._connectedAnalyser.dispose();
  33467. this.masterGain.disconnect();
  33468. this.masterGain.connect(this._audioContext.destination);
  33469. this._connectedAnalyser = null;
  33470. }
  33471. this.masterGain.gain.value = 1;
  33472. }
  33473. this.WarnedWebAudioUnsupported = false;
  33474. };
  33475. AudioEngine.prototype.getGlobalVolume = function () {
  33476. if (this.canUseWebAudio && this._audioContextInitialized) {
  33477. return this.masterGain.gain.value;
  33478. }
  33479. else {
  33480. return -1;
  33481. }
  33482. };
  33483. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33484. if (this.canUseWebAudio && this._audioContextInitialized) {
  33485. this.masterGain.gain.value = newVolume;
  33486. }
  33487. };
  33488. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33489. if (this._connectedAnalyser) {
  33490. this._connectedAnalyser.stopDebugCanvas();
  33491. }
  33492. if (this.canUseWebAudio && this._audioContextInitialized) {
  33493. this._connectedAnalyser = analyser;
  33494. this.masterGain.disconnect();
  33495. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33496. }
  33497. };
  33498. return AudioEngine;
  33499. })();
  33500. BABYLON.AudioEngine = AudioEngine;
  33501. })(BABYLON || (BABYLON = {}));
  33502. var BABYLON;
  33503. (function (BABYLON) {
  33504. var Sound = (function () {
  33505. /**
  33506. * Create a sound and attach it to a scene
  33507. * @param name Name of your sound
  33508. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33509. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33510. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33511. */
  33512. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33513. var _this = this;
  33514. this.autoplay = false;
  33515. this.loop = false;
  33516. this.useCustomAttenuation = false;
  33517. this.spatialSound = false;
  33518. this.refDistance = 1;
  33519. this.rolloffFactor = 1;
  33520. this.maxDistance = 100;
  33521. this.distanceModel = "linear";
  33522. this._panningModel = "equalpower";
  33523. this._playbackRate = 1;
  33524. this._streaming = false;
  33525. this._startTime = 0;
  33526. this._startOffset = 0;
  33527. this._position = BABYLON.Vector3.Zero();
  33528. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33529. this._volume = 1;
  33530. this._isLoaded = false;
  33531. this._isReadyToPlay = false;
  33532. this.isPlaying = false;
  33533. this.isPaused = false;
  33534. this._isDirectional = false;
  33535. // Used if you'd like to create a directional sound.
  33536. // If not set, the sound will be omnidirectional
  33537. this._coneInnerAngle = 360;
  33538. this._coneOuterAngle = 360;
  33539. this._coneOuterGain = 0;
  33540. this._isOutputConnected = false;
  33541. this.name = name;
  33542. this._scene = scene;
  33543. this._readyToPlayCallback = readyToPlayCallback;
  33544. // Default custom attenuation function is a linear attenuation
  33545. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33546. if (currentDistance < maxDistance) {
  33547. return currentVolume * (1 - currentDistance / maxDistance);
  33548. }
  33549. else {
  33550. return 0;
  33551. }
  33552. };
  33553. if (options) {
  33554. this.autoplay = options.autoplay || false;
  33555. this.loop = options.loop || false;
  33556. // if volume === 0, we need another way to check this option
  33557. if (options.volume !== undefined) {
  33558. this._volume = options.volume;
  33559. }
  33560. this.spatialSound = options.spatialSound || false;
  33561. this.maxDistance = options.maxDistance || 100;
  33562. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33563. this.rolloffFactor = options.rolloffFactor || 1;
  33564. this.refDistance = options.refDistance || 1;
  33565. this.distanceModel = options.distanceModel || "linear";
  33566. this._playbackRate = options.playbackRate || 1;
  33567. this._streaming = options.streaming || false;
  33568. }
  33569. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33570. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33571. this._soundGain.gain.value = this._volume;
  33572. this._inputAudioNode = this._soundGain;
  33573. this._ouputAudioNode = this._soundGain;
  33574. if (this.spatialSound) {
  33575. this._createSpatialParameters();
  33576. }
  33577. this._scene.mainSoundTrack.AddSound(this);
  33578. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33579. if (urlOrArrayBuffer) {
  33580. // If it's an URL
  33581. if (typeof (urlOrArrayBuffer) === "string") {
  33582. // Loading sound using XHR2
  33583. if (!this._streaming) {
  33584. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33585. }
  33586. else {
  33587. this._htmlAudioElement = new Audio();
  33588. this._htmlAudioElement.src = urlOrArrayBuffer;
  33589. this._htmlAudioElement.controls = false;
  33590. this._htmlAudioElement.loop = this.loop;
  33591. this._htmlAudioElement.crossOrigin = "anonymous";
  33592. this._isReadyToPlay = true;
  33593. document.body.appendChild(this._htmlAudioElement);
  33594. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33595. if (this._readyToPlayCallback) {
  33596. window.setTimeout(function () {
  33597. _this._readyToPlayCallback();
  33598. }, 1000);
  33599. }
  33600. if (this.autoplay) {
  33601. this.play();
  33602. }
  33603. }
  33604. }
  33605. else {
  33606. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33607. this._soundLoaded(urlOrArrayBuffer);
  33608. }
  33609. else {
  33610. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33611. }
  33612. }
  33613. }
  33614. }
  33615. else {
  33616. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33617. this._scene.mainSoundTrack.AddSound(this);
  33618. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33619. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33620. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33621. }
  33622. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33623. if (this._readyToPlayCallback) {
  33624. window.setTimeout(function () {
  33625. _this._readyToPlayCallback();
  33626. }, 1000);
  33627. }
  33628. }
  33629. }
  33630. Sound.prototype.dispose = function () {
  33631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33632. if (this.isPlaying) {
  33633. this.stop();
  33634. }
  33635. this._isReadyToPlay = false;
  33636. if (this.soundTrackId === -1) {
  33637. this._scene.mainSoundTrack.RemoveSound(this);
  33638. }
  33639. else {
  33640. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33641. }
  33642. if (this._soundGain) {
  33643. this._soundGain.disconnect();
  33644. this._soundGain = null;
  33645. }
  33646. if (this._soundPanner) {
  33647. this._soundPanner.disconnect();
  33648. this._soundPanner = null;
  33649. }
  33650. if (this._soundSource) {
  33651. this._soundSource.disconnect();
  33652. this._soundSource = null;
  33653. }
  33654. this._audioBuffer = null;
  33655. if (this._htmlAudioElement) {
  33656. this._htmlAudioElement.pause();
  33657. this._htmlAudioElement.src = "";
  33658. document.body.removeChild(this._htmlAudioElement);
  33659. }
  33660. if (this._connectedMesh) {
  33661. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33662. this._connectedMesh = null;
  33663. }
  33664. }
  33665. };
  33666. Sound.prototype._soundLoaded = function (audioData) {
  33667. var _this = this;
  33668. this._isLoaded = true;
  33669. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33670. _this._audioBuffer = buffer;
  33671. _this._isReadyToPlay = true;
  33672. if (_this.autoplay) {
  33673. _this.play();
  33674. }
  33675. if (_this._readyToPlayCallback) {
  33676. _this._readyToPlayCallback();
  33677. }
  33678. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33679. };
  33680. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33681. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33682. this._audioBuffer = audioBuffer;
  33683. this._isReadyToPlay = true;
  33684. }
  33685. };
  33686. Sound.prototype.updateOptions = function (options) {
  33687. if (options) {
  33688. this.loop = options.loop || this.loop;
  33689. this.maxDistance = options.maxDistance || this.maxDistance;
  33690. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33691. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33692. this.refDistance = options.refDistance || this.refDistance;
  33693. this.distanceModel = options.distanceModel || this.distanceModel;
  33694. this._playbackRate = options.playbackRate || this._playbackRate;
  33695. this._updateSpatialParameters();
  33696. if (this.isPlaying) {
  33697. if (this._streaming) {
  33698. this._htmlAudioElement.playbackRate = this._playbackRate;
  33699. }
  33700. else {
  33701. this._soundSource.playbackRate.value = this._playbackRate;
  33702. }
  33703. }
  33704. }
  33705. };
  33706. Sound.prototype._createSpatialParameters = function () {
  33707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33708. if (this._scene.headphone) {
  33709. this._panningModel = "HRTF";
  33710. }
  33711. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33712. this._updateSpatialParameters();
  33713. this._soundPanner.connect(this._ouputAudioNode);
  33714. this._inputAudioNode = this._soundPanner;
  33715. }
  33716. };
  33717. Sound.prototype._updateSpatialParameters = function () {
  33718. if (this.spatialSound) {
  33719. if (this.useCustomAttenuation) {
  33720. // Tricks to disable in a way embedded Web Audio attenuation
  33721. this._soundPanner.distanceModel = "linear";
  33722. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33723. this._soundPanner.refDistance = 1;
  33724. this._soundPanner.rolloffFactor = 1;
  33725. this._soundPanner.panningModel = this._panningModel;
  33726. }
  33727. else {
  33728. this._soundPanner.distanceModel = this.distanceModel;
  33729. this._soundPanner.maxDistance = this.maxDistance;
  33730. this._soundPanner.refDistance = this.refDistance;
  33731. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33732. this._soundPanner.panningModel = this._panningModel;
  33733. }
  33734. }
  33735. };
  33736. Sound.prototype.switchPanningModelToHRTF = function () {
  33737. this._panningModel = "HRTF";
  33738. this._switchPanningModel();
  33739. };
  33740. Sound.prototype.switchPanningModelToEqualPower = function () {
  33741. this._panningModel = "equalpower";
  33742. this._switchPanningModel();
  33743. };
  33744. Sound.prototype._switchPanningModel = function () {
  33745. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33746. this._soundPanner.panningModel = this._panningModel;
  33747. }
  33748. };
  33749. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33750. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33751. if (this._isOutputConnected) {
  33752. this._ouputAudioNode.disconnect();
  33753. }
  33754. this._ouputAudioNode.connect(soundTrackAudioNode);
  33755. this._isOutputConnected = true;
  33756. }
  33757. };
  33758. /**
  33759. * Transform this sound into a directional source
  33760. * @param coneInnerAngle Size of the inner cone in degree
  33761. * @param coneOuterAngle Size of the outer cone in degree
  33762. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33763. */
  33764. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33765. if (coneOuterAngle < coneInnerAngle) {
  33766. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33767. return;
  33768. }
  33769. this._coneInnerAngle = coneInnerAngle;
  33770. this._coneOuterAngle = coneOuterAngle;
  33771. this._coneOuterGain = coneOuterGain;
  33772. this._isDirectional = true;
  33773. if (this.isPlaying && this.loop) {
  33774. this.stop();
  33775. this.play();
  33776. }
  33777. };
  33778. Sound.prototype.setPosition = function (newPosition) {
  33779. this._position = newPosition;
  33780. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33781. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33782. }
  33783. };
  33784. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33785. this._localDirection = newLocalDirection;
  33786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33787. this._updateDirection();
  33788. }
  33789. };
  33790. Sound.prototype._updateDirection = function () {
  33791. var mat = this._connectedMesh.getWorldMatrix();
  33792. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33793. direction.normalize();
  33794. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33795. };
  33796. Sound.prototype.updateDistanceFromListener = function () {
  33797. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33798. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33799. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33800. }
  33801. };
  33802. Sound.prototype.setAttenuationFunction = function (callback) {
  33803. this._customAttenuationFunction = callback;
  33804. };
  33805. /**
  33806. * Play the sound
  33807. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33808. */
  33809. Sound.prototype.play = function (time) {
  33810. var _this = this;
  33811. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33812. try {
  33813. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33814. if (!this._soundSource || !this._streamingSource) {
  33815. if (this.spatialSound) {
  33816. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33817. if (this._isDirectional) {
  33818. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33819. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33820. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33821. if (this._connectedMesh) {
  33822. this._updateDirection();
  33823. }
  33824. else {
  33825. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33826. }
  33827. }
  33828. }
  33829. }
  33830. if (this._streaming) {
  33831. if (!this._streamingSource) {
  33832. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33833. this._htmlAudioElement.onended = function () { _this._onended(); };
  33834. this._htmlAudioElement.playbackRate = this._playbackRate;
  33835. }
  33836. this._streamingSource.disconnect();
  33837. this._streamingSource.connect(this._inputAudioNode);
  33838. this._htmlAudioElement.play();
  33839. }
  33840. else {
  33841. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33842. this._soundSource.buffer = this._audioBuffer;
  33843. this._soundSource.connect(this._inputAudioNode);
  33844. this._soundSource.loop = this.loop;
  33845. this._soundSource.playbackRate.value = this._playbackRate;
  33846. this._soundSource.onended = function () { _this._onended(); };
  33847. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33848. }
  33849. this._startTime = startTime;
  33850. this.isPlaying = true;
  33851. this.isPaused = false;
  33852. }
  33853. catch (ex) {
  33854. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33855. }
  33856. }
  33857. };
  33858. Sound.prototype._onended = function () {
  33859. this.isPlaying = false;
  33860. if (this.onended) {
  33861. this.onended();
  33862. }
  33863. };
  33864. /**
  33865. * Stop the sound
  33866. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33867. */
  33868. Sound.prototype.stop = function (time) {
  33869. if (this.isPlaying) {
  33870. if (this._streaming) {
  33871. this._htmlAudioElement.pause();
  33872. // Test needed for Firefox or it will generate an Invalid State Error
  33873. if (this._htmlAudioElement.currentTime > 0) {
  33874. this._htmlAudioElement.currentTime = 0;
  33875. }
  33876. }
  33877. else {
  33878. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33879. this._soundSource.stop(stopTime);
  33880. }
  33881. this.isPlaying = false;
  33882. }
  33883. };
  33884. Sound.prototype.pause = function () {
  33885. if (this.isPlaying) {
  33886. if (this._streaming) {
  33887. this._htmlAudioElement.pause();
  33888. }
  33889. else {
  33890. this.stop(0);
  33891. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33892. }
  33893. this.isPaused = true;
  33894. }
  33895. };
  33896. Sound.prototype.setVolume = function (newVolume, time) {
  33897. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33898. if (time) {
  33899. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33900. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33901. }
  33902. else {
  33903. this._soundGain.gain.value = newVolume;
  33904. }
  33905. }
  33906. this._volume = newVolume;
  33907. };
  33908. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33909. this._playbackRate = newPlaybackRate;
  33910. if (this.isPlaying) {
  33911. if (this._streaming) {
  33912. this._htmlAudioElement.playbackRate = this._playbackRate;
  33913. }
  33914. else {
  33915. this._soundSource.playbackRate.value = this._playbackRate;
  33916. }
  33917. }
  33918. };
  33919. Sound.prototype.getVolume = function () {
  33920. return this._volume;
  33921. };
  33922. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33923. var _this = this;
  33924. this._connectedMesh = meshToConnectTo;
  33925. if (!this.spatialSound) {
  33926. this.spatialSound = true;
  33927. this._createSpatialParameters();
  33928. if (this.isPlaying && this.loop) {
  33929. this.stop();
  33930. this.play();
  33931. }
  33932. }
  33933. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33934. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33935. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33936. };
  33937. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33938. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33939. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33940. this._updateDirection();
  33941. }
  33942. };
  33943. Sound.Parse = function (parsedSound, scene, rootUrl) {
  33944. var soundName = parsedSound.name;
  33945. var soundUrl = rootUrl + soundName;
  33946. var options = {
  33947. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33948. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33949. rolloffFactor: parsedSound.rolloffFactor,
  33950. refDistance: parsedSound.refDistance,
  33951. distanceModel: parsedSound.distanceModel,
  33952. playbackRate: parsedSound.playbackRate
  33953. };
  33954. var newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33955. scene._addPendingData(newSound);
  33956. if (parsedSound.position) {
  33957. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33958. newSound.setPosition(soundPosition);
  33959. }
  33960. if (parsedSound.isDirectional) {
  33961. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33962. if (parsedSound.localDirectionToMesh) {
  33963. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33964. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33965. }
  33966. }
  33967. if (parsedSound.connectedMeshId) {
  33968. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33969. if (connectedMesh) {
  33970. newSound.attachToMesh(connectedMesh);
  33971. }
  33972. }
  33973. return newSound;
  33974. };
  33975. return Sound;
  33976. })();
  33977. BABYLON.Sound = Sound;
  33978. })(BABYLON || (BABYLON = {}));
  33979. var BABYLON;
  33980. (function (BABYLON) {
  33981. var SoundTrack = (function () {
  33982. function SoundTrack(scene, options) {
  33983. this.id = -1;
  33984. this._isMainTrack = false;
  33985. this._isInitialized = false;
  33986. this._scene = scene;
  33987. this.soundCollection = new Array();
  33988. this._options = options;
  33989. if (!this._isMainTrack) {
  33990. this._scene.soundTracks.push(this);
  33991. this.id = this._scene.soundTracks.length - 1;
  33992. }
  33993. }
  33994. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33996. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33997. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33998. if (this._options) {
  33999. if (this._options.volume) {
  34000. this._outputAudioNode.gain.value = this._options.volume;
  34001. }
  34002. if (this._options.mainTrack) {
  34003. this._isMainTrack = this._options.mainTrack;
  34004. }
  34005. }
  34006. this._isInitialized = true;
  34007. }
  34008. };
  34009. SoundTrack.prototype.dispose = function () {
  34010. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34011. if (this._connectedAnalyser) {
  34012. this._connectedAnalyser.stopDebugCanvas();
  34013. }
  34014. while (this.soundCollection.length) {
  34015. this.soundCollection[0].dispose();
  34016. }
  34017. if (this._outputAudioNode) {
  34018. this._outputAudioNode.disconnect();
  34019. }
  34020. this._outputAudioNode = null;
  34021. }
  34022. };
  34023. SoundTrack.prototype.AddSound = function (sound) {
  34024. if (!this._isInitialized) {
  34025. this._initializeSoundTrackAudioGraph();
  34026. }
  34027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34028. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34029. }
  34030. if (sound.soundTrackId) {
  34031. if (sound.soundTrackId === -1) {
  34032. this._scene.mainSoundTrack.RemoveSound(sound);
  34033. }
  34034. else {
  34035. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34036. }
  34037. }
  34038. this.soundCollection.push(sound);
  34039. sound.soundTrackId = this.id;
  34040. };
  34041. SoundTrack.prototype.RemoveSound = function (sound) {
  34042. var index = this.soundCollection.indexOf(sound);
  34043. if (index !== -1) {
  34044. this.soundCollection.splice(index, 1);
  34045. }
  34046. };
  34047. SoundTrack.prototype.setVolume = function (newVolume) {
  34048. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34049. this._outputAudioNode.gain.value = newVolume;
  34050. }
  34051. };
  34052. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34053. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34054. for (var i = 0; i < this.soundCollection.length; i++) {
  34055. this.soundCollection[i].switchPanningModelToHRTF();
  34056. }
  34057. }
  34058. };
  34059. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34060. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34061. for (var i = 0; i < this.soundCollection.length; i++) {
  34062. this.soundCollection[i].switchPanningModelToEqualPower();
  34063. }
  34064. }
  34065. };
  34066. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34067. if (this._connectedAnalyser) {
  34068. this._connectedAnalyser.stopDebugCanvas();
  34069. }
  34070. this._connectedAnalyser = analyser;
  34071. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34072. this._outputAudioNode.disconnect();
  34073. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34074. }
  34075. };
  34076. return SoundTrack;
  34077. })();
  34078. BABYLON.SoundTrack = SoundTrack;
  34079. })(BABYLON || (BABYLON = {}));
  34080. var BABYLON;
  34081. (function (BABYLON) {
  34082. var DepthRenderer = (function () {
  34083. function DepthRenderer(scene, type) {
  34084. var _this = this;
  34085. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34086. this._viewMatrix = BABYLON.Matrix.Zero();
  34087. this._projectionMatrix = BABYLON.Matrix.Zero();
  34088. this._transformMatrix = BABYLON.Matrix.Zero();
  34089. this._worldViewProjection = BABYLON.Matrix.Zero();
  34090. this._scene = scene;
  34091. var engine = scene.getEngine();
  34092. // Render target
  34093. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34094. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34095. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34096. this._depthMap.refreshRate = 1;
  34097. this._depthMap.renderParticles = false;
  34098. this._depthMap.renderList = null;
  34099. // set default depth value to 1.0 (far away)
  34100. this._depthMap.onClear = function (engine) {
  34101. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34102. };
  34103. // Custom render function
  34104. var renderSubMesh = function (subMesh) {
  34105. var mesh = subMesh.getRenderingMesh();
  34106. var scene = _this._scene;
  34107. var engine = scene.getEngine();
  34108. // Culling
  34109. engine.setState(subMesh.getMaterial().backFaceCulling);
  34110. // Managing instances
  34111. var batch = mesh._getInstancesRenderList(subMesh._id);
  34112. if (batch.mustReturn) {
  34113. return;
  34114. }
  34115. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34116. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34117. engine.enableEffect(_this._effect);
  34118. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34119. var material = subMesh.getMaterial();
  34120. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34121. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34122. // Alpha test
  34123. if (material && material.needAlphaTesting()) {
  34124. var alphaTexture = material.getAlphaTestTexture();
  34125. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34126. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34127. }
  34128. // Bones
  34129. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34130. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34131. }
  34132. // Draw
  34133. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34134. }
  34135. };
  34136. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34137. var index;
  34138. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34139. renderSubMesh(opaqueSubMeshes.data[index]);
  34140. }
  34141. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34142. renderSubMesh(alphaTestSubMeshes.data[index]);
  34143. }
  34144. };
  34145. }
  34146. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34147. var defines = [];
  34148. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34149. var mesh = subMesh.getMesh();
  34150. var scene = mesh.getScene();
  34151. var material = subMesh.getMaterial();
  34152. // Alpha test
  34153. if (material && material.needAlphaTesting()) {
  34154. defines.push("#define ALPHATEST");
  34155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34156. attribs.push(BABYLON.VertexBuffer.UVKind);
  34157. defines.push("#define UV1");
  34158. }
  34159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34160. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34161. defines.push("#define UV2");
  34162. }
  34163. }
  34164. // Bones
  34165. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34166. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34167. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34168. if (mesh.numBoneInfluencers > 4) {
  34169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34171. }
  34172. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34173. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34174. }
  34175. else {
  34176. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34177. }
  34178. // Instances
  34179. if (useInstances) {
  34180. defines.push("#define INSTANCES");
  34181. attribs.push("world0");
  34182. attribs.push("world1");
  34183. attribs.push("world2");
  34184. attribs.push("world3");
  34185. }
  34186. // Get correct effect
  34187. var join = defines.join("\n");
  34188. if (this._cachedDefines !== join) {
  34189. this._cachedDefines = join;
  34190. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34191. }
  34192. return this._effect.isReady();
  34193. };
  34194. DepthRenderer.prototype.getDepthMap = function () {
  34195. return this._depthMap;
  34196. };
  34197. // Methods
  34198. DepthRenderer.prototype.dispose = function () {
  34199. this._depthMap.dispose();
  34200. };
  34201. return DepthRenderer;
  34202. })();
  34203. BABYLON.DepthRenderer = DepthRenderer;
  34204. })(BABYLON || (BABYLON = {}));
  34205. var BABYLON;
  34206. (function (BABYLON) {
  34207. var SSAORenderingPipeline = (function (_super) {
  34208. __extends(SSAORenderingPipeline, _super);
  34209. /**
  34210. * @constructor
  34211. * @param {string} name - The rendering pipeline name
  34212. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34213. * @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 }
  34214. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34215. */
  34216. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34217. var _this = this;
  34218. _super.call(this, scene.getEngine(), name);
  34219. // Members
  34220. /**
  34221. * The PassPostProcess id in the pipeline that contains the original scene color
  34222. * @type {string}
  34223. */
  34224. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34225. /**
  34226. * The SSAO PostProcess id in the pipeline
  34227. * @type {string}
  34228. */
  34229. this.SSAORenderEffect = "SSAORenderEffect";
  34230. /**
  34231. * The horizontal blur PostProcess id in the pipeline
  34232. * @type {string}
  34233. */
  34234. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34235. /**
  34236. * The vertical blur PostProcess id in the pipeline
  34237. * @type {string}
  34238. */
  34239. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34240. /**
  34241. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34242. * @type {string}
  34243. */
  34244. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34245. /**
  34246. * The output strength of the SSAO post-process. Default value is 1.0.
  34247. * @type {number}
  34248. */
  34249. this.totalStrength = 1.0;
  34250. /**
  34251. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34252. * @type {number}
  34253. */
  34254. this.radius = 0.0001;
  34255. /**
  34256. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34257. * Must not be equal to fallOff and superior to fallOff.
  34258. * Default value is 0.975
  34259. * @type {number}
  34260. */
  34261. this.area = 0.0075;
  34262. /**
  34263. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34264. * Must not be equal to area and inferior to area.
  34265. * Default value is 0.0
  34266. * @type {number}
  34267. */
  34268. this.fallOff = 0.000001;
  34269. /**
  34270. * The base color of the SSAO post-process
  34271. * The final result is "base + ssao" between [0, 1]
  34272. * @type {number}
  34273. */
  34274. this.base = 0.5;
  34275. this._firstUpdate = true;
  34276. this._scene = scene;
  34277. // Set up assets
  34278. this._createRandomTexture();
  34279. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34280. var ssaoRatio = ratio.ssaoRatio || ratio;
  34281. var combineRatio = ratio.combineRatio || ratio;
  34282. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34283. this._createSSAOPostProcess(ssaoRatio);
  34284. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34285. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34286. this._createSSAOCombinePostProcess(combineRatio);
  34287. // Set up pipeline
  34288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34293. // Finish
  34294. scene.postProcessRenderPipelineManager.addPipeline(this);
  34295. if (cameras)
  34296. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34297. }
  34298. // Public Methods
  34299. /**
  34300. * Returns the horizontal blur PostProcess
  34301. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34302. */
  34303. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34304. return this._blurHPostProcess;
  34305. };
  34306. /**
  34307. * Returns the vertical blur PostProcess
  34308. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34309. */
  34310. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34311. return this._blurVPostProcess;
  34312. };
  34313. /**
  34314. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34315. */
  34316. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34317. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34318. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34319. this._originalColorPostProcess = undefined;
  34320. this._ssaoPostProcess = undefined;
  34321. this._blurHPostProcess = undefined;
  34322. this._blurVPostProcess = undefined;
  34323. this._ssaoCombinePostProcess = undefined;
  34324. this._randomTexture.dispose();
  34325. if (disableDepthRender)
  34326. this._scene.disableDepthRenderer();
  34327. };
  34328. // Private Methods
  34329. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34330. var _this = this;
  34331. var numSamples = 16;
  34332. var sampleSphere = [
  34333. 0.5381, 0.1856, -0.4319,
  34334. 0.1379, 0.2486, 0.4430,
  34335. 0.3371, 0.5679, -0.0057,
  34336. -0.6999, -0.0451, -0.0019,
  34337. 0.0689, -0.1598, -0.8547,
  34338. 0.0560, 0.0069, -0.1843,
  34339. -0.0146, 0.1402, 0.0762,
  34340. 0.0100, -0.1924, -0.0344,
  34341. -0.3577, -0.5301, -0.4358,
  34342. -0.3169, 0.1063, 0.0158,
  34343. 0.0103, -0.5869, 0.0046,
  34344. -0.0897, -0.4940, 0.3287,
  34345. 0.7119, -0.0154, -0.0918,
  34346. -0.0533, 0.0596, -0.5411,
  34347. 0.0352, -0.0631, 0.5460,
  34348. -0.4776, 0.2847, -0.0271
  34349. ];
  34350. var samplesFactor = 1.0 / numSamples;
  34351. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34352. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34353. "area", "fallOff", "base"
  34354. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34355. this._ssaoPostProcess.onApply = function (effect) {
  34356. if (_this._firstUpdate) {
  34357. effect.setArray3("sampleSphere", sampleSphere);
  34358. effect.setFloat("samplesFactor", samplesFactor);
  34359. effect.setFloat("randTextureTiles", 4.0);
  34360. _this._firstUpdate = false;
  34361. }
  34362. effect.setFloat("totalStrength", _this.totalStrength);
  34363. effect.setFloat("radius", _this.radius);
  34364. effect.setFloat("area", _this.area);
  34365. effect.setFloat("fallOff", _this.fallOff);
  34366. effect.setFloat("base", _this.base);
  34367. effect.setTexture("textureSampler", _this._depthTexture);
  34368. effect.setTexture("randomSampler", _this._randomTexture);
  34369. };
  34370. };
  34371. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34372. var _this = this;
  34373. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34374. this._ssaoCombinePostProcess.onApply = function (effect) {
  34375. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34376. };
  34377. };
  34378. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34379. var size = 512;
  34380. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34381. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34382. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34383. var context = this._randomTexture.getContext();
  34384. var rand = function (min, max) {
  34385. return Math.random() * (max - min) + min;
  34386. };
  34387. var randVector = BABYLON.Vector3.Zero();
  34388. for (var x = 0; x < size; x++) {
  34389. for (var y = 0; y < size; y++) {
  34390. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34391. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34392. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34393. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34394. context.fillRect(x, y, 1, 1);
  34395. }
  34396. }
  34397. this._randomTexture.update(false);
  34398. };
  34399. return SSAORenderingPipeline;
  34400. })(BABYLON.PostProcessRenderPipeline);
  34401. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34402. })(BABYLON || (BABYLON = {}));
  34403. var BABYLON;
  34404. (function (BABYLON) {
  34405. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34406. var VolumetricLightScatteringPostProcess = (function (_super) {
  34407. __extends(VolumetricLightScatteringPostProcess, _super);
  34408. /**
  34409. * @constructor
  34410. * @param {string} name - The post-process name
  34411. * @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)
  34412. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34413. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34414. * @param {number} samples - The post-process quality, default 100
  34415. * @param {number} samplingMode - The post-process filtering mode
  34416. * @param {BABYLON.Engine} engine - The babylon engine
  34417. * @param {boolean} reusable - If the post-process is reusable
  34418. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34419. */
  34420. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34421. var _this = this;
  34422. if (samples === void 0) { samples = 100; }
  34423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34424. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34425. this._screenCoordinates = BABYLON.Vector2.Zero();
  34426. /**
  34427. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34428. * @type {boolean}
  34429. */
  34430. this.useCustomMeshPosition = false;
  34431. /**
  34432. * If the post-process should inverse the light scattering direction
  34433. * @type {boolean}
  34434. */
  34435. this.invert = true;
  34436. /**
  34437. * Set to true to use the diffuseColor instead of the diffuseTexture
  34438. * @type {boolean}
  34439. */
  34440. this.useDiffuseColor = false;
  34441. /**
  34442. * Array containing the excluded meshes not rendered in the internal pass
  34443. */
  34444. this.excludedMeshes = new Array();
  34445. /**
  34446. * Controls the overall intensity of the post-process
  34447. * @type {number}
  34448. */
  34449. this.exposure = 0.3;
  34450. /**
  34451. * Dissipates each sample's contribution in range [0, 1]
  34452. * @type {number}
  34453. */
  34454. this.decay = 0.96815;
  34455. /**
  34456. * Controls the overall intensity of each sample
  34457. * @type {number}
  34458. */
  34459. this.weight = 0.58767;
  34460. /**
  34461. * Controls the density of each sample
  34462. * @type {number}
  34463. */
  34464. this.density = 0.926;
  34465. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34466. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34467. // Configure mesh
  34468. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34469. // Configure
  34470. this._createPass(scene, ratio.passRatio || ratio);
  34471. this.onActivate = function (camera) {
  34472. if (!_this.isSupported) {
  34473. _this.dispose(camera);
  34474. }
  34475. _this.onActivate = null;
  34476. };
  34477. this.onApply = function (effect) {
  34478. _this._updateMeshScreenCoordinates(scene);
  34479. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34480. effect.setFloat("exposure", _this.exposure);
  34481. effect.setFloat("decay", _this.decay);
  34482. effect.setFloat("weight", _this.weight);
  34483. effect.setFloat("density", _this.density);
  34484. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34485. };
  34486. }
  34487. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34488. var mesh = subMesh.getMesh();
  34489. var defines = [];
  34490. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34491. var material = subMesh.getMaterial();
  34492. var needUV = false;
  34493. // Render this.mesh as default
  34494. if (mesh === this.mesh) {
  34495. if (this.useDiffuseColor) {
  34496. defines.push("#define DIFFUSE_COLOR_RENDER");
  34497. }
  34498. else if (material) {
  34499. if (material.diffuseTexture !== undefined) {
  34500. defines.push("#define BASIC_RENDER");
  34501. }
  34502. else {
  34503. defines.push("#define DIFFUSE_COLOR_RENDER");
  34504. }
  34505. }
  34506. defines.push("#define NEED_UV");
  34507. needUV = true;
  34508. }
  34509. // Alpha test
  34510. if (material) {
  34511. if (material.needAlphaTesting()) {
  34512. defines.push("#define ALPHATEST");
  34513. }
  34514. if (material.opacityTexture !== undefined) {
  34515. defines.push("#define OPACITY");
  34516. if (material.opacityTexture.getAlphaFromRGB) {
  34517. defines.push("#define OPACITYRGB");
  34518. }
  34519. if (!needUV) {
  34520. defines.push("#define NEED_UV");
  34521. }
  34522. }
  34523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34524. attribs.push(BABYLON.VertexBuffer.UVKind);
  34525. defines.push("#define UV1");
  34526. }
  34527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34529. defines.push("#define UV2");
  34530. }
  34531. }
  34532. // Bones
  34533. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34534. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34535. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34536. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34537. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34538. }
  34539. else {
  34540. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34541. }
  34542. // Instances
  34543. if (useInstances) {
  34544. defines.push("#define INSTANCES");
  34545. attribs.push("world0");
  34546. attribs.push("world1");
  34547. attribs.push("world2");
  34548. attribs.push("world3");
  34549. }
  34550. // Get correct effect
  34551. var join = defines.join("\n");
  34552. if (this._cachedDefines !== join) {
  34553. this._cachedDefines = join;
  34554. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34555. }
  34556. return this._volumetricLightScatteringPass.isReady();
  34557. };
  34558. /**
  34559. * Sets the new light position for light scattering effect
  34560. * @param {BABYLON.Vector3} The new custom light position
  34561. */
  34562. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34563. this._customMeshPosition = position;
  34564. };
  34565. /**
  34566. * Returns the light position for light scattering effect
  34567. * @return {BABYLON.Vector3} The custom light position
  34568. */
  34569. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34570. return this._customMeshPosition;
  34571. };
  34572. /**
  34573. * Disposes the internal assets and detaches the post-process from the camera
  34574. */
  34575. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34576. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34577. if (rttIndex !== -1) {
  34578. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34579. }
  34580. this._volumetricLightScatteringRTT.dispose();
  34581. _super.prototype.dispose.call(this, camera);
  34582. };
  34583. /**
  34584. * Returns the render target texture used by the post-process
  34585. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34586. */
  34587. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34588. return this._volumetricLightScatteringRTT;
  34589. };
  34590. // Private methods
  34591. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34592. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34593. return true;
  34594. }
  34595. return false;
  34596. };
  34597. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34598. var _this = this;
  34599. var engine = scene.getEngine();
  34600. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34601. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34602. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34603. this._volumetricLightScatteringRTT.renderList = null;
  34604. this._volumetricLightScatteringRTT.renderParticles = false;
  34605. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34606. // Custom render function for submeshes
  34607. var renderSubMesh = function (subMesh) {
  34608. var mesh = subMesh.getRenderingMesh();
  34609. if (_this._meshExcluded(mesh)) {
  34610. return;
  34611. }
  34612. var scene = mesh.getScene();
  34613. var engine = scene.getEngine();
  34614. // Culling
  34615. engine.setState(subMesh.getMaterial().backFaceCulling);
  34616. // Managing instances
  34617. var batch = mesh._getInstancesRenderList(subMesh._id);
  34618. if (batch.mustReturn) {
  34619. return;
  34620. }
  34621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34622. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34623. engine.enableEffect(_this._volumetricLightScatteringPass);
  34624. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34625. var material = subMesh.getMaterial();
  34626. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34627. // Alpha test
  34628. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34629. var alphaTexture = material.getAlphaTestTexture();
  34630. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34631. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34632. }
  34633. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34634. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34635. if (alphaTexture) {
  34636. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34637. }
  34638. }
  34639. if (material.opacityTexture !== undefined) {
  34640. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34641. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34642. }
  34643. }
  34644. // Bones
  34645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34646. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34647. }
  34648. // Draw
  34649. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34650. }
  34651. };
  34652. // Render target texture callbacks
  34653. var savedSceneClearColor;
  34654. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34655. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34656. savedSceneClearColor = scene.clearColor;
  34657. scene.clearColor = sceneClearColor;
  34658. };
  34659. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34660. scene.clearColor = savedSceneClearColor;
  34661. };
  34662. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34663. var engine = scene.getEngine();
  34664. var index;
  34665. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34666. renderSubMesh(opaqueSubMeshes.data[index]);
  34667. }
  34668. engine.setAlphaTesting(true);
  34669. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34670. renderSubMesh(alphaTestSubMeshes.data[index]);
  34671. }
  34672. engine.setAlphaTesting(false);
  34673. if (transparentSubMeshes.length) {
  34674. // Sort sub meshes
  34675. for (index = 0; index < transparentSubMeshes.length; index++) {
  34676. var submesh = transparentSubMeshes.data[index];
  34677. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34678. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34679. }
  34680. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34681. sortedArray.sort(function (a, b) {
  34682. // Alpha index first
  34683. if (a._alphaIndex > b._alphaIndex) {
  34684. return 1;
  34685. }
  34686. if (a._alphaIndex < b._alphaIndex) {
  34687. return -1;
  34688. }
  34689. // Then distance to camera
  34690. if (a._distanceToCamera < b._distanceToCamera) {
  34691. return 1;
  34692. }
  34693. if (a._distanceToCamera > b._distanceToCamera) {
  34694. return -1;
  34695. }
  34696. return 0;
  34697. });
  34698. // Render sub meshes
  34699. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34700. for (index = 0; index < sortedArray.length; index++) {
  34701. renderSubMesh(sortedArray[index]);
  34702. }
  34703. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34704. }
  34705. };
  34706. };
  34707. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34708. var transform = scene.getTransformMatrix();
  34709. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34710. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34711. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34712. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34713. if (this.invert)
  34714. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34715. };
  34716. // Static methods
  34717. /**
  34718. * Creates a default mesh for the Volumeric Light Scattering post-process
  34719. * @param {string} The mesh name
  34720. * @param {BABYLON.Scene} The scene where to create the mesh
  34721. * @return {BABYLON.Mesh} the default mesh
  34722. */
  34723. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34724. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34725. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34726. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34727. return mesh;
  34728. };
  34729. return VolumetricLightScatteringPostProcess;
  34730. })(BABYLON.PostProcess);
  34731. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34732. })(BABYLON || (BABYLON = {}));
  34733. // BABYLON.JS Chromatic Aberration GLSL Shader
  34734. // Author: Olivier Guyot
  34735. // Separates very slightly R, G and B colors on the edges of the screen
  34736. // Inspired by Francois Tarlier & Martins Upitis
  34737. var BABYLON;
  34738. (function (BABYLON) {
  34739. var LensRenderingPipeline = (function (_super) {
  34740. __extends(LensRenderingPipeline, _super);
  34741. /**
  34742. * @constructor
  34743. *
  34744. * Effect parameters are as follow:
  34745. * {
  34746. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34747. * edge_blur: number; // from 0 to x (1 for realism)
  34748. * distortion: number; // from 0 to x (1 for realism)
  34749. * grain_amount: number; // from 0 to 1
  34750. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34751. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34752. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34753. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34754. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34755. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34756. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34757. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34758. * }
  34759. * Note: if an effect parameter is unset, effect is disabled
  34760. *
  34761. * @param {string} name - The rendering pipeline name
  34762. * @param {object} parameters - An object containing all parameters (see above)
  34763. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34764. * @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)
  34765. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34766. */
  34767. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34768. var _this = this;
  34769. if (ratio === void 0) { ratio = 1.0; }
  34770. _super.call(this, scene.getEngine(), name);
  34771. // Lens effects can be of the following:
  34772. // - chromatic aberration (slight shift of RGB colors)
  34773. // - blur on the edge of the lens
  34774. // - lens distortion
  34775. // - depth-of-field blur & highlights enhancing
  34776. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34777. // - grain effect (noise or custom texture)
  34778. // Two additional texture samplers are needed:
  34779. // - depth map (for depth-of-field)
  34780. // - grain texture
  34781. /**
  34782. * The chromatic aberration PostProcess id in the pipeline
  34783. * @type {string}
  34784. */
  34785. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34786. /**
  34787. * The highlights enhancing PostProcess id in the pipeline
  34788. * @type {string}
  34789. */
  34790. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34791. /**
  34792. * The depth-of-field PostProcess id in the pipeline
  34793. * @type {string}
  34794. */
  34795. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34796. this._scene = scene;
  34797. // Fetch texture samplers
  34798. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34799. if (parameters.grain_texture) {
  34800. this._grainTexture = parameters.grain_texture;
  34801. }
  34802. else {
  34803. this._createGrainTexture();
  34804. }
  34805. // save parameters
  34806. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34807. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34808. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34809. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34810. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34811. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34812. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34813. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34814. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34815. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34816. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34817. // Create effects
  34818. this._createChromaticAberrationPostProcess(ratio);
  34819. this._createHighlightsPostProcess(ratio);
  34820. this._createDepthOfFieldPostProcess(ratio / 4);
  34821. // Set up pipeline
  34822. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34824. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34825. if (this._highlightsGain === -1) {
  34826. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34827. }
  34828. // Finish
  34829. scene.postProcessRenderPipelineManager.addPipeline(this);
  34830. if (cameras) {
  34831. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34832. }
  34833. }
  34834. // public methods (self explanatory)
  34835. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34836. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34837. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34838. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34839. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34840. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34841. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34842. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34843. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34844. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34845. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34846. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34847. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34848. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34849. };
  34850. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34851. this._highlightsPostProcess.updateEffect();
  34852. };
  34853. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34854. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34855. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34856. this._highlightsGain = amount;
  34857. };
  34858. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34859. if (this._highlightsGain === -1) {
  34860. this._highlightsGain = 1.0;
  34861. }
  34862. this._highlightsThreshold = amount;
  34863. };
  34864. LensRenderingPipeline.prototype.disableHighlights = function () {
  34865. this._highlightsGain = -1;
  34866. };
  34867. /**
  34868. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34869. */
  34870. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34871. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34872. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34873. this._chromaticAberrationPostProcess = undefined;
  34874. this._highlightsPostProcess = undefined;
  34875. this._depthOfFieldPostProcess = undefined;
  34876. this._grainTexture.dispose();
  34877. if (disableDepthRender)
  34878. this._scene.disableDepthRenderer();
  34879. };
  34880. // colors shifting and distortion
  34881. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34882. var _this = this;
  34883. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34884. [], // samplers
  34885. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34886. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34887. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34888. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34889. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34890. };
  34891. };
  34892. // highlights enhancing
  34893. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34894. var _this = this;
  34895. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34896. [], // samplers
  34897. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34898. this._highlightsPostProcess.onApply = function (effect) {
  34899. effect.setFloat('gain', _this._highlightsGain);
  34900. effect.setFloat('threshold', _this._highlightsThreshold);
  34901. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34902. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34903. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34904. };
  34905. };
  34906. // colors shifting and distortion
  34907. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34908. var _this = this;
  34909. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34910. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34911. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34912. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34913. this._depthOfFieldPostProcess.onApply = function (effect) {
  34914. effect.setTexture("depthSampler", _this._depthTexture);
  34915. effect.setTexture("grainSampler", _this._grainTexture);
  34916. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34917. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34918. effect.setFloat('grain_amount', _this._grainAmount);
  34919. effect.setBool('blur_noise', _this._blurNoise);
  34920. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34921. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34922. effect.setFloat('distortion', _this._distortion);
  34923. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34924. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34925. effect.setFloat('aperture', _this._dofAperture);
  34926. effect.setFloat('darken', _this._dofDarken);
  34927. effect.setFloat('edge_blur', _this._edgeBlur);
  34928. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34929. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34930. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34931. };
  34932. };
  34933. // creates a black and white random noise texture, 512x512
  34934. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34935. var size = 512;
  34936. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34937. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34938. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34939. var context = this._grainTexture.getContext();
  34940. var rand = function (min, max) {
  34941. return Math.random() * (max - min) + min;
  34942. };
  34943. var value;
  34944. for (var x = 0; x < size; x++) {
  34945. for (var y = 0; y < size; y++) {
  34946. value = Math.floor(rand(0.42, 0.58) * 255);
  34947. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34948. context.fillRect(x, y, 1, 1);
  34949. }
  34950. }
  34951. this._grainTexture.update(false);
  34952. };
  34953. return LensRenderingPipeline;
  34954. })(BABYLON.PostProcessRenderPipeline);
  34955. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34956. })(BABYLON || (BABYLON = {}));
  34957. //
  34958. // This post-process allows the modification of rendered colors by using
  34959. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34960. //
  34961. // The object needs to be provided an url to a texture containing the color
  34962. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34963. // Use an image editing software to tweak the LUT to match your needs.
  34964. //
  34965. // For an example of a color LUT, see here:
  34966. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34967. // For explanations on color grading, see here:
  34968. // http://udn.epicgames.com/Three/ColorGrading.html
  34969. //
  34970. var BABYLON;
  34971. (function (BABYLON) {
  34972. var ColorCorrectionPostProcess = (function (_super) {
  34973. __extends(ColorCorrectionPostProcess, _super);
  34974. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34975. var _this = this;
  34976. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34977. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34978. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34979. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34980. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34981. this.onApply = function (effect) {
  34982. effect.setTexture("colorTable", _this._colorTableTexture);
  34983. };
  34984. }
  34985. return ColorCorrectionPostProcess;
  34986. })(BABYLON.PostProcess);
  34987. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34988. })(BABYLON || (BABYLON = {}));
  34989. var BABYLON;
  34990. (function (BABYLON) {
  34991. var AnaglyphFreeCamera = (function (_super) {
  34992. __extends(AnaglyphFreeCamera, _super);
  34993. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34994. _super.call(this, name, position, scene);
  34995. this.interaxialDistance = interaxialDistance;
  34996. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34997. }
  34998. return AnaglyphFreeCamera;
  34999. })(BABYLON.FreeCamera);
  35000. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35001. var AnaglyphArcRotateCamera = (function (_super) {
  35002. __extends(AnaglyphArcRotateCamera, _super);
  35003. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35004. _super.call(this, name, alpha, beta, radius, target, scene);
  35005. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35006. }
  35007. return AnaglyphArcRotateCamera;
  35008. })(BABYLON.ArcRotateCamera);
  35009. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35010. var AnaglyphGamepadCamera = (function (_super) {
  35011. __extends(AnaglyphGamepadCamera, _super);
  35012. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35013. _super.call(this, name, position, scene);
  35014. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35015. }
  35016. return AnaglyphGamepadCamera;
  35017. })(BABYLON.GamepadCamera);
  35018. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35019. var StereoscopicFreeCamera = (function (_super) {
  35020. __extends(StereoscopicFreeCamera, _super);
  35021. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35022. _super.call(this, name, position, scene);
  35023. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35024. }
  35025. return StereoscopicFreeCamera;
  35026. })(BABYLON.FreeCamera);
  35027. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35028. var StereoscopicArcRotateCamera = (function (_super) {
  35029. __extends(StereoscopicArcRotateCamera, _super);
  35030. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35031. _super.call(this, name, alpha, beta, radius, target, scene);
  35032. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35033. }
  35034. return StereoscopicArcRotateCamera;
  35035. })(BABYLON.ArcRotateCamera);
  35036. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35037. var StereoscopicGamepadCamera = (function (_super) {
  35038. __extends(StereoscopicGamepadCamera, _super);
  35039. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35040. _super.call(this, name, position, scene);
  35041. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35042. }
  35043. return StereoscopicGamepadCamera;
  35044. })(BABYLON.GamepadCamera);
  35045. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35046. })(BABYLON || (BABYLON = {}));
  35047. var BABYLON;
  35048. (function (BABYLON) {
  35049. var HDRRenderingPipeline = (function (_super) {
  35050. __extends(HDRRenderingPipeline, _super);
  35051. /**
  35052. * @constructor
  35053. * @param {string} name - The rendering pipeline name
  35054. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35055. * @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)
  35056. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35057. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35058. */
  35059. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35060. var _this = this;
  35061. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35062. _super.call(this, scene.getEngine(), name);
  35063. /**
  35064. * Public members
  35065. */
  35066. // Gaussian Blur
  35067. /**
  35068. * Gaussian blur coefficient
  35069. * @type {number}
  35070. */
  35071. this.gaussCoeff = 0.3;
  35072. /**
  35073. * Gaussian blur mean
  35074. * @type {number}
  35075. */
  35076. this.gaussMean = 1.0;
  35077. /**
  35078. * Gaussian blur standard deviation
  35079. * @type {number}
  35080. */
  35081. this.gaussStandDev = 0.8;
  35082. /**
  35083. * Gaussian blur multiplier. Multiplies the blur effect
  35084. * @type {number}
  35085. */
  35086. this.gaussMultiplier = 4.0;
  35087. // HDR
  35088. /**
  35089. * Exposure, controls the overall intensity of the pipeline
  35090. * @type {number}
  35091. */
  35092. this.exposure = 1.0;
  35093. /**
  35094. * Minimum luminance that the post-process can output. Luminance is >= 0
  35095. * @type {number}
  35096. */
  35097. this.minimumLuminance = 1.0;
  35098. /**
  35099. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35100. * @type {number}
  35101. */
  35102. this.maximumLuminance = 1e20;
  35103. /**
  35104. * Increase rate for luminance: eye adaptation speed to dark
  35105. * @type {number}
  35106. */
  35107. this.luminanceIncreaserate = 0.5;
  35108. /**
  35109. * Decrease rate for luminance: eye adaptation speed to bright
  35110. * @type {number}
  35111. */
  35112. this.luminanceDecreaseRate = 0.5;
  35113. // Bright pass
  35114. /**
  35115. * Minimum luminance needed to compute HDR
  35116. * @type {number}
  35117. */
  35118. this.brightThreshold = 0.8;
  35119. this._needUpdate = true;
  35120. this._scene = scene;
  35121. // Bright pass
  35122. this._createBrightPassPostProcess(scene, ratio);
  35123. // Down sample X4
  35124. this._createDownSampleX4PostProcess(scene, ratio);
  35125. // Create gaussian blur post-processes
  35126. this._createGaussianBlurPostProcess(scene, ratio);
  35127. // Texture adder
  35128. this._createTextureAdderPostProcess(scene, ratio);
  35129. // Luminance generator
  35130. this._createLuminanceGeneratorPostProcess(scene);
  35131. // HDR
  35132. this._createHDRPostProcess(scene, ratio);
  35133. // Pass postprocess
  35134. if (originalPostProcess === null) {
  35135. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35136. }
  35137. else {
  35138. this._originalPostProcess = originalPostProcess;
  35139. }
  35140. // Configure pipeline
  35141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35147. var addDownSamplerPostProcess = function (id) {
  35148. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35149. };
  35150. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35151. addDownSamplerPostProcess(i);
  35152. }
  35153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35154. // Finish
  35155. scene.postProcessRenderPipelineManager.addPipeline(this);
  35156. if (cameras !== null) {
  35157. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35158. }
  35159. this.update();
  35160. }
  35161. /**
  35162. * Tells the pipeline to update its post-processes
  35163. */
  35164. HDRRenderingPipeline.prototype.update = function () {
  35165. this._needUpdate = true;
  35166. };
  35167. /**
  35168. * Returns the current calculated luminance
  35169. */
  35170. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35171. return this._hdrCurrentLuminance;
  35172. };
  35173. /**
  35174. * Returns the currently drawn luminance
  35175. */
  35176. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35177. return this._hdrOutputLuminance;
  35178. };
  35179. /**
  35180. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35181. */
  35182. HDRRenderingPipeline.prototype.dispose = function () {
  35183. this._originalPostProcess = undefined;
  35184. this._brightPassPostProcess = undefined;
  35185. this._downSampleX4PostProcess = undefined;
  35186. this._guassianBlurHPostProcess = undefined;
  35187. this._guassianBlurVPostProcess = undefined;
  35188. this._textureAdderPostProcess = undefined;
  35189. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35190. this._downSamplePostProcesses[i] = undefined;
  35191. }
  35192. this._hdrPostProcess = undefined;
  35193. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35194. };
  35195. /**
  35196. * Creates the HDR post-process and computes the luminance adaptation
  35197. */
  35198. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35199. var _this = this;
  35200. var hdrLastLuminance = 0.0;
  35201. this._hdrOutputLuminance = -1.0;
  35202. this._hdrCurrentLuminance = 1.0;
  35203. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35204. this._hdrPostProcess.onApply = function (effect) {
  35205. if (_this._hdrOutputLuminance < 0.0) {
  35206. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35207. }
  35208. else {
  35209. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35210. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35211. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35212. }
  35213. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35214. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35215. }
  35216. else {
  35217. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35218. }
  35219. }
  35220. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35221. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35222. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35223. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35224. effect.setFloat("exposure", _this.exposure);
  35225. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35226. _this._needUpdate = false;
  35227. };
  35228. };
  35229. /**
  35230. * Texture Adder post-process
  35231. */
  35232. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35233. var _this = this;
  35234. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35235. this._textureAdderPostProcess.onApply = function (effect) {
  35236. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35237. };
  35238. };
  35239. /**
  35240. * Down sample X4 post-process
  35241. */
  35242. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35243. var _this = this;
  35244. var downSampleX4Offsets = new Array(32);
  35245. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35246. this._downSampleX4PostProcess.onApply = function (effect) {
  35247. if (_this._needUpdate) {
  35248. var id = 0;
  35249. for (var i = -2; i < 2; i++) {
  35250. for (var j = -2; j < 2; j++) {
  35251. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35252. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35253. id += 2;
  35254. }
  35255. }
  35256. }
  35257. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35258. };
  35259. };
  35260. /**
  35261. * Bright pass post-process
  35262. */
  35263. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35264. var _this = this;
  35265. var brightOffsets = new Array(8);
  35266. var brightPassCallback = function (effect) {
  35267. if (_this._needUpdate) {
  35268. var sU = (1.0 / _this._brightPassPostProcess.width);
  35269. var sV = (1.0 / _this._brightPassPostProcess.height);
  35270. brightOffsets[0] = -0.5 * sU;
  35271. brightOffsets[1] = 0.5 * sV;
  35272. brightOffsets[2] = 0.5 * sU;
  35273. brightOffsets[3] = 0.5 * sV;
  35274. brightOffsets[4] = -0.5 * sU;
  35275. brightOffsets[5] = -0.5 * sV;
  35276. brightOffsets[6] = 0.5 * sU;
  35277. brightOffsets[7] = -0.5 * sV;
  35278. }
  35279. effect.setArray2("dsOffsets", brightOffsets);
  35280. effect.setFloat("brightThreshold", _this.brightThreshold);
  35281. };
  35282. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35283. this._brightPassPostProcess.onApply = brightPassCallback;
  35284. };
  35285. /**
  35286. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35287. */
  35288. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35289. var _this = this;
  35290. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35291. var luminanceOffsets = new Array(8);
  35292. var downSampleOffsets = new Array(18);
  35293. var halfDestPixelSize;
  35294. this._downSamplePostProcesses = new Array(lumSteps);
  35295. // Utils for luminance
  35296. var luminanceUpdateSourceOffsets = function (width, height) {
  35297. var sU = (1.0 / width);
  35298. var sV = (1.0 / height);
  35299. luminanceOffsets[0] = -0.5 * sU;
  35300. luminanceOffsets[1] = 0.5 * sV;
  35301. luminanceOffsets[2] = 0.5 * sU;
  35302. luminanceOffsets[3] = 0.5 * sV;
  35303. luminanceOffsets[4] = -0.5 * sU;
  35304. luminanceOffsets[5] = -0.5 * sV;
  35305. luminanceOffsets[6] = 0.5 * sU;
  35306. luminanceOffsets[7] = -0.5 * sV;
  35307. };
  35308. var luminanceUpdateDestOffsets = function (width, height) {
  35309. var id = 0;
  35310. for (var x = -1; x < 2; x++) {
  35311. for (var y = -1; y < 2; y++) {
  35312. downSampleOffsets[id] = (x) / width;
  35313. downSampleOffsets[id + 1] = (y) / height;
  35314. id += 2;
  35315. }
  35316. }
  35317. };
  35318. // Luminance callback
  35319. var luminanceCallback = function (effect) {
  35320. if (_this._needUpdate) {
  35321. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35322. }
  35323. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35324. effect.setArray2("lumOffsets", luminanceOffsets);
  35325. };
  35326. // Down sample callbacks
  35327. var downSampleCallback = function (indice) {
  35328. var i = indice;
  35329. return function (effect) {
  35330. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35331. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35332. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35333. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35334. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35335. effect.setArray2("dsOffsets", downSampleOffsets);
  35336. };
  35337. };
  35338. var downSampleAfterRenderCallback = function (effect) {
  35339. // Unpack result
  35340. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35341. 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);
  35342. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35343. };
  35344. // Create luminance post-process
  35345. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35346. 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);
  35347. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35348. // Create down sample post-processes
  35349. for (var i = lumSteps - 2; i >= 0; i--) {
  35350. var length = Math.pow(3, i);
  35351. ratio = { width: length, height: length };
  35352. var defines = "#define DOWN_SAMPLE\n";
  35353. if (i === 0) {
  35354. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35355. }
  35356. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35357. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35358. if (i === 0) {
  35359. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35360. }
  35361. }
  35362. };
  35363. /**
  35364. * Gaussian blur post-processes. Horizontal and Vertical
  35365. */
  35366. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35367. var _this = this;
  35368. var blurOffsetsW = new Array(9);
  35369. var blurOffsetsH = new Array(9);
  35370. var blurWeights = new Array(9);
  35371. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35372. // Utils for gaussian blur
  35373. var calculateBlurOffsets = function (height) {
  35374. var lastOutputDimensions = {
  35375. width: scene.getEngine().getRenderWidth(),
  35376. height: scene.getEngine().getRenderHeight()
  35377. };
  35378. for (var i = 0; i < 9; i++) {
  35379. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35380. if (height) {
  35381. blurOffsetsH[i] = value;
  35382. }
  35383. else {
  35384. blurOffsetsW[i] = value;
  35385. }
  35386. }
  35387. };
  35388. var calculateWeights = function () {
  35389. var x = 0.0;
  35390. for (var i = 0; i < 9; i++) {
  35391. x = (i - 4.0) / 4.0;
  35392. 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));
  35393. }
  35394. };
  35395. // Callback
  35396. var gaussianBlurCallback = function (height) {
  35397. return function (effect) {
  35398. if (_this._needUpdate) {
  35399. calculateWeights();
  35400. calculateBlurOffsets(height);
  35401. }
  35402. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35403. effect.setArray("blurWeights", blurWeights);
  35404. effect.setFloat("multiplier", _this.gaussMultiplier);
  35405. };
  35406. };
  35407. // Create horizontal gaussian blur post-processes
  35408. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35409. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35410. // Create vertical gaussian blur post-process
  35411. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35412. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35413. };
  35414. // Luminance generator
  35415. HDRRenderingPipeline.LUM_STEPS = 6;
  35416. return HDRRenderingPipeline;
  35417. })(BABYLON.PostProcessRenderPipeline);
  35418. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35419. })(BABYLON || (BABYLON = {}));
  35420. var BABYLON;
  35421. (function (BABYLON) {
  35422. var FaceAdjacencies = (function () {
  35423. function FaceAdjacencies() {
  35424. this.edges = new Array();
  35425. this.edgesConnectedCount = 0;
  35426. }
  35427. return FaceAdjacencies;
  35428. })();
  35429. var EdgesRenderer = (function () {
  35430. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35431. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35432. if (epsilon === void 0) { epsilon = 0.95; }
  35433. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35434. this._linesPositions = new Array();
  35435. this._linesNormals = new Array();
  35436. this._linesIndices = new Array();
  35437. this._buffers = new Array();
  35438. this._checkVerticesInsteadOfIndices = false;
  35439. this._source = source;
  35440. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35441. this._epsilon = epsilon;
  35442. this._prepareRessources();
  35443. this._generateEdgesLines();
  35444. }
  35445. EdgesRenderer.prototype._prepareRessources = function () {
  35446. if (this._lineShader) {
  35447. return;
  35448. }
  35449. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35450. attributes: ["position", "normal"],
  35451. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35452. });
  35453. this._lineShader.disableDepthWrite = true;
  35454. this._lineShader.backFaceCulling = false;
  35455. };
  35456. EdgesRenderer.prototype.dispose = function () {
  35457. this._vb0.dispose();
  35458. this._vb1.dispose();
  35459. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35460. this._lineShader.dispose();
  35461. };
  35462. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35463. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35464. return 0;
  35465. }
  35466. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35467. return 1;
  35468. }
  35469. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35470. return 2;
  35471. }
  35472. return -1;
  35473. };
  35474. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35475. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35476. return 0;
  35477. }
  35478. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35479. return 1;
  35480. }
  35481. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35482. return 2;
  35483. }
  35484. return -1;
  35485. };
  35486. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35487. var needToCreateLine;
  35488. if (edge === undefined) {
  35489. needToCreateLine = true;
  35490. }
  35491. else {
  35492. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35493. needToCreateLine = dotProduct < this._epsilon;
  35494. }
  35495. if (needToCreateLine) {
  35496. var offset = this._linesPositions.length / 3;
  35497. var normal = p0.subtract(p1);
  35498. normal.normalize();
  35499. // Positions
  35500. this._linesPositions.push(p0.x);
  35501. this._linesPositions.push(p0.y);
  35502. this._linesPositions.push(p0.z);
  35503. this._linesPositions.push(p0.x);
  35504. this._linesPositions.push(p0.y);
  35505. this._linesPositions.push(p0.z);
  35506. this._linesPositions.push(p1.x);
  35507. this._linesPositions.push(p1.y);
  35508. this._linesPositions.push(p1.z);
  35509. this._linesPositions.push(p1.x);
  35510. this._linesPositions.push(p1.y);
  35511. this._linesPositions.push(p1.z);
  35512. // Normals
  35513. this._linesNormals.push(p1.x);
  35514. this._linesNormals.push(p1.y);
  35515. this._linesNormals.push(p1.z);
  35516. this._linesNormals.push(-1);
  35517. this._linesNormals.push(p1.x);
  35518. this._linesNormals.push(p1.y);
  35519. this._linesNormals.push(p1.z);
  35520. this._linesNormals.push(1);
  35521. this._linesNormals.push(p0.x);
  35522. this._linesNormals.push(p0.y);
  35523. this._linesNormals.push(p0.z);
  35524. this._linesNormals.push(-1);
  35525. this._linesNormals.push(p0.x);
  35526. this._linesNormals.push(p0.y);
  35527. this._linesNormals.push(p0.z);
  35528. this._linesNormals.push(1);
  35529. // Indices
  35530. this._linesIndices.push(offset);
  35531. this._linesIndices.push(offset + 1);
  35532. this._linesIndices.push(offset + 2);
  35533. this._linesIndices.push(offset);
  35534. this._linesIndices.push(offset + 2);
  35535. this._linesIndices.push(offset + 3);
  35536. }
  35537. };
  35538. EdgesRenderer.prototype._generateEdgesLines = function () {
  35539. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35540. var indices = this._source.getIndices();
  35541. // First let's find adjacencies
  35542. var adjacencies = new Array();
  35543. var faceNormals = new Array();
  35544. var index;
  35545. var faceAdjacencies;
  35546. // Prepare faces
  35547. for (index = 0; index < indices.length; index += 3) {
  35548. faceAdjacencies = new FaceAdjacencies();
  35549. var p0Index = indices[index];
  35550. var p1Index = indices[index + 1];
  35551. var p2Index = indices[index + 2];
  35552. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35553. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35554. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35555. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35556. faceNormal.normalize();
  35557. faceNormals.push(faceNormal);
  35558. adjacencies.push(faceAdjacencies);
  35559. }
  35560. // Scan
  35561. for (index = 0; index < adjacencies.length; index++) {
  35562. faceAdjacencies = adjacencies[index];
  35563. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35564. var otherFaceAdjacencies = adjacencies[otherIndex];
  35565. if (faceAdjacencies.edgesConnectedCount === 3) {
  35566. break;
  35567. }
  35568. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35569. continue;
  35570. }
  35571. var otherP0 = indices[otherIndex * 3];
  35572. var otherP1 = indices[otherIndex * 3 + 1];
  35573. var otherP2 = indices[otherIndex * 3 + 2];
  35574. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35575. var otherEdgeIndex;
  35576. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35577. continue;
  35578. }
  35579. switch (edgeIndex) {
  35580. case 0:
  35581. if (this._checkVerticesInsteadOfIndices) {
  35582. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35583. }
  35584. else {
  35585. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35586. }
  35587. break;
  35588. case 1:
  35589. if (this._checkVerticesInsteadOfIndices) {
  35590. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35591. }
  35592. else {
  35593. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35594. }
  35595. break;
  35596. case 2:
  35597. if (this._checkVerticesInsteadOfIndices) {
  35598. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35599. }
  35600. else {
  35601. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35602. }
  35603. break;
  35604. }
  35605. if (otherEdgeIndex === -1) {
  35606. continue;
  35607. }
  35608. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35609. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35610. faceAdjacencies.edgesConnectedCount++;
  35611. otherFaceAdjacencies.edgesConnectedCount++;
  35612. if (faceAdjacencies.edgesConnectedCount === 3) {
  35613. break;
  35614. }
  35615. }
  35616. }
  35617. }
  35618. // Create lines
  35619. for (index = 0; index < adjacencies.length; index++) {
  35620. // 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
  35621. var current = adjacencies[index];
  35622. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35623. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35624. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35625. }
  35626. // Merge into a single mesh
  35627. var engine = this._source.getScene().getEngine();
  35628. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35629. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35630. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35631. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35632. this._ib = engine.createIndexBuffer(this._linesIndices);
  35633. this._indicesCount = this._linesIndices.length;
  35634. };
  35635. EdgesRenderer.prototype.render = function () {
  35636. if (!this._lineShader.isReady()) {
  35637. return;
  35638. }
  35639. var scene = this._source.getScene();
  35640. var engine = scene.getEngine();
  35641. this._lineShader._preBind();
  35642. // VBOs
  35643. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35644. scene.resetCachedMaterial();
  35645. this._lineShader.setColor4("color", this._source.edgesColor);
  35646. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35647. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35648. this._lineShader.bind(this._source.getWorldMatrix());
  35649. // Draw order
  35650. engine.draw(true, 0, this._indicesCount);
  35651. this._lineShader.unbind();
  35652. engine.setDepthWrite(true);
  35653. };
  35654. return EdgesRenderer;
  35655. })();
  35656. BABYLON.EdgesRenderer = EdgesRenderer;
  35657. })(BABYLON || (BABYLON = {}));
  35658. var BABYLON;
  35659. (function (BABYLON) {
  35660. (function (TonemappingOperator) {
  35661. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35662. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35663. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35664. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35665. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35666. var TonemappingOperator = BABYLON.TonemappingOperator;
  35667. ;
  35668. var TonemapPostProcess = (function (_super) {
  35669. __extends(TonemapPostProcess, _super);
  35670. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35671. var _this = this;
  35672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35673. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35674. this._operator = operator;
  35675. this._exposureAdjustment = exposureAdjustment;
  35676. var params = ["_ExposureAdjustment"];
  35677. var defines = "#define ";
  35678. if (operator === TonemappingOperator.Hable)
  35679. defines += "HABLE_TONEMAPPING";
  35680. else if (operator === TonemappingOperator.Reinhard)
  35681. defines += "REINHARD_TONEMAPPING";
  35682. else if (operator === TonemappingOperator.HejiDawson)
  35683. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35684. else if (operator === TonemappingOperator.Photographic)
  35685. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35686. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35687. this.onApply = function (effect) {
  35688. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35689. };
  35690. }
  35691. return TonemapPostProcess;
  35692. })(BABYLON.PostProcess);
  35693. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35694. })(BABYLON || (BABYLON = {}));
  35695. var BABYLON;
  35696. (function (BABYLON) {
  35697. var ReflectionProbe = (function () {
  35698. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35699. var _this = this;
  35700. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35701. this.name = name;
  35702. this._viewMatrix = BABYLON.Matrix.Identity();
  35703. this._target = BABYLON.Vector3.Zero();
  35704. this._add = BABYLON.Vector3.Zero();
  35705. this.position = BABYLON.Vector3.Zero();
  35706. this._scene = scene;
  35707. this._scene.reflectionProbes.push(this);
  35708. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35709. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35710. switch (faceIndex) {
  35711. case 0:
  35712. _this._add.copyFromFloats(1, 0, 0);
  35713. break;
  35714. case 1:
  35715. _this._add.copyFromFloats(-1, 0, 0);
  35716. break;
  35717. case 2:
  35718. _this._add.copyFromFloats(0, -1, 0);
  35719. break;
  35720. case 3:
  35721. _this._add.copyFromFloats(0, 1, 0);
  35722. break;
  35723. case 4:
  35724. _this._add.copyFromFloats(0, 0, 1);
  35725. break;
  35726. case 5:
  35727. _this._add.copyFromFloats(0, 0, -1);
  35728. break;
  35729. }
  35730. if (_this._attachedMesh) {
  35731. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35732. }
  35733. _this.position.addToRef(_this._add, _this._target);
  35734. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35735. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35736. };
  35737. this._renderTargetTexture.onAfterUnbind = function () {
  35738. scene.updateTransformMatrix(true);
  35739. };
  35740. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35741. }
  35742. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35743. get: function () {
  35744. return this._renderTargetTexture.refreshRate;
  35745. },
  35746. set: function (value) {
  35747. this._renderTargetTexture.refreshRate = value;
  35748. },
  35749. enumerable: true,
  35750. configurable: true
  35751. });
  35752. ReflectionProbe.prototype.getScene = function () {
  35753. return this._scene;
  35754. };
  35755. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35756. get: function () {
  35757. return this._renderTargetTexture;
  35758. },
  35759. enumerable: true,
  35760. configurable: true
  35761. });
  35762. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35763. get: function () {
  35764. return this._renderTargetTexture.renderList;
  35765. },
  35766. enumerable: true,
  35767. configurable: true
  35768. });
  35769. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35770. this._attachedMesh = mesh;
  35771. };
  35772. ReflectionProbe.prototype.dispose = function () {
  35773. var index = this._scene.reflectionProbes.indexOf(this);
  35774. if (index !== -1) {
  35775. // Remove from the scene if found
  35776. this._scene.reflectionProbes.splice(index, 1);
  35777. }
  35778. };
  35779. return ReflectionProbe;
  35780. })();
  35781. BABYLON.ReflectionProbe = ReflectionProbe;
  35782. })(BABYLON || (BABYLON = {}));
  35783. var BABYLON;
  35784. (function (BABYLON) {
  35785. var SolidParticle = (function () {
  35786. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35787. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35788. this.position = BABYLON.Vector3.Zero(); // position
  35789. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35790. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35791. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35792. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35793. this.alive = true; // alive
  35794. this.idx = particleIndex;
  35795. this._pos = positionIndex;
  35796. this._model = model;
  35797. this.shapeId = shapeId;
  35798. this.idxInShape = idxInShape;
  35799. }
  35800. return SolidParticle;
  35801. })();
  35802. BABYLON.SolidParticle = SolidParticle;
  35803. var ModelShape = (function () {
  35804. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35805. this.shapeID = id;
  35806. this._shape = shape;
  35807. this._shapeUV = shapeUV;
  35808. this._positionFunction = posFunction;
  35809. this._vertexFunction = vtxFunction;
  35810. }
  35811. return ModelShape;
  35812. })();
  35813. BABYLON.ModelShape = ModelShape;
  35814. })(BABYLON || (BABYLON = {}));
  35815. var BABYLON;
  35816. (function (BABYLON) {
  35817. var SolidParticleSystem = (function () {
  35818. function SolidParticleSystem(name, scene, options) {
  35819. // public members
  35820. this.particles = new Array();
  35821. this.nbParticles = 0;
  35822. this.billboard = false;
  35823. this.counter = 0;
  35824. this.vars = {};
  35825. this._positions = new Array();
  35826. this._indices = new Array();
  35827. this._normals = new Array();
  35828. this._colors = new Array();
  35829. this._uvs = new Array();
  35830. this._index = 0; // indices index
  35831. this._updatable = true;
  35832. this._pickable = false;
  35833. this._alwaysVisible = false;
  35834. this._shapeCounter = 0;
  35835. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35836. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35837. this._computeParticleColor = true;
  35838. this._computeParticleTexture = true;
  35839. this._computeParticleRotation = true;
  35840. this._computeParticleVertex = false;
  35841. this._cam_axisZ = BABYLON.Vector3.Zero();
  35842. this._cam_axisY = BABYLON.Vector3.Zero();
  35843. this._cam_axisX = BABYLON.Vector3.Zero();
  35844. this._axisX = BABYLON.Axis.X;
  35845. this._axisY = BABYLON.Axis.Y;
  35846. this._axisZ = BABYLON.Axis.Z;
  35847. this._fakeCamPos = BABYLON.Vector3.Zero();
  35848. this._rotMatrix = new BABYLON.Matrix();
  35849. this._invertMatrix = new BABYLON.Matrix();
  35850. this._rotated = BABYLON.Vector3.Zero();
  35851. this._quaternion = new BABYLON.Quaternion();
  35852. this._vertex = BABYLON.Vector3.Zero();
  35853. this._normal = BABYLON.Vector3.Zero();
  35854. this._yaw = 0.0;
  35855. this._pitch = 0.0;
  35856. this._roll = 0.0;
  35857. this._halfroll = 0.0;
  35858. this._halfpitch = 0.0;
  35859. this._halfyaw = 0.0;
  35860. this._sinRoll = 0.0;
  35861. this._cosRoll = 0.0;
  35862. this._sinPitch = 0.0;
  35863. this._cosPitch = 0.0;
  35864. this._sinYaw = 0.0;
  35865. this._cosYaw = 0.0;
  35866. this._w = 0.0;
  35867. this.name = name;
  35868. this._scene = scene;
  35869. this._camera = scene.activeCamera;
  35870. this._pickable = options ? options.isPickable : false;
  35871. if (options && options.updatable) {
  35872. this._updatable = options.updatable;
  35873. }
  35874. else {
  35875. this._updatable = true;
  35876. }
  35877. if (this._pickable) {
  35878. this.pickedParticles = [];
  35879. }
  35880. }
  35881. // build the SPS mesh : returns the mesh
  35882. SolidParticleSystem.prototype.buildMesh = function () {
  35883. if (this.nbParticles === 0) {
  35884. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35885. this.addShape(triangle, 1);
  35886. triangle.dispose();
  35887. }
  35888. this._positions32 = new Float32Array(this._positions);
  35889. this._uvs32 = new Float32Array(this._uvs);
  35890. this._colors32 = new Float32Array(this._colors);
  35891. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35892. this._normals32 = new Float32Array(this._normals);
  35893. this._fixedNormal32 = new Float32Array(this._normals);
  35894. var vertexData = new BABYLON.VertexData();
  35895. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35896. vertexData.indices = this._indices;
  35897. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35898. if (this._uvs32) {
  35899. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35900. ;
  35901. }
  35902. if (this._colors32) {
  35903. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35904. }
  35905. var mesh = new BABYLON.Mesh(name, this._scene);
  35906. vertexData.applyToMesh(mesh, this._updatable);
  35907. this.mesh = mesh;
  35908. this.mesh.isPickable = this._pickable;
  35909. // free memory
  35910. this._positions = null;
  35911. this._normals = null;
  35912. this._uvs = null;
  35913. this._colors = null;
  35914. if (!this._updatable) {
  35915. this.particles.length = 0;
  35916. }
  35917. return mesh;
  35918. };
  35919. //reset copy
  35920. SolidParticleSystem.prototype._resetCopy = function () {
  35921. this._copy.position.x = 0;
  35922. this._copy.position.y = 0;
  35923. this._copy.position.z = 0;
  35924. this._copy.rotation.x = 0;
  35925. this._copy.rotation.y = 0;
  35926. this._copy.rotation.z = 0;
  35927. this._copy.quaternion = null;
  35928. this._copy.scale.x = 1;
  35929. this._copy.scale.y = 1;
  35930. this._copy.scale.z = 1;
  35931. this._copy.uvs.x = 0;
  35932. this._copy.uvs.y = 0;
  35933. this._copy.uvs.z = 1;
  35934. this._copy.uvs.w = 1;
  35935. this._copy.color = null;
  35936. };
  35937. // _meshBuilder : inserts the shape model in the global SPS mesh
  35938. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35939. var i;
  35940. var u = 0;
  35941. var c = 0;
  35942. this._resetCopy();
  35943. if (options && options.positionFunction) {
  35944. options.positionFunction(this._copy, idx, idxInShape);
  35945. }
  35946. if (this._copy.quaternion) {
  35947. this._quaternion.x = this._copy.quaternion.x;
  35948. this._quaternion.y = this._copy.quaternion.y;
  35949. this._quaternion.z = this._copy.quaternion.z;
  35950. this._quaternion.w = this._copy.quaternion.w;
  35951. }
  35952. else {
  35953. this._yaw = this._copy.rotation.y;
  35954. this._pitch = this._copy.rotation.x;
  35955. this._roll = this._copy.rotation.z;
  35956. this._quaternionRotationYPR();
  35957. }
  35958. this._quaternionToRotationMatrix();
  35959. for (i = 0; i < shape.length; i++) {
  35960. this._vertex.x = shape[i].x;
  35961. this._vertex.y = shape[i].y;
  35962. this._vertex.z = shape[i].z;
  35963. if (options && options.vertexFunction) {
  35964. options.vertexFunction(this._copy, this._vertex, i);
  35965. }
  35966. this._vertex.x *= this._copy.scale.x;
  35967. this._vertex.y *= this._copy.scale.y;
  35968. this._vertex.z *= this._copy.scale.z;
  35969. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35970. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35971. if (meshUV) {
  35972. 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);
  35973. u += 2;
  35974. }
  35975. if (this._copy.color) {
  35976. this._color = this._copy.color;
  35977. }
  35978. else if (meshCol && meshCol[c]) {
  35979. this._color.r = meshCol[c];
  35980. this._color.g = meshCol[c + 1];
  35981. this._color.b = meshCol[c + 2];
  35982. this._color.a = meshCol[c + 3];
  35983. }
  35984. else {
  35985. this._color.r = 1;
  35986. this._color.g = 1;
  35987. this._color.b = 1;
  35988. this._color.a = 1;
  35989. }
  35990. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35991. c += 4;
  35992. }
  35993. for (i = 0; i < meshInd.length; i++) {
  35994. indices.push(p + meshInd[i]);
  35995. }
  35996. if (this._pickable) {
  35997. var nbfaces = meshInd.length / 3;
  35998. for (i = 0; i < nbfaces; i++) {
  35999. this.pickedParticles.push({ idx: idx, faceId: i });
  36000. }
  36001. }
  36002. };
  36003. // returns a shape array from positions array
  36004. SolidParticleSystem.prototype._posToShape = function (positions) {
  36005. var shape = [];
  36006. for (var i = 0; i < positions.length; i += 3) {
  36007. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36008. }
  36009. return shape;
  36010. };
  36011. // returns a shapeUV array from a Vector4 uvs
  36012. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36013. var shapeUV = [];
  36014. if (uvs) {
  36015. for (var i = 0; i < uvs.length; i++)
  36016. shapeUV.push(uvs[i]);
  36017. }
  36018. return shapeUV;
  36019. };
  36020. // adds a new particle object in the particles array
  36021. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36022. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36023. };
  36024. // add solid particles from a shape model in the particles array
  36025. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36026. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36027. var meshInd = mesh.getIndices();
  36028. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36029. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36030. var shape = this._posToShape(meshPos);
  36031. var shapeUV = this._uvsToShapeUV(meshUV);
  36032. var posfunc = options ? options.positionFunction : null;
  36033. var vtxfunc = options ? options.vertexFunction : null;
  36034. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36035. // particles
  36036. var idx = this.nbParticles;
  36037. for (var i = 0; i < nb; i++) {
  36038. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36039. if (this._updatable) {
  36040. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36041. }
  36042. this._index += shape.length;
  36043. idx++;
  36044. }
  36045. this.nbParticles += nb;
  36046. this._shapeCounter++;
  36047. return this._shapeCounter;
  36048. };
  36049. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36050. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36051. this._resetCopy();
  36052. if (particle._model._positionFunction) {
  36053. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36054. }
  36055. if (this._copy.quaternion) {
  36056. this._quaternion.x = this._copy.quaternion.x;
  36057. this._quaternion.y = this._copy.quaternion.y;
  36058. this._quaternion.z = this._copy.quaternion.z;
  36059. this._quaternion.w = this._copy.quaternion.w;
  36060. }
  36061. else {
  36062. this._yaw = this._copy.rotation.y;
  36063. this._pitch = this._copy.rotation.x;
  36064. this._roll = this._copy.rotation.z;
  36065. this._quaternionRotationYPR();
  36066. }
  36067. this._quaternionToRotationMatrix();
  36068. this._shape = particle._model._shape;
  36069. for (var pt = 0; pt < this._shape.length; pt++) {
  36070. this._vertex.x = this._shape[pt].x;
  36071. this._vertex.y = this._shape[pt].y;
  36072. this._vertex.z = this._shape[pt].z;
  36073. if (particle._model._vertexFunction) {
  36074. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36075. }
  36076. this._vertex.x *= this._copy.scale.x;
  36077. this._vertex.y *= this._copy.scale.y;
  36078. this._vertex.z *= this._copy.scale.z;
  36079. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36080. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36081. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36082. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36083. }
  36084. particle.position.x = 0;
  36085. particle.position.y = 0;
  36086. particle.position.z = 0;
  36087. particle.rotation.x = 0;
  36088. particle.rotation.y = 0;
  36089. particle.rotation.z = 0;
  36090. particle.quaternion = null;
  36091. particle.scale.x = 1;
  36092. particle.scale.y = 1;
  36093. particle.scale.z = 1;
  36094. };
  36095. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36096. SolidParticleSystem.prototype.rebuildMesh = function () {
  36097. for (var p = 0; p < this.particles.length; p++) {
  36098. this._rebuildParticle(this.particles[p]);
  36099. }
  36100. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36101. };
  36102. // sets all the particles : updates the VBO
  36103. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36104. if (start === void 0) { start = 0; }
  36105. if (end === void 0) { end = this.nbParticles - 1; }
  36106. if (update === void 0) { update = true; }
  36107. if (!this._updatable) {
  36108. return;
  36109. }
  36110. // custom beforeUpdate
  36111. this.beforeUpdateParticles(start, end, update);
  36112. this._cam_axisX.x = 1;
  36113. this._cam_axisX.y = 0;
  36114. this._cam_axisX.z = 0;
  36115. this._cam_axisY.x = 0;
  36116. this._cam_axisY.y = 1;
  36117. this._cam_axisY.z = 0;
  36118. this._cam_axisZ.x = 0;
  36119. this._cam_axisZ.y = 0;
  36120. this._cam_axisZ.z = 1;
  36121. // if the particles will always face the camera
  36122. if (this.billboard) {
  36123. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36124. this._yaw = this.mesh.rotation.y;
  36125. this._pitch = this.mesh.rotation.x;
  36126. this._roll = this.mesh.rotation.z;
  36127. this._quaternionRotationYPR();
  36128. this._quaternionToRotationMatrix();
  36129. this._rotMatrix.invertToRef(this._invertMatrix);
  36130. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36131. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36132. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36133. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36134. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36135. this._cam_axisY.normalize();
  36136. this._cam_axisX.normalize();
  36137. this._cam_axisZ.normalize();
  36138. }
  36139. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36140. var idx = 0;
  36141. var index = 0;
  36142. var colidx = 0;
  36143. var colorIndex = 0;
  36144. var uvidx = 0;
  36145. var uvIndex = 0;
  36146. // particle loop
  36147. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36148. for (var p = start; p <= end; p++) {
  36149. this._particle = this.particles[p];
  36150. this._shape = this._particle._model._shape;
  36151. this._shapeUV = this._particle._model._shapeUV;
  36152. // call to custom user function to update the particle properties
  36153. this.updateParticle(this._particle);
  36154. // particle rotation matrix
  36155. if (this.billboard) {
  36156. this._particle.rotation.x = 0.0;
  36157. this._particle.rotation.y = 0.0;
  36158. }
  36159. if (this._computeParticleRotation) {
  36160. if (this._particle.quaternion) {
  36161. this._quaternion.x = this._particle.quaternion.x;
  36162. this._quaternion.y = this._particle.quaternion.y;
  36163. this._quaternion.z = this._particle.quaternion.z;
  36164. this._quaternion.w = this._particle.quaternion.w;
  36165. }
  36166. else {
  36167. this._yaw = this._particle.rotation.y;
  36168. this._pitch = this._particle.rotation.x;
  36169. this._roll = this._particle.rotation.z;
  36170. this._quaternionRotationYPR();
  36171. }
  36172. this._quaternionToRotationMatrix();
  36173. }
  36174. for (var pt = 0; pt < this._shape.length; pt++) {
  36175. idx = index + pt * 3;
  36176. colidx = colorIndex + pt * 4;
  36177. uvidx = uvIndex + pt * 2;
  36178. this._vertex.x = this._shape[pt].x;
  36179. this._vertex.y = this._shape[pt].y;
  36180. this._vertex.z = this._shape[pt].z;
  36181. if (this._computeParticleVertex) {
  36182. this.updateParticleVertex(this._particle, this._vertex, pt);
  36183. }
  36184. // positions
  36185. this._vertex.x *= this._particle.scale.x;
  36186. this._vertex.y *= this._particle.scale.y;
  36187. this._vertex.z *= this._particle.scale.z;
  36188. 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];
  36189. 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;
  36190. 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;
  36191. 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;
  36192. 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;
  36193. 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;
  36194. 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;
  36195. // normals : if the particles can't be morphed then just rotate the normals
  36196. if (!this._computeParticleVertex && !this.billboard) {
  36197. this._normal.x = this._fixedNormal32[idx];
  36198. this._normal.y = this._fixedNormal32[idx + 1];
  36199. this._normal.z = this._fixedNormal32[idx + 2];
  36200. 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];
  36201. 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;
  36202. 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;
  36203. 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;
  36204. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36205. 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;
  36206. 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;
  36207. }
  36208. if (this._computeParticleColor) {
  36209. this._colors32[colidx] = this._particle.color.r;
  36210. this._colors32[colidx + 1] = this._particle.color.g;
  36211. this._colors32[colidx + 2] = this._particle.color.b;
  36212. this._colors32[colidx + 3] = this._particle.color.a;
  36213. }
  36214. if (this._computeParticleTexture) {
  36215. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36216. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36217. }
  36218. }
  36219. index = idx + 3;
  36220. colorIndex = colidx + 4;
  36221. uvIndex = uvidx + 2;
  36222. }
  36223. if (update) {
  36224. if (this._computeParticleColor) {
  36225. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36226. }
  36227. if (this._computeParticleTexture) {
  36228. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36229. }
  36230. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36231. if (!this.mesh.areNormalsFrozen) {
  36232. if (this._computeParticleVertex || this.billboard) {
  36233. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36234. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36235. for (var i = 0; i < this._normals32.length; i++) {
  36236. this._fixedNormal32[i] = this._normals32[i];
  36237. }
  36238. }
  36239. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36240. }
  36241. }
  36242. this.afterUpdateParticles(start, end, update);
  36243. };
  36244. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36245. this._halfroll = this._roll * 0.5;
  36246. this._halfpitch = this._pitch * 0.5;
  36247. this._halfyaw = this._yaw * 0.5;
  36248. this._sinRoll = Math.sin(this._halfroll);
  36249. this._cosRoll = Math.cos(this._halfroll);
  36250. this._sinPitch = Math.sin(this._halfpitch);
  36251. this._cosPitch = Math.cos(this._halfpitch);
  36252. this._sinYaw = Math.sin(this._halfyaw);
  36253. this._cosYaw = Math.cos(this._halfyaw);
  36254. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36255. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36256. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36257. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36258. };
  36259. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36260. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36261. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36262. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36263. this._rotMatrix.m[3] = 0;
  36264. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36265. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36266. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36267. this._rotMatrix.m[7] = 0;
  36268. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36269. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36270. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36271. this._rotMatrix.m[11] = 0;
  36272. this._rotMatrix.m[12] = 0;
  36273. this._rotMatrix.m[13] = 0;
  36274. this._rotMatrix.m[14] = 0;
  36275. this._rotMatrix.m[15] = 1.0;
  36276. };
  36277. // dispose the SPS
  36278. SolidParticleSystem.prototype.dispose = function () {
  36279. this.mesh.dispose();
  36280. this.vars = null;
  36281. // drop references to internal big arrays for the GC
  36282. this._positions = null;
  36283. this._indices = null;
  36284. this._normals = null;
  36285. this._uvs = null;
  36286. this._colors = null;
  36287. this._positions32 = null;
  36288. this._normals32 = null;
  36289. this._fixedNormal32 = null;
  36290. this._uvs32 = null;
  36291. this._colors32 = null;
  36292. this.pickedParticles = null;
  36293. };
  36294. // Visibilty helpers
  36295. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36296. this.mesh.refreshBoundingInfo();
  36297. };
  36298. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36299. // getter and setter
  36300. get: function () {
  36301. return this._alwaysVisible;
  36302. },
  36303. set: function (val) {
  36304. this._alwaysVisible = val;
  36305. this.mesh.alwaysSelectAsActiveMesh = val;
  36306. },
  36307. enumerable: true,
  36308. configurable: true
  36309. });
  36310. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36311. // getters
  36312. get: function () {
  36313. return this._computeParticleRotation;
  36314. },
  36315. // Optimizer setters
  36316. set: function (val) {
  36317. this._computeParticleRotation = val;
  36318. },
  36319. enumerable: true,
  36320. configurable: true
  36321. });
  36322. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36323. get: function () {
  36324. return this._computeParticleColor;
  36325. },
  36326. set: function (val) {
  36327. this._computeParticleColor = val;
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36333. get: function () {
  36334. return this._computeParticleTexture;
  36335. },
  36336. set: function (val) {
  36337. this._computeParticleTexture = val;
  36338. },
  36339. enumerable: true,
  36340. configurable: true
  36341. });
  36342. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36343. get: function () {
  36344. return this._computeParticleVertex;
  36345. },
  36346. set: function (val) {
  36347. this._computeParticleVertex = val;
  36348. },
  36349. enumerable: true,
  36350. configurable: true
  36351. });
  36352. // =======================================================================
  36353. // Particle behavior logic
  36354. // these following methods may be overwritten by the user to fit his needs
  36355. // init : sets all particles first values and calls updateParticle to set them in space
  36356. // can be overwritten by the user
  36357. SolidParticleSystem.prototype.initParticles = function () {
  36358. };
  36359. // recycles a particle : can by overwritten by the user
  36360. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36361. return particle;
  36362. };
  36363. // updates a particle : can be overwritten by the user
  36364. // will be called on each particle by setParticles() :
  36365. // ex : just set a particle position or velocity and recycle conditions
  36366. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36367. return particle;
  36368. };
  36369. // updates a vertex of a particle : can be overwritten by the user
  36370. // will be called on each vertex particle by setParticles() :
  36371. // particle : the current particle
  36372. // vertex : the current index of the current particle
  36373. // pt : the index of the current vertex in the particle shape
  36374. // ex : just set a vertex particle position
  36375. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36376. return vertex;
  36377. };
  36378. // will be called before any other treatment by setParticles()
  36379. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36380. };
  36381. // will be called after all setParticles() treatments
  36382. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36383. };
  36384. return SolidParticleSystem;
  36385. })();
  36386. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36387. })(BABYLON || (BABYLON = {}));
  36388. 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\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\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\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - 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] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < 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\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 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\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 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\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\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\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\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\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}"};
  36389. 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,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},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,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,N=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*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*S+o*D)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*S-n*Z+o*W)*b,t.m[15]=(i*D-n*N+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],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,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;\nt.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;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}();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=_}(BABYLON||(BABYLON={}));";
  36390. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36391. module.exports = BABYLON;
  36392. };