babylon.max.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447
  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. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. })(BABYLON || (BABYLON = {}));
  2955. var BABYLON;
  2956. (function (BABYLON) {
  2957. var Database = (function () {
  2958. function Database(urlToScene, callbackManifestChecked) {
  2959. // Handling various flavors of prefixed version of IndexedDB
  2960. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2961. this.callbackManifestChecked = callbackManifestChecked;
  2962. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2963. this.db = null;
  2964. this.enableSceneOffline = false;
  2965. this.enableTexturesOffline = false;
  2966. this.manifestVersionFound = 0;
  2967. this.mustUpdateRessources = false;
  2968. this.hasReachedQuota = false;
  2969. if (!Database.IDBStorageEnabled) {
  2970. this.callbackManifestChecked(true);
  2971. }
  2972. else {
  2973. this.checkManifestFile();
  2974. }
  2975. }
  2976. Database.prototype.checkManifestFile = function () {
  2977. var _this = this;
  2978. function noManifestFile() {
  2979. that.enableSceneOffline = false;
  2980. that.enableTexturesOffline = false;
  2981. that.callbackManifestChecked(false);
  2982. }
  2983. var that = this;
  2984. var manifestURL = this.currentSceneUrl + ".manifest";
  2985. var xhr = new XMLHttpRequest();
  2986. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2987. xhr.open("GET", manifestURLTimeStamped, true);
  2988. xhr.addEventListener("load", function () {
  2989. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2990. try {
  2991. var manifestFile = JSON.parse(xhr.response);
  2992. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2993. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2994. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2995. _this.manifestVersionFound = manifestFile.version;
  2996. }
  2997. if (_this.callbackManifestChecked) {
  2998. _this.callbackManifestChecked(true);
  2999. }
  3000. }
  3001. catch (ex) {
  3002. noManifestFile();
  3003. }
  3004. }
  3005. else {
  3006. noManifestFile();
  3007. }
  3008. }, false);
  3009. xhr.addEventListener("error", function (event) {
  3010. noManifestFile();
  3011. }, false);
  3012. try {
  3013. xhr.send();
  3014. }
  3015. catch (ex) {
  3016. BABYLON.Tools.Error("Error on XHR send request.");
  3017. that.callbackManifestChecked(false);
  3018. }
  3019. };
  3020. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3021. var _this = this;
  3022. function handleError() {
  3023. that.isSupported = false;
  3024. if (errorCallback)
  3025. errorCallback();
  3026. }
  3027. var that = this;
  3028. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3029. // Your browser doesn't support IndexedDB
  3030. this.isSupported = false;
  3031. if (errorCallback)
  3032. errorCallback();
  3033. }
  3034. else {
  3035. // If the DB hasn't been opened or created yet
  3036. if (!this.db) {
  3037. this.hasReachedQuota = false;
  3038. this.isSupported = true;
  3039. var request = this.idbFactory.open("babylonjs", 1);
  3040. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3041. request.onerror = function (event) {
  3042. handleError();
  3043. };
  3044. // executes when a version change transaction cannot complete due to other active transactions
  3045. request.onblocked = function (event) {
  3046. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3047. handleError();
  3048. };
  3049. // DB has been opened successfully
  3050. request.onsuccess = function (event) {
  3051. _this.db = request.result;
  3052. successCallback();
  3053. };
  3054. // Initialization of the DB. Creating Scenes & Textures stores
  3055. request.onupgradeneeded = function (event) {
  3056. _this.db = (event.target).result;
  3057. try {
  3058. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3059. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3060. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3061. }
  3062. catch (ex) {
  3063. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3064. handleError();
  3065. }
  3066. };
  3067. }
  3068. else {
  3069. if (successCallback)
  3070. successCallback();
  3071. }
  3072. }
  3073. };
  3074. Database.prototype.loadImageFromDB = function (url, image) {
  3075. var _this = this;
  3076. var completeURL = Database.ReturnFullUrlLocation(url);
  3077. var saveAndLoadImage = function () {
  3078. if (!_this.hasReachedQuota && _this.db !== null) {
  3079. // the texture is not yet in the DB, let's try to save it
  3080. _this._saveImageIntoDBAsync(completeURL, image);
  3081. }
  3082. else {
  3083. image.src = url;
  3084. }
  3085. };
  3086. if (!this.mustUpdateRessources) {
  3087. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3088. }
  3089. else {
  3090. saveAndLoadImage();
  3091. }
  3092. };
  3093. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3094. if (this.isSupported && this.db !== null) {
  3095. var texture;
  3096. var transaction = this.db.transaction(["textures"]);
  3097. transaction.onabort = function (event) {
  3098. image.src = url;
  3099. };
  3100. transaction.oncomplete = function (event) {
  3101. var blobTextureURL;
  3102. if (texture) {
  3103. var URL = window.URL || window.webkitURL;
  3104. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3105. image.onerror = function () {
  3106. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3107. image.src = url;
  3108. };
  3109. image.src = blobTextureURL;
  3110. }
  3111. else {
  3112. notInDBCallback();
  3113. }
  3114. };
  3115. var getRequest = transaction.objectStore("textures").get(url);
  3116. getRequest.onsuccess = function (event) {
  3117. texture = (event.target).result;
  3118. };
  3119. getRequest.onerror = function (event) {
  3120. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3121. image.src = url;
  3122. };
  3123. }
  3124. else {
  3125. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3126. image.src = url;
  3127. }
  3128. };
  3129. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3130. var _this = this;
  3131. if (this.isSupported) {
  3132. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3133. var generateBlobUrl = function () {
  3134. var blobTextureURL;
  3135. if (blob) {
  3136. var URL = window.URL || window.webkitURL;
  3137. try {
  3138. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3139. }
  3140. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3141. catch (ex) {
  3142. blobTextureURL = URL.createObjectURL(blob);
  3143. }
  3144. }
  3145. image.src = blobTextureURL;
  3146. };
  3147. if (Database.IsUASupportingBlobStorage) {
  3148. var xhr = new XMLHttpRequest(), blob;
  3149. xhr.open("GET", url, true);
  3150. xhr.responseType = "blob";
  3151. xhr.addEventListener("load", function () {
  3152. if (xhr.status === 200) {
  3153. // Blob as response (XHR2)
  3154. blob = xhr.response;
  3155. var transaction = _this.db.transaction(["textures"], "readwrite");
  3156. // the transaction could abort because of a QuotaExceededError error
  3157. transaction.onabort = function (event) {
  3158. try {
  3159. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3160. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3161. this.hasReachedQuota = true;
  3162. }
  3163. }
  3164. catch (ex) { }
  3165. generateBlobUrl();
  3166. };
  3167. transaction.oncomplete = function (event) {
  3168. generateBlobUrl();
  3169. };
  3170. var newTexture = { textureUrl: url, data: blob };
  3171. try {
  3172. // Put the blob into the dabase
  3173. var addRequest = transaction.objectStore("textures").put(newTexture);
  3174. addRequest.onsuccess = function (event) {
  3175. };
  3176. addRequest.onerror = function (event) {
  3177. generateBlobUrl();
  3178. };
  3179. }
  3180. catch (ex) {
  3181. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3182. if (ex.code === 25) {
  3183. Database.IsUASupportingBlobStorage = false;
  3184. }
  3185. image.src = url;
  3186. }
  3187. }
  3188. else {
  3189. image.src = url;
  3190. }
  3191. }, false);
  3192. xhr.addEventListener("error", function (event) {
  3193. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3194. image.src = url;
  3195. }, false);
  3196. xhr.send();
  3197. }
  3198. else {
  3199. image.src = url;
  3200. }
  3201. }
  3202. else {
  3203. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3204. image.src = url;
  3205. }
  3206. };
  3207. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3208. var _this = this;
  3209. var updateVersion = function (event) {
  3210. // the version is not yet in the DB or we need to update it
  3211. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3212. };
  3213. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3214. };
  3215. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3216. var _this = this;
  3217. if (this.isSupported) {
  3218. var version;
  3219. try {
  3220. var transaction = this.db.transaction(["versions"]);
  3221. transaction.oncomplete = function (event) {
  3222. if (version) {
  3223. // If the version in the JSON file is > than the version in DB
  3224. if (_this.manifestVersionFound > version.data) {
  3225. _this.mustUpdateRessources = true;
  3226. updateInDBCallback();
  3227. }
  3228. else {
  3229. callback(version.data);
  3230. }
  3231. }
  3232. else {
  3233. _this.mustUpdateRessources = true;
  3234. updateInDBCallback();
  3235. }
  3236. };
  3237. transaction.onabort = function (event) {
  3238. callback(-1);
  3239. };
  3240. var getRequest = transaction.objectStore("versions").get(url);
  3241. getRequest.onsuccess = function (event) {
  3242. version = (event.target).result;
  3243. };
  3244. getRequest.onerror = function (event) {
  3245. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3246. callback(-1);
  3247. };
  3248. }
  3249. catch (ex) {
  3250. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3251. callback(-1);
  3252. }
  3253. }
  3254. else {
  3255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3256. callback(-1);
  3257. }
  3258. };
  3259. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3260. var _this = this;
  3261. if (this.isSupported && !this.hasReachedQuota) {
  3262. try {
  3263. // Open a transaction to the database
  3264. var transaction = this.db.transaction(["versions"], "readwrite");
  3265. // the transaction could abort because of a QuotaExceededError error
  3266. transaction.onabort = function (event) {
  3267. try {
  3268. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3269. _this.hasReachedQuota = true;
  3270. }
  3271. }
  3272. catch (ex) { }
  3273. callback(-1);
  3274. };
  3275. transaction.oncomplete = function (event) {
  3276. callback(_this.manifestVersionFound);
  3277. };
  3278. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3279. // Put the scene into the database
  3280. var addRequest = transaction.objectStore("versions").put(newVersion);
  3281. addRequest.onsuccess = function (event) {
  3282. };
  3283. addRequest.onerror = function (event) {
  3284. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3285. };
  3286. }
  3287. catch (ex) {
  3288. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3289. callback(-1);
  3290. }
  3291. }
  3292. else {
  3293. callback(-1);
  3294. }
  3295. };
  3296. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3297. var _this = this;
  3298. var completeUrl = Database.ReturnFullUrlLocation(url);
  3299. var saveAndLoadFile = function (event) {
  3300. // the scene is not yet in the DB, let's try to save it
  3301. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3302. };
  3303. this._checkVersionFromDB(completeUrl, function (version) {
  3304. if (version !== -1) {
  3305. if (!_this.mustUpdateRessources) {
  3306. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3307. }
  3308. else {
  3309. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3310. }
  3311. }
  3312. else {
  3313. errorCallback();
  3314. }
  3315. });
  3316. };
  3317. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3318. if (this.isSupported) {
  3319. var targetStore;
  3320. if (url.indexOf(".babylon") !== -1) {
  3321. targetStore = "scenes";
  3322. }
  3323. else {
  3324. targetStore = "textures";
  3325. }
  3326. var file;
  3327. var transaction = this.db.transaction([targetStore]);
  3328. transaction.oncomplete = function (event) {
  3329. if (file) {
  3330. callback(file.data);
  3331. }
  3332. else {
  3333. notInDBCallback();
  3334. }
  3335. };
  3336. transaction.onabort = function (event) {
  3337. notInDBCallback();
  3338. };
  3339. var getRequest = transaction.objectStore(targetStore).get(url);
  3340. getRequest.onsuccess = function (event) {
  3341. file = (event.target).result;
  3342. };
  3343. getRequest.onerror = function (event) {
  3344. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3345. notInDBCallback();
  3346. };
  3347. }
  3348. else {
  3349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3350. callback();
  3351. }
  3352. };
  3353. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3354. var _this = this;
  3355. if (this.isSupported) {
  3356. var targetStore;
  3357. if (url.indexOf(".babylon") !== -1) {
  3358. targetStore = "scenes";
  3359. }
  3360. else {
  3361. targetStore = "textures";
  3362. }
  3363. // Create XHR
  3364. var xhr = new XMLHttpRequest(), fileData;
  3365. xhr.open("GET", url, true);
  3366. if (useArrayBuffer) {
  3367. xhr.responseType = "arraybuffer";
  3368. }
  3369. xhr.onprogress = progressCallback;
  3370. xhr.addEventListener("load", function () {
  3371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3372. // Blob as response (XHR2)
  3373. //fileData = xhr.responseText;
  3374. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3375. if (!_this.hasReachedQuota) {
  3376. // Open a transaction to the database
  3377. var transaction = _this.db.transaction([targetStore], "readwrite");
  3378. // the transaction could abort because of a QuotaExceededError error
  3379. transaction.onabort = function (event) {
  3380. try {
  3381. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3382. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3383. this.hasReachedQuota = true;
  3384. }
  3385. }
  3386. catch (ex) { }
  3387. callback(fileData);
  3388. };
  3389. transaction.oncomplete = function (event) {
  3390. callback(fileData);
  3391. };
  3392. var newFile;
  3393. if (targetStore === "scenes") {
  3394. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3395. }
  3396. else {
  3397. newFile = { textureUrl: url, data: fileData };
  3398. }
  3399. try {
  3400. // Put the scene into the database
  3401. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3402. addRequest.onsuccess = function (event) {
  3403. };
  3404. addRequest.onerror = function (event) {
  3405. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3406. };
  3407. }
  3408. catch (ex) {
  3409. callback(fileData);
  3410. }
  3411. }
  3412. else {
  3413. callback(fileData);
  3414. }
  3415. }
  3416. else {
  3417. callback();
  3418. }
  3419. }, false);
  3420. xhr.addEventListener("error", function (event) {
  3421. BABYLON.Tools.Error("error on XHR request.");
  3422. callback();
  3423. }, false);
  3424. xhr.send();
  3425. }
  3426. else {
  3427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3428. callback();
  3429. }
  3430. };
  3431. Database.IsUASupportingBlobStorage = true;
  3432. Database.IDBStorageEnabled = true;
  3433. Database.parseURL = function (url) {
  3434. var a = document.createElement('a');
  3435. a.href = url;
  3436. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3437. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3438. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3439. return absLocation;
  3440. };
  3441. Database.ReturnFullUrlLocation = function (url) {
  3442. if (url.indexOf("http:/") === -1) {
  3443. return (Database.parseURL(window.location.href) + url);
  3444. }
  3445. else {
  3446. return url;
  3447. }
  3448. };
  3449. return Database;
  3450. })();
  3451. BABYLON.Database = Database;
  3452. })(BABYLON || (BABYLON = {}));
  3453. var BABYLON;
  3454. (function (BABYLON) {
  3455. var Internals;
  3456. (function (Internals) {
  3457. /*
  3458. * Based on jsTGALoader - Javascript loader for TGA file
  3459. * By Vincent Thibault
  3460. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3461. */
  3462. var TGATools = (function () {
  3463. function TGATools() {
  3464. }
  3465. TGATools.GetTGAHeader = function (data) {
  3466. var offset = 0;
  3467. var header = {
  3468. id_length: data[offset++],
  3469. colormap_type: data[offset++],
  3470. image_type: data[offset++],
  3471. colormap_index: data[offset++] | data[offset++] << 8,
  3472. colormap_length: data[offset++] | data[offset++] << 8,
  3473. colormap_size: data[offset++],
  3474. origin: [
  3475. data[offset++] | data[offset++] << 8,
  3476. data[offset++] | data[offset++] << 8
  3477. ],
  3478. width: data[offset++] | data[offset++] << 8,
  3479. height: data[offset++] | data[offset++] << 8,
  3480. pixel_size: data[offset++],
  3481. flags: data[offset++]
  3482. };
  3483. return header;
  3484. };
  3485. TGATools.UploadContent = function (gl, data) {
  3486. // Not enough data to contain header ?
  3487. if (data.length < 19) {
  3488. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3489. return;
  3490. }
  3491. // Read Header
  3492. var offset = 18;
  3493. var header = TGATools.GetTGAHeader(data);
  3494. // Assume it's a valid Targa file.
  3495. if (header.id_length + offset > data.length) {
  3496. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3497. return;
  3498. }
  3499. // Skip not needed data
  3500. offset += header.id_length;
  3501. var use_rle = false;
  3502. var use_pal = false;
  3503. var use_rgb = false;
  3504. var use_grey = false;
  3505. // Get some informations.
  3506. switch (header.image_type) {
  3507. case TGATools._TYPE_RLE_INDEXED:
  3508. use_rle = true;
  3509. case TGATools._TYPE_INDEXED:
  3510. use_pal = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_RGB:
  3513. use_rle = true;
  3514. case TGATools._TYPE_RGB:
  3515. use_rgb = true;
  3516. break;
  3517. case TGATools._TYPE_RLE_GREY:
  3518. use_rle = true;
  3519. case TGATools._TYPE_GREY:
  3520. use_grey = true;
  3521. break;
  3522. }
  3523. var pixel_data;
  3524. var numAlphaBits = header.flags & 0xf;
  3525. var pixel_size = header.pixel_size >> 3;
  3526. var pixel_total = header.width * header.height * pixel_size;
  3527. // Read palettes
  3528. var palettes;
  3529. if (use_pal) {
  3530. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3531. }
  3532. // Read LRE
  3533. if (use_rle) {
  3534. pixel_data = new Uint8Array(pixel_total);
  3535. var c, count, i;
  3536. var localOffset = 0;
  3537. var pixels = new Uint8Array(pixel_size);
  3538. while (offset < pixel_total && localOffset < pixel_total) {
  3539. c = data[offset++];
  3540. count = (c & 0x7f) + 1;
  3541. // RLE pixels
  3542. if (c & 0x80) {
  3543. // Bind pixel tmp array
  3544. for (i = 0; i < pixel_size; ++i) {
  3545. pixels[i] = data[offset++];
  3546. }
  3547. // Copy pixel array
  3548. for (i = 0; i < count; ++i) {
  3549. pixel_data.set(pixels, localOffset + i * pixel_size);
  3550. }
  3551. localOffset += pixel_size * count;
  3552. }
  3553. else {
  3554. count *= pixel_size;
  3555. for (i = 0; i < count; ++i) {
  3556. pixel_data[localOffset + i] = data[offset++];
  3557. }
  3558. localOffset += count;
  3559. }
  3560. }
  3561. }
  3562. else {
  3563. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3564. }
  3565. // Load to texture
  3566. var x_start, y_start, x_step, y_step, y_end, x_end;
  3567. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3568. default:
  3569. case TGATools._ORIGIN_UL:
  3570. x_start = 0;
  3571. x_step = 1;
  3572. x_end = header.width;
  3573. y_start = 0;
  3574. y_step = 1;
  3575. y_end = header.height;
  3576. break;
  3577. case TGATools._ORIGIN_BL:
  3578. x_start = 0;
  3579. x_step = 1;
  3580. x_end = header.width;
  3581. y_start = header.height - 1;
  3582. y_step = -1;
  3583. y_end = -1;
  3584. break;
  3585. case TGATools._ORIGIN_UR:
  3586. x_start = header.width - 1;
  3587. x_step = -1;
  3588. x_end = -1;
  3589. y_start = 0;
  3590. y_step = 1;
  3591. y_end = header.height;
  3592. break;
  3593. case TGATools._ORIGIN_BR:
  3594. x_start = header.width - 1;
  3595. x_step = -1;
  3596. x_end = -1;
  3597. y_start = header.height - 1;
  3598. y_step = -1;
  3599. y_end = -1;
  3600. break;
  3601. }
  3602. // Load the specify method
  3603. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3604. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3605. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3606. };
  3607. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3608. var image = pixel_data, colormap = palettes;
  3609. var width = header.width, height = header.height;
  3610. var color, i = 0, x, y;
  3611. var imageData = new Uint8Array(width * height * 4);
  3612. for (y = y_start; y !== y_end; y += y_step) {
  3613. for (x = x_start; x !== x_end; x += x_step, i++) {
  3614. color = image[i];
  3615. imageData[(x + width * y) * 4 + 3] = 255;
  3616. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3617. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3618. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3619. }
  3620. }
  3621. return imageData;
  3622. };
  3623. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3624. var image = pixel_data;
  3625. var width = header.width, height = header.height;
  3626. var color, i = 0, x, y;
  3627. var imageData = new Uint8Array(width * height * 4);
  3628. for (y = y_start; y !== y_end; y += y_step) {
  3629. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3630. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3631. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3632. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3633. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3634. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3635. }
  3636. }
  3637. return imageData;
  3638. };
  3639. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3640. var image = pixel_data;
  3641. var width = header.width, height = header.height;
  3642. var i = 0, x, y;
  3643. var imageData = new Uint8Array(width * height * 4);
  3644. for (y = y_start; y !== y_end; y += y_step) {
  3645. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3646. imageData[(x + width * y) * 4 + 3] = 255;
  3647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3650. }
  3651. }
  3652. return imageData;
  3653. };
  3654. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3655. var image = pixel_data;
  3656. var width = header.width, height = header.height;
  3657. var i = 0, x, y;
  3658. var imageData = new Uint8Array(width * height * 4);
  3659. for (y = y_start; y !== y_end; y += y_step) {
  3660. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3662. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3663. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3664. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3665. }
  3666. }
  3667. return imageData;
  3668. };
  3669. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3670. var image = pixel_data;
  3671. var width = header.width, height = header.height;
  3672. var color, i = 0, x, y;
  3673. var imageData = new Uint8Array(width * height * 4);
  3674. for (y = y_start; y !== y_end; y += y_step) {
  3675. for (x = x_start; x !== x_end; x += x_step, i++) {
  3676. color = image[i];
  3677. imageData[(x + width * y) * 4 + 0] = color;
  3678. imageData[(x + width * y) * 4 + 1] = color;
  3679. imageData[(x + width * y) * 4 + 2] = color;
  3680. imageData[(x + width * y) * 4 + 3] = 255;
  3681. }
  3682. }
  3683. return imageData;
  3684. };
  3685. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3686. var image = pixel_data;
  3687. var width = header.width, height = header.height;
  3688. var i = 0, x, y;
  3689. var imageData = new Uint8Array(width * height * 4);
  3690. for (y = y_start; y !== y_end; y += y_step) {
  3691. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3692. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3693. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3694. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3695. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3696. }
  3697. }
  3698. return imageData;
  3699. };
  3700. TGATools._TYPE_NO_DATA = 0;
  3701. TGATools._TYPE_INDEXED = 1;
  3702. TGATools._TYPE_RGB = 2;
  3703. TGATools._TYPE_GREY = 3;
  3704. TGATools._TYPE_RLE_INDEXED = 9;
  3705. TGATools._TYPE_RLE_RGB = 10;
  3706. TGATools._TYPE_RLE_GREY = 11;
  3707. TGATools._ORIGIN_MASK = 0x30;
  3708. TGATools._ORIGIN_SHIFT = 0x04;
  3709. TGATools._ORIGIN_BL = 0x00;
  3710. TGATools._ORIGIN_BR = 0x01;
  3711. TGATools._ORIGIN_UL = 0x02;
  3712. TGATools._ORIGIN_UR = 0x03;
  3713. return TGATools;
  3714. })();
  3715. Internals.TGATools = TGATools;
  3716. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3717. })(BABYLON || (BABYLON = {}));
  3718. var BABYLON;
  3719. (function (BABYLON) {
  3720. var SmartArray = (function () {
  3721. function SmartArray(capacity) {
  3722. this.length = 0;
  3723. this._duplicateId = 0;
  3724. this.data = new Array(capacity);
  3725. this._id = SmartArray._GlobalId++;
  3726. }
  3727. SmartArray.prototype.push = function (value) {
  3728. this.data[this.length++] = value;
  3729. if (this.length > this.data.length) {
  3730. this.data.length *= 2;
  3731. }
  3732. if (!value.__smartArrayFlags) {
  3733. value.__smartArrayFlags = {};
  3734. }
  3735. value.__smartArrayFlags[this._id] = this._duplicateId;
  3736. };
  3737. SmartArray.prototype.pushNoDuplicate = function (value) {
  3738. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3739. return;
  3740. }
  3741. this.push(value);
  3742. };
  3743. SmartArray.prototype.sort = function (compareFn) {
  3744. this.data.sort(compareFn);
  3745. };
  3746. SmartArray.prototype.reset = function () {
  3747. this.length = 0;
  3748. this._duplicateId++;
  3749. };
  3750. SmartArray.prototype.concat = function (array) {
  3751. if (array.length === 0) {
  3752. return;
  3753. }
  3754. if (this.length + array.length > this.data.length) {
  3755. this.data.length = (this.length + array.length) * 2;
  3756. }
  3757. for (var index = 0; index < array.length; index++) {
  3758. this.data[this.length++] = (array.data || array)[index];
  3759. }
  3760. };
  3761. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3762. if (array.length === 0) {
  3763. return;
  3764. }
  3765. if (this.length + array.length > this.data.length) {
  3766. this.data.length = (this.length + array.length) * 2;
  3767. }
  3768. for (var index = 0; index < array.length; index++) {
  3769. var item = (array.data || array)[index];
  3770. this.pushNoDuplicate(item);
  3771. }
  3772. };
  3773. SmartArray.prototype.indexOf = function (value) {
  3774. var position = this.data.indexOf(value);
  3775. if (position >= this.length) {
  3776. return -1;
  3777. }
  3778. return position;
  3779. };
  3780. // Statics
  3781. SmartArray._GlobalId = 0;
  3782. return SmartArray;
  3783. })();
  3784. BABYLON.SmartArray = SmartArray;
  3785. })(BABYLON || (BABYLON = {}));
  3786. var BABYLON;
  3787. (function (BABYLON) {
  3788. var SmartCollection = (function () {
  3789. function SmartCollection(capacity) {
  3790. if (capacity === void 0) { capacity = 10; }
  3791. this.count = 0;
  3792. this._initialCapacity = capacity;
  3793. this.items = {};
  3794. this._keys = new Array(this._initialCapacity);
  3795. }
  3796. SmartCollection.prototype.add = function (key, item) {
  3797. if (this.items[key] != undefined) {
  3798. return -1;
  3799. }
  3800. this.items[key] = item;
  3801. //literal keys are always strings, but we keep source type of key in _keys array
  3802. this._keys[this.count++] = key;
  3803. if (this.count > this._keys.length) {
  3804. this._keys.length *= 2;
  3805. }
  3806. return this.count;
  3807. };
  3808. SmartCollection.prototype.remove = function (key) {
  3809. if (this.items[key] == undefined) {
  3810. return -1;
  3811. }
  3812. return this.removeItemOfIndex(this.indexOf(key));
  3813. };
  3814. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3815. if (index < this.count && index > -1) {
  3816. delete this.items[this._keys[index]];
  3817. //here, shifting by hand is better optimised than .splice
  3818. while (index < this.count) {
  3819. this._keys[index] = this._keys[index + 1];
  3820. index++;
  3821. }
  3822. }
  3823. else {
  3824. return -1;
  3825. }
  3826. return --this.count;
  3827. };
  3828. SmartCollection.prototype.indexOf = function (key) {
  3829. for (var i = 0; i !== this.count; i++) {
  3830. if (this._keys[i] === key) {
  3831. return i;
  3832. }
  3833. }
  3834. return -1;
  3835. };
  3836. SmartCollection.prototype.item = function (key) {
  3837. return this.items[key];
  3838. };
  3839. SmartCollection.prototype.getAllKeys = function () {
  3840. if (this.count > 0) {
  3841. var keys = new Array(this.count);
  3842. for (var i = 0; i < this.count; i++) {
  3843. keys[i] = this._keys[i];
  3844. }
  3845. return keys;
  3846. }
  3847. else {
  3848. return undefined;
  3849. }
  3850. };
  3851. SmartCollection.prototype.getKeyByIndex = function (index) {
  3852. if (index < this.count && index > -1) {
  3853. return this._keys[index];
  3854. }
  3855. else {
  3856. return undefined;
  3857. }
  3858. };
  3859. SmartCollection.prototype.getItemByIndex = function (index) {
  3860. if (index < this.count && index > -1) {
  3861. return this.items[this._keys[index]];
  3862. }
  3863. else {
  3864. return undefined;
  3865. }
  3866. };
  3867. SmartCollection.prototype.empty = function () {
  3868. if (this.count > 0) {
  3869. this.count = 0;
  3870. this.items = {};
  3871. this._keys = new Array(this._initialCapacity);
  3872. }
  3873. };
  3874. SmartCollection.prototype.forEach = function (block) {
  3875. var key;
  3876. for (key in this.items) {
  3877. if (this.items.hasOwnProperty(key)) {
  3878. block(this.items[key]);
  3879. }
  3880. }
  3881. };
  3882. return SmartCollection;
  3883. })();
  3884. BABYLON.SmartCollection = SmartCollection;
  3885. })(BABYLON || (BABYLON = {}));
  3886. var BABYLON;
  3887. (function (BABYLON) {
  3888. // Screenshots
  3889. var screenshotCanvas;
  3890. var cloneValue = function (source, destinationObject) {
  3891. if (!source)
  3892. return null;
  3893. if (source instanceof BABYLON.Mesh) {
  3894. return null;
  3895. }
  3896. if (source instanceof BABYLON.SubMesh) {
  3897. return source.clone(destinationObject);
  3898. }
  3899. else if (source.clone) {
  3900. return source.clone();
  3901. }
  3902. return null;
  3903. };
  3904. var Tools = (function () {
  3905. function Tools() {
  3906. }
  3907. Tools.Instantiate = function (className) {
  3908. var arr = className.split(".");
  3909. var fn = (window || this);
  3910. for (var i = 0, len = arr.length; i < len; i++) {
  3911. fn = fn[arr[i]];
  3912. }
  3913. if (typeof fn !== "function") {
  3914. return null;
  3915. }
  3916. return fn;
  3917. };
  3918. Tools.GetConstructorName = function (obj) {
  3919. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3920. var cname = str.match(/function\s(\w*)/)[1];
  3921. var aliases = ["", "anonymous", "Anonymous"];
  3922. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3923. };
  3924. Tools.ToHex = function (i) {
  3925. var str = i.toString(16);
  3926. if (i <= 15) {
  3927. return ("0" + str).toUpperCase();
  3928. }
  3929. return str.toUpperCase();
  3930. };
  3931. Tools.SetImmediate = function (action) {
  3932. if (window.setImmediate) {
  3933. window.setImmediate(action);
  3934. }
  3935. else {
  3936. setTimeout(action, 1);
  3937. }
  3938. };
  3939. Tools.IsExponentOfTwo = function (value) {
  3940. var count = 1;
  3941. do {
  3942. count *= 2;
  3943. } while (count < value);
  3944. return count === value;
  3945. };
  3946. Tools.GetExponentOfTwo = function (value, max) {
  3947. var count = 1;
  3948. do {
  3949. count *= 2;
  3950. } while (count < value);
  3951. if (count > max)
  3952. count = max;
  3953. return count;
  3954. };
  3955. Tools.GetFilename = function (path) {
  3956. var index = path.lastIndexOf("/");
  3957. if (index < 0)
  3958. return path;
  3959. return path.substring(index + 1);
  3960. };
  3961. Tools.GetDOMTextContent = function (element) {
  3962. var result = "";
  3963. var child = element.firstChild;
  3964. while (child) {
  3965. if (child.nodeType === 3) {
  3966. result += child.textContent;
  3967. }
  3968. child = child.nextSibling;
  3969. }
  3970. return result;
  3971. };
  3972. Tools.ToDegrees = function (angle) {
  3973. return angle * 180 / Math.PI;
  3974. };
  3975. Tools.ToRadians = function (angle) {
  3976. return angle * Math.PI / 180;
  3977. };
  3978. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3979. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3980. var output = "";
  3981. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3982. var i = 0;
  3983. var bytes = new Uint8Array(buffer);
  3984. while (i < bytes.length) {
  3985. chr1 = bytes[i++];
  3986. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3987. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3988. enc1 = chr1 >> 2;
  3989. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3990. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3991. enc4 = chr3 & 63;
  3992. if (isNaN(chr2)) {
  3993. enc3 = enc4 = 64;
  3994. }
  3995. else if (isNaN(chr3)) {
  3996. enc4 = 64;
  3997. }
  3998. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3999. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4000. }
  4001. return "data:image/png;base64," + output;
  4002. };
  4003. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4004. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4005. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4006. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4007. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4008. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4009. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4010. }
  4011. return {
  4012. minimum: minimum,
  4013. maximum: maximum
  4014. };
  4015. };
  4016. Tools.ExtractMinAndMax = function (positions, start, count) {
  4017. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4018. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4019. for (var index = start; index < start + count; index++) {
  4020. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4021. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4022. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4023. }
  4024. return {
  4025. minimum: minimum,
  4026. maximum: maximum
  4027. };
  4028. };
  4029. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4030. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4031. return undefined;
  4032. return Array.isArray(obj) ? obj : [obj];
  4033. };
  4034. // Misc.
  4035. Tools.GetPointerPrefix = function () {
  4036. var eventPrefix = "pointer";
  4037. // Check if pointer events are supported
  4038. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4039. eventPrefix = "mouse";
  4040. }
  4041. return eventPrefix;
  4042. };
  4043. Tools.QueueNewFrame = function (func) {
  4044. if (window.requestAnimationFrame)
  4045. window.requestAnimationFrame(func);
  4046. else if (window.msRequestAnimationFrame)
  4047. window.msRequestAnimationFrame(func);
  4048. else if (window.webkitRequestAnimationFrame)
  4049. window.webkitRequestAnimationFrame(func);
  4050. else if (window.mozRequestAnimationFrame)
  4051. window.mozRequestAnimationFrame(func);
  4052. else if (window.oRequestAnimationFrame)
  4053. window.oRequestAnimationFrame(func);
  4054. else {
  4055. window.setTimeout(func, 16);
  4056. }
  4057. };
  4058. Tools.RequestFullscreen = function (element) {
  4059. if (element.requestFullscreen)
  4060. element.requestFullscreen();
  4061. else if (element.msRequestFullscreen)
  4062. element.msRequestFullscreen();
  4063. else if (element.webkitRequestFullscreen)
  4064. element.webkitRequestFullscreen();
  4065. else if (element.mozRequestFullScreen)
  4066. element.mozRequestFullScreen();
  4067. };
  4068. Tools.ExitFullscreen = function () {
  4069. if (document.exitFullscreen) {
  4070. document.exitFullscreen();
  4071. }
  4072. else if (document.mozCancelFullScreen) {
  4073. document.mozCancelFullScreen();
  4074. }
  4075. else if (document.webkitCancelFullScreen) {
  4076. document.webkitCancelFullScreen();
  4077. }
  4078. else if (document.msCancelFullScreen) {
  4079. document.msCancelFullScreen();
  4080. }
  4081. };
  4082. // External files
  4083. Tools.CleanUrl = function (url) {
  4084. url = url.replace(/#/mg, "%23");
  4085. return url;
  4086. };
  4087. Tools.LoadImage = function (url, onload, onerror, database) {
  4088. if (url instanceof ArrayBuffer) {
  4089. url = Tools.EncodeArrayBufferTobase64(url);
  4090. }
  4091. url = Tools.CleanUrl(url);
  4092. var img = new Image();
  4093. if (url.substr(0, 5) !== "data:") {
  4094. if (Tools.CorsBehavior) {
  4095. switch (typeof (Tools.CorsBehavior)) {
  4096. case "function":
  4097. var result = Tools.CorsBehavior(url);
  4098. if (result) {
  4099. img.crossOrigin = result;
  4100. }
  4101. break;
  4102. case "string":
  4103. default:
  4104. img.crossOrigin = Tools.CorsBehavior;
  4105. break;
  4106. }
  4107. }
  4108. }
  4109. img.onload = function () {
  4110. onload(img);
  4111. };
  4112. img.onerror = function (err) {
  4113. Tools.Error("Error while trying to load texture: " + url);
  4114. 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";
  4115. onload(img);
  4116. };
  4117. var noIndexedDB = function () {
  4118. img.src = url;
  4119. };
  4120. var loadFromIndexedDB = function () {
  4121. database.loadImageFromDB(url, img);
  4122. };
  4123. //ANY database to do!
  4124. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4125. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4126. }
  4127. else {
  4128. if (url.indexOf("file:") === -1) {
  4129. noIndexedDB();
  4130. }
  4131. else {
  4132. try {
  4133. var textureName = url.substring(5);
  4134. var blobURL;
  4135. try {
  4136. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4137. }
  4138. catch (ex) {
  4139. // Chrome doesn't support oneTimeOnly parameter
  4140. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4141. }
  4142. img.src = blobURL;
  4143. }
  4144. catch (e) {
  4145. img.src = null;
  4146. }
  4147. }
  4148. }
  4149. return img;
  4150. };
  4151. //ANY
  4152. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4153. url = Tools.CleanUrl(url);
  4154. var noIndexedDB = function () {
  4155. var request = new XMLHttpRequest();
  4156. var loadUrl = Tools.BaseUrl + url;
  4157. request.open('GET', loadUrl, true);
  4158. if (useArrayBuffer) {
  4159. request.responseType = "arraybuffer";
  4160. }
  4161. request.onprogress = progressCallBack;
  4162. request.onreadystatechange = function () {
  4163. if (request.readyState === 4) {
  4164. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4165. callback(!useArrayBuffer ? request.responseText : request.response);
  4166. }
  4167. else {
  4168. if (onError) {
  4169. onError();
  4170. }
  4171. else {
  4172. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4173. }
  4174. }
  4175. }
  4176. };
  4177. request.send(null);
  4178. };
  4179. var loadFromIndexedDB = function () {
  4180. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4181. };
  4182. if (url.indexOf("file:") !== -1) {
  4183. var fileName = url.substring(5);
  4184. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4185. }
  4186. else {
  4187. // Caching all files
  4188. if (database && database.enableSceneOffline) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. noIndexedDB();
  4193. }
  4194. }
  4195. };
  4196. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4197. var reader = new FileReader();
  4198. reader.onload = function (e) {
  4199. //target doesn't have result from ts 1.3
  4200. callback(e.target['result']);
  4201. };
  4202. reader.onprogress = progressCallback;
  4203. reader.readAsDataURL(fileToLoad);
  4204. };
  4205. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4206. var reader = new FileReader();
  4207. reader.onerror = function (e) {
  4208. Tools.Log("Error while reading file: " + fileToLoad.name);
  4209. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4210. };
  4211. reader.onload = function (e) {
  4212. //target doesn't have result from ts 1.3
  4213. callback(e.target['result']);
  4214. };
  4215. reader.onprogress = progressCallBack;
  4216. if (!useArrayBuffer) {
  4217. // Asynchronous read
  4218. reader.readAsText(fileToLoad);
  4219. }
  4220. else {
  4221. reader.readAsArrayBuffer(fileToLoad);
  4222. }
  4223. };
  4224. //returns a downloadable url to a file content.
  4225. Tools.FileAsURL = function (content) {
  4226. var fileBlob = new Blob([content]);
  4227. var url = window.URL || window.webkitURL;
  4228. var link = url.createObjectURL(fileBlob);
  4229. return link;
  4230. };
  4231. // Misc.
  4232. Tools.Clamp = function (value, min, max) {
  4233. if (min === void 0) { min = 0; }
  4234. if (max === void 0) { max = 1; }
  4235. return Math.min(max, Math.max(min, value));
  4236. };
  4237. // Returns -1 when value is a negative number and
  4238. // +1 when value is a positive number.
  4239. Tools.Sign = function (value) {
  4240. value = +value; // convert to a number
  4241. if (value === 0 || isNaN(value))
  4242. return value;
  4243. return value > 0 ? 1 : -1;
  4244. };
  4245. Tools.Format = function (value, decimals) {
  4246. if (decimals === void 0) { decimals = 2; }
  4247. return value.toFixed(decimals);
  4248. };
  4249. Tools.CheckExtends = function (v, min, max) {
  4250. if (v.x < min.x)
  4251. min.x = v.x;
  4252. if (v.y < min.y)
  4253. min.y = v.y;
  4254. if (v.z < min.z)
  4255. min.z = v.z;
  4256. if (v.x > max.x)
  4257. max.x = v.x;
  4258. if (v.y > max.y)
  4259. max.y = v.y;
  4260. if (v.z > max.z)
  4261. max.z = v.z;
  4262. };
  4263. Tools.WithinEpsilon = function (a, b, epsilon) {
  4264. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4265. var num = a - b;
  4266. return -epsilon <= num && num <= epsilon;
  4267. };
  4268. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4269. for (var prop in source) {
  4270. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4271. continue;
  4272. }
  4273. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4274. continue;
  4275. }
  4276. var sourceValue = source[prop];
  4277. var typeOfSourceValue = typeof sourceValue;
  4278. if (typeOfSourceValue === "function") {
  4279. continue;
  4280. }
  4281. if (typeOfSourceValue === "object") {
  4282. if (sourceValue instanceof Array) {
  4283. destination[prop] = [];
  4284. if (sourceValue.length > 0) {
  4285. if (typeof sourceValue[0] == "object") {
  4286. for (var index = 0; index < sourceValue.length; index++) {
  4287. var clonedValue = cloneValue(sourceValue[index], destination);
  4288. if (destination[prop].indexOf(clonedValue) === -1) {
  4289. destination[prop].push(clonedValue);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = sourceValue.slice(0);
  4295. }
  4296. }
  4297. }
  4298. else {
  4299. destination[prop] = cloneValue(sourceValue, destination);
  4300. }
  4301. }
  4302. else {
  4303. destination[prop] = sourceValue;
  4304. }
  4305. }
  4306. };
  4307. Tools.IsEmpty = function (obj) {
  4308. for (var i in obj) {
  4309. return false;
  4310. }
  4311. return true;
  4312. };
  4313. Tools.RegisterTopRootEvents = function (events) {
  4314. for (var index = 0; index < events.length; index++) {
  4315. var event = events[index];
  4316. window.addEventListener(event.name, event.handler, false);
  4317. try {
  4318. if (window.parent) {
  4319. window.parent.addEventListener(event.name, event.handler, false);
  4320. }
  4321. }
  4322. catch (e) {
  4323. }
  4324. }
  4325. };
  4326. Tools.UnregisterTopRootEvents = function (events) {
  4327. for (var index = 0; index < events.length; index++) {
  4328. var event = events[index];
  4329. window.removeEventListener(event.name, event.handler);
  4330. try {
  4331. if (window.parent) {
  4332. window.parent.removeEventListener(event.name, event.handler);
  4333. }
  4334. }
  4335. catch (e) {
  4336. }
  4337. }
  4338. };
  4339. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4340. // Read the contents of the framebuffer
  4341. var numberOfChannelsByLine = width * 4;
  4342. var halfHeight = height / 2;
  4343. //Reading datas from WebGL
  4344. var data = engine.readPixels(0, 0, width, height);
  4345. //To flip image on Y axis.
  4346. for (var i = 0; i < halfHeight; i++) {
  4347. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4348. var currentCell = j + i * numberOfChannelsByLine;
  4349. var targetLine = height - i - 1;
  4350. var targetCell = j + targetLine * numberOfChannelsByLine;
  4351. var temp = data[currentCell];
  4352. data[currentCell] = data[targetCell];
  4353. data[targetCell] = temp;
  4354. }
  4355. }
  4356. // Create a 2D canvas to store the result
  4357. if (!screenshotCanvas) {
  4358. screenshotCanvas = document.createElement('canvas');
  4359. }
  4360. screenshotCanvas.width = width;
  4361. screenshotCanvas.height = height;
  4362. var context = screenshotCanvas.getContext('2d');
  4363. // Copy the pixels to a 2D canvas
  4364. var imageData = context.createImageData(width, height);
  4365. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4366. var castData = imageData.data;
  4367. castData.set(data);
  4368. context.putImageData(imageData, 0, 0);
  4369. var base64Image = screenshotCanvas.toDataURL();
  4370. if (successCallback) {
  4371. successCallback(base64Image);
  4372. }
  4373. else {
  4374. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4375. if (("download" in document.createElement("a"))) {
  4376. var a = window.document.createElement("a");
  4377. a.href = base64Image;
  4378. var date = new Date();
  4379. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4380. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4381. window.document.body.appendChild(a);
  4382. a.addEventListener("click", function () {
  4383. a.parentElement.removeChild(a);
  4384. });
  4385. a.click();
  4386. }
  4387. else {
  4388. var newWindow = window.open("");
  4389. var img = newWindow.document.createElement("img");
  4390. img.src = base64Image;
  4391. newWindow.document.body.appendChild(img);
  4392. }
  4393. }
  4394. };
  4395. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4396. var width;
  4397. var height;
  4398. //If a precision value is specified
  4399. if (size.precision) {
  4400. width = Math.round(engine.getRenderWidth() * size.precision);
  4401. height = Math.round(width / engine.getAspectRatio(camera));
  4402. size = { width: width, height: height };
  4403. }
  4404. else if (size.width && size.height) {
  4405. width = size.width;
  4406. height = size.height;
  4407. }
  4408. else if (size.width && !size.height) {
  4409. width = size.width;
  4410. height = Math.round(width / engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (size.height && !size.width) {
  4414. height = size.height;
  4415. width = Math.round(height * engine.getAspectRatio(camera));
  4416. size = { width: width, height: height };
  4417. }
  4418. else if (!isNaN(size)) {
  4419. height = size;
  4420. width = size;
  4421. }
  4422. else {
  4423. Tools.Error("Invalid 'size' parameter !");
  4424. return;
  4425. }
  4426. var scene = camera.getScene();
  4427. var previousCamera = null;
  4428. if (scene.activeCamera !== camera) {
  4429. previousCamera = scene.activeCamera;
  4430. scene.activeCamera = camera;
  4431. }
  4432. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4433. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4434. texture.renderList = scene.meshes;
  4435. texture.onAfterRender = function () {
  4436. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4437. };
  4438. scene.incrementRenderId();
  4439. texture.render(true);
  4440. texture.dispose();
  4441. if (previousCamera) {
  4442. scene.activeCamera = previousCamera;
  4443. }
  4444. camera.getProjectionMatrix(true); // Force cache refresh;
  4445. };
  4446. // XHR response validator for local file scenario
  4447. Tools.ValidateXHRData = function (xhr, dataType) {
  4448. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4449. if (dataType === void 0) { dataType = 7; }
  4450. try {
  4451. if (dataType & 1) {
  4452. if (xhr.responseText && xhr.responseText.length > 0) {
  4453. return true;
  4454. }
  4455. else if (dataType === 1) {
  4456. return false;
  4457. }
  4458. }
  4459. if (dataType & 2) {
  4460. // Check header width and height since there is no "TGA" magic number
  4461. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4462. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4463. return true;
  4464. }
  4465. else if (dataType === 2) {
  4466. return false;
  4467. }
  4468. }
  4469. if (dataType & 4) {
  4470. // Check for the "DDS" magic number
  4471. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4472. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4473. return true;
  4474. }
  4475. else {
  4476. return false;
  4477. }
  4478. }
  4479. }
  4480. catch (e) {
  4481. }
  4482. return false;
  4483. };
  4484. Object.defineProperty(Tools, "NoneLogLevel", {
  4485. get: function () {
  4486. return Tools._NoneLogLevel;
  4487. },
  4488. enumerable: true,
  4489. configurable: true
  4490. });
  4491. Object.defineProperty(Tools, "MessageLogLevel", {
  4492. get: function () {
  4493. return Tools._MessageLogLevel;
  4494. },
  4495. enumerable: true,
  4496. configurable: true
  4497. });
  4498. Object.defineProperty(Tools, "WarningLogLevel", {
  4499. get: function () {
  4500. return Tools._WarningLogLevel;
  4501. },
  4502. enumerable: true,
  4503. configurable: true
  4504. });
  4505. Object.defineProperty(Tools, "ErrorLogLevel", {
  4506. get: function () {
  4507. return Tools._ErrorLogLevel;
  4508. },
  4509. enumerable: true,
  4510. configurable: true
  4511. });
  4512. Object.defineProperty(Tools, "AllLogLevel", {
  4513. get: function () {
  4514. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4515. },
  4516. enumerable: true,
  4517. configurable: true
  4518. });
  4519. Tools._AddLogEntry = function (entry) {
  4520. Tools._LogCache = entry + Tools._LogCache;
  4521. if (Tools.OnNewCacheEntry) {
  4522. Tools.OnNewCacheEntry(entry);
  4523. }
  4524. };
  4525. Tools._FormatMessage = function (message) {
  4526. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4527. var date = new Date();
  4528. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4529. };
  4530. Tools._LogDisabled = function (message) {
  4531. // nothing to do
  4532. };
  4533. Tools._LogEnabled = function (message) {
  4534. var formattedMessage = Tools._FormatMessage(message);
  4535. console.log("BJS - " + formattedMessage);
  4536. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4537. Tools._AddLogEntry(entry);
  4538. };
  4539. Tools._WarnDisabled = function (message) {
  4540. // nothing to do
  4541. };
  4542. Tools._WarnEnabled = function (message) {
  4543. var formattedMessage = Tools._FormatMessage(message);
  4544. console.warn("BJS - " + formattedMessage);
  4545. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4546. Tools._AddLogEntry(entry);
  4547. };
  4548. Tools._ErrorDisabled = function (message) {
  4549. // nothing to do
  4550. };
  4551. Tools._ErrorEnabled = function (message) {
  4552. Tools.errorsCount++;
  4553. var formattedMessage = Tools._FormatMessage(message);
  4554. console.error("BJS - " + formattedMessage);
  4555. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4556. Tools._AddLogEntry(entry);
  4557. };
  4558. Object.defineProperty(Tools, "LogCache", {
  4559. get: function () {
  4560. return Tools._LogCache;
  4561. },
  4562. enumerable: true,
  4563. configurable: true
  4564. });
  4565. Tools.ClearLogCache = function () {
  4566. Tools._LogCache = "";
  4567. Tools.errorsCount = 0;
  4568. };
  4569. Object.defineProperty(Tools, "LogLevels", {
  4570. set: function (level) {
  4571. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4572. Tools.Log = Tools._LogEnabled;
  4573. }
  4574. else {
  4575. Tools.Log = Tools._LogDisabled;
  4576. }
  4577. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4578. Tools.Warn = Tools._WarnEnabled;
  4579. }
  4580. else {
  4581. Tools.Warn = Tools._WarnDisabled;
  4582. }
  4583. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4584. Tools.Error = Tools._ErrorEnabled;
  4585. }
  4586. else {
  4587. Tools.Error = Tools._ErrorDisabled;
  4588. }
  4589. },
  4590. enumerable: true,
  4591. configurable: true
  4592. });
  4593. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4594. get: function () {
  4595. return Tools._PerformanceNoneLogLevel;
  4596. },
  4597. enumerable: true,
  4598. configurable: true
  4599. });
  4600. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4601. get: function () {
  4602. return Tools._PerformanceUserMarkLogLevel;
  4603. },
  4604. enumerable: true,
  4605. configurable: true
  4606. });
  4607. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4608. get: function () {
  4609. return Tools._PerformanceConsoleLogLevel;
  4610. },
  4611. enumerable: true,
  4612. configurable: true
  4613. });
  4614. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4615. set: function (level) {
  4616. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4617. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4618. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4619. return;
  4620. }
  4621. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4622. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4623. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4624. return;
  4625. }
  4626. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4627. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4628. },
  4629. enumerable: true,
  4630. configurable: true
  4631. });
  4632. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4633. };
  4634. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4635. };
  4636. Tools._StartUserMark = function (counterName, condition) {
  4637. if (condition === void 0) { condition = true; }
  4638. if (!condition || !Tools._performance.mark) {
  4639. return;
  4640. }
  4641. Tools._performance.mark(counterName + "-Begin");
  4642. };
  4643. Tools._EndUserMark = function (counterName, condition) {
  4644. if (condition === void 0) { condition = true; }
  4645. if (!condition || !Tools._performance.mark) {
  4646. return;
  4647. }
  4648. Tools._performance.mark(counterName + "-End");
  4649. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4650. };
  4651. Tools._StartPerformanceConsole = function (counterName, condition) {
  4652. if (condition === void 0) { condition = true; }
  4653. if (!condition) {
  4654. return;
  4655. }
  4656. Tools._StartUserMark(counterName, condition);
  4657. if (console.time) {
  4658. console.time(counterName);
  4659. }
  4660. };
  4661. Tools._EndPerformanceConsole = function (counterName, condition) {
  4662. if (condition === void 0) { condition = true; }
  4663. if (!condition) {
  4664. return;
  4665. }
  4666. Tools._EndUserMark(counterName, condition);
  4667. if (console.time) {
  4668. console.timeEnd(counterName);
  4669. }
  4670. };
  4671. Object.defineProperty(Tools, "Now", {
  4672. get: function () {
  4673. if (window.performance && window.performance.now) {
  4674. return window.performance.now();
  4675. }
  4676. return new Date().getTime();
  4677. },
  4678. enumerable: true,
  4679. configurable: true
  4680. });
  4681. Tools.BaseUrl = "";
  4682. Tools.CorsBehavior = "anonymous";
  4683. // Logs
  4684. Tools._NoneLogLevel = 0;
  4685. Tools._MessageLogLevel = 1;
  4686. Tools._WarningLogLevel = 2;
  4687. Tools._ErrorLogLevel = 4;
  4688. Tools._LogCache = "";
  4689. Tools.errorsCount = 0;
  4690. Tools.Log = Tools._LogEnabled;
  4691. Tools.Warn = Tools._WarnEnabled;
  4692. Tools.Error = Tools._ErrorEnabled;
  4693. // Performances
  4694. Tools._PerformanceNoneLogLevel = 0;
  4695. Tools._PerformanceUserMarkLogLevel = 1;
  4696. Tools._PerformanceConsoleLogLevel = 2;
  4697. Tools._performance = window.performance;
  4698. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4699. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4700. return Tools;
  4701. })();
  4702. BABYLON.Tools = Tools;
  4703. /**
  4704. * An implementation of a loop for asynchronous functions.
  4705. */
  4706. var AsyncLoop = (function () {
  4707. /**
  4708. * Constroctor.
  4709. * @param iterations the number of iterations.
  4710. * @param _fn the function to run each iteration
  4711. * @param _successCallback the callback that will be called upon succesful execution
  4712. * @param offset starting offset.
  4713. */
  4714. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4715. if (offset === void 0) { offset = 0; }
  4716. this.iterations = iterations;
  4717. this._fn = _fn;
  4718. this._successCallback = _successCallback;
  4719. this.index = offset - 1;
  4720. this._done = false;
  4721. }
  4722. /**
  4723. * Execute the next iteration. Must be called after the last iteration was finished.
  4724. */
  4725. AsyncLoop.prototype.executeNext = function () {
  4726. if (!this._done) {
  4727. if (this.index + 1 < this.iterations) {
  4728. ++this.index;
  4729. this._fn(this);
  4730. }
  4731. else {
  4732. this.breakLoop();
  4733. }
  4734. }
  4735. };
  4736. /**
  4737. * Break the loop and run the success callback.
  4738. */
  4739. AsyncLoop.prototype.breakLoop = function () {
  4740. this._done = true;
  4741. this._successCallback();
  4742. };
  4743. /**
  4744. * Helper function
  4745. */
  4746. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4747. if (offset === void 0) { offset = 0; }
  4748. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4749. loop.executeNext();
  4750. return loop;
  4751. };
  4752. /**
  4753. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4754. * @param iterations total number of iterations
  4755. * @param syncedIterations number of synchronous iterations in each async iteration.
  4756. * @param fn the function to call each iteration.
  4757. * @param callback a success call back that will be called when iterating stops.
  4758. * @param breakFunction a break condition (optional)
  4759. * @param timeout timeout settings for the setTimeout function. default - 0.
  4760. * @constructor
  4761. */
  4762. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4763. if (timeout === void 0) { timeout = 0; }
  4764. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4765. if (breakFunction && breakFunction())
  4766. loop.breakLoop();
  4767. else {
  4768. setTimeout(function () {
  4769. for (var i = 0; i < syncedIterations; ++i) {
  4770. var iteration = (loop.index * syncedIterations) + i;
  4771. if (iteration >= iterations)
  4772. break;
  4773. fn(iteration);
  4774. if (breakFunction && breakFunction()) {
  4775. loop.breakLoop();
  4776. break;
  4777. }
  4778. }
  4779. loop.executeNext();
  4780. }, timeout);
  4781. }
  4782. }, callback);
  4783. };
  4784. return AsyncLoop;
  4785. })();
  4786. BABYLON.AsyncLoop = AsyncLoop;
  4787. })(BABYLON || (BABYLON = {}));
  4788. var BABYLON;
  4789. (function (BABYLON) {
  4790. var _DepthCullingState = (function () {
  4791. function _DepthCullingState() {
  4792. this._isDepthTestDirty = false;
  4793. this._isDepthMaskDirty = false;
  4794. this._isDepthFuncDirty = false;
  4795. this._isCullFaceDirty = false;
  4796. this._isCullDirty = false;
  4797. this._isZOffsetDirty = false;
  4798. }
  4799. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4800. get: function () {
  4801. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4802. },
  4803. enumerable: true,
  4804. configurable: true
  4805. });
  4806. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4807. get: function () {
  4808. return this._zOffset;
  4809. },
  4810. set: function (value) {
  4811. if (this._zOffset === value) {
  4812. return;
  4813. }
  4814. this._zOffset = value;
  4815. this._isZOffsetDirty = true;
  4816. },
  4817. enumerable: true,
  4818. configurable: true
  4819. });
  4820. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4821. get: function () {
  4822. return this._cullFace;
  4823. },
  4824. set: function (value) {
  4825. if (this._cullFace === value) {
  4826. return;
  4827. }
  4828. this._cullFace = value;
  4829. this._isCullFaceDirty = true;
  4830. },
  4831. enumerable: true,
  4832. configurable: true
  4833. });
  4834. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4835. get: function () {
  4836. return this._cull;
  4837. },
  4838. set: function (value) {
  4839. if (this._cull === value) {
  4840. return;
  4841. }
  4842. this._cull = value;
  4843. this._isCullDirty = true;
  4844. },
  4845. enumerable: true,
  4846. configurable: true
  4847. });
  4848. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4849. get: function () {
  4850. return this._depthFunc;
  4851. },
  4852. set: function (value) {
  4853. if (this._depthFunc === value) {
  4854. return;
  4855. }
  4856. this._depthFunc = value;
  4857. this._isDepthFuncDirty = true;
  4858. },
  4859. enumerable: true,
  4860. configurable: true
  4861. });
  4862. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4863. get: function () {
  4864. return this._depthMask;
  4865. },
  4866. set: function (value) {
  4867. if (this._depthMask === value) {
  4868. return;
  4869. }
  4870. this._depthMask = value;
  4871. this._isDepthMaskDirty = true;
  4872. },
  4873. enumerable: true,
  4874. configurable: true
  4875. });
  4876. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4877. get: function () {
  4878. return this._depthTest;
  4879. },
  4880. set: function (value) {
  4881. if (this._depthTest === value) {
  4882. return;
  4883. }
  4884. this._depthTest = value;
  4885. this._isDepthTestDirty = true;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. _DepthCullingState.prototype.reset = function () {
  4891. this._depthMask = true;
  4892. this._depthTest = true;
  4893. this._depthFunc = null;
  4894. this._cull = null;
  4895. this._cullFace = null;
  4896. this._zOffset = 0;
  4897. this._isDepthTestDirty = true;
  4898. this._isDepthMaskDirty = true;
  4899. this._isDepthFuncDirty = false;
  4900. this._isCullFaceDirty = false;
  4901. this._isCullDirty = false;
  4902. this._isZOffsetDirty = false;
  4903. };
  4904. _DepthCullingState.prototype.apply = function (gl) {
  4905. if (!this.isDirty) {
  4906. return;
  4907. }
  4908. // Cull
  4909. if (this._isCullDirty) {
  4910. if (this.cull) {
  4911. gl.enable(gl.CULL_FACE);
  4912. }
  4913. else {
  4914. gl.disable(gl.CULL_FACE);
  4915. }
  4916. this._isCullDirty = false;
  4917. }
  4918. // Cull face
  4919. if (this._isCullFaceDirty) {
  4920. gl.cullFace(this.cullFace);
  4921. this._isCullFaceDirty = false;
  4922. }
  4923. // Depth mask
  4924. if (this._isDepthMaskDirty) {
  4925. gl.depthMask(this.depthMask);
  4926. this._isDepthMaskDirty = false;
  4927. }
  4928. // Depth test
  4929. if (this._isDepthTestDirty) {
  4930. if (this.depthTest) {
  4931. gl.enable(gl.DEPTH_TEST);
  4932. }
  4933. else {
  4934. gl.disable(gl.DEPTH_TEST);
  4935. }
  4936. this._isDepthTestDirty = false;
  4937. }
  4938. // Depth func
  4939. if (this._isDepthFuncDirty) {
  4940. gl.depthFunc(this.depthFunc);
  4941. this._isDepthFuncDirty = false;
  4942. }
  4943. // zOffset
  4944. if (this._isZOffsetDirty) {
  4945. if (this.zOffset) {
  4946. gl.enable(gl.POLYGON_OFFSET_FILL);
  4947. gl.polygonOffset(this.zOffset, 0);
  4948. }
  4949. else {
  4950. gl.disable(gl.POLYGON_OFFSET_FILL);
  4951. }
  4952. this._isZOffsetDirty = false;
  4953. }
  4954. };
  4955. return _DepthCullingState;
  4956. })();
  4957. BABYLON._DepthCullingState = _DepthCullingState;
  4958. var _AlphaState = (function () {
  4959. function _AlphaState() {
  4960. this._isAlphaBlendDirty = false;
  4961. this._isBlendFunctionParametersDirty = false;
  4962. this._alphaBlend = false;
  4963. this._blendFunctionParameters = new Array(4);
  4964. }
  4965. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4966. get: function () {
  4967. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4968. },
  4969. enumerable: true,
  4970. configurable: true
  4971. });
  4972. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4973. get: function () {
  4974. return this._alphaBlend;
  4975. },
  4976. set: function (value) {
  4977. if (this._alphaBlend === value) {
  4978. return;
  4979. }
  4980. this._alphaBlend = value;
  4981. this._isAlphaBlendDirty = true;
  4982. },
  4983. enumerable: true,
  4984. configurable: true
  4985. });
  4986. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4987. if (this._blendFunctionParameters[0] === value0 &&
  4988. this._blendFunctionParameters[1] === value1 &&
  4989. this._blendFunctionParameters[2] === value2 &&
  4990. this._blendFunctionParameters[3] === value3) {
  4991. return;
  4992. }
  4993. this._blendFunctionParameters[0] = value0;
  4994. this._blendFunctionParameters[1] = value1;
  4995. this._blendFunctionParameters[2] = value2;
  4996. this._blendFunctionParameters[3] = value3;
  4997. this._isBlendFunctionParametersDirty = true;
  4998. };
  4999. _AlphaState.prototype.reset = function () {
  5000. this._alphaBlend = false;
  5001. this._blendFunctionParameters[0] = null;
  5002. this._blendFunctionParameters[1] = null;
  5003. this._blendFunctionParameters[2] = null;
  5004. this._blendFunctionParameters[3] = null;
  5005. this._isAlphaBlendDirty = true;
  5006. this._isBlendFunctionParametersDirty = false;
  5007. };
  5008. _AlphaState.prototype.apply = function (gl) {
  5009. if (!this.isDirty) {
  5010. return;
  5011. }
  5012. // Alpha blend
  5013. if (this._isAlphaBlendDirty) {
  5014. if (this._alphaBlend) {
  5015. gl.enable(gl.BLEND);
  5016. }
  5017. else {
  5018. gl.disable(gl.BLEND);
  5019. }
  5020. this._isAlphaBlendDirty = false;
  5021. }
  5022. // Alpha function
  5023. if (this._isBlendFunctionParametersDirty) {
  5024. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5025. this._isBlendFunctionParametersDirty = false;
  5026. }
  5027. };
  5028. return _AlphaState;
  5029. })();
  5030. BABYLON._AlphaState = _AlphaState;
  5031. var compileShader = function (gl, source, type, defines) {
  5032. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5033. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5034. gl.compileShader(shader);
  5035. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5036. throw new Error(gl.getShaderInfoLog(shader));
  5037. }
  5038. return shader;
  5039. };
  5040. var getWebGLTextureType = function (gl, type) {
  5041. var textureType = gl.UNSIGNED_BYTE;
  5042. if (type === Engine.TEXTURETYPE_FLOAT)
  5043. textureType = gl.FLOAT;
  5044. return textureType;
  5045. };
  5046. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5047. var magFilter = gl.NEAREST;
  5048. var minFilter = gl.NEAREST;
  5049. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5050. magFilter = gl.LINEAR;
  5051. if (generateMipMaps) {
  5052. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5053. }
  5054. else {
  5055. minFilter = gl.LINEAR;
  5056. }
  5057. }
  5058. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5059. magFilter = gl.LINEAR;
  5060. if (generateMipMaps) {
  5061. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5062. }
  5063. else {
  5064. minFilter = gl.LINEAR;
  5065. }
  5066. }
  5067. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5068. magFilter = gl.NEAREST;
  5069. if (generateMipMaps) {
  5070. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5071. }
  5072. else {
  5073. minFilter = gl.NEAREST;
  5074. }
  5075. }
  5076. return {
  5077. min: minFilter,
  5078. mag: magFilter
  5079. };
  5080. };
  5081. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5082. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5083. var engine = scene.getEngine();
  5084. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5085. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5086. gl.bindTexture(gl.TEXTURE_2D, texture);
  5087. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5088. texture._baseWidth = width;
  5089. texture._baseHeight = height;
  5090. texture._width = potWidth;
  5091. texture._height = potHeight;
  5092. texture.isReady = true;
  5093. processFunction(potWidth, potHeight);
  5094. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5097. if (!noMipmap && !isCompressed) {
  5098. gl.generateMipmap(gl.TEXTURE_2D);
  5099. }
  5100. gl.bindTexture(gl.TEXTURE_2D, null);
  5101. engine.resetTextureCache();
  5102. scene._removePendingData(texture);
  5103. };
  5104. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5105. var img;
  5106. var onload = function () {
  5107. loadedImages[index] = img;
  5108. loadedImages._internalCount++;
  5109. scene._removePendingData(img);
  5110. if (loadedImages._internalCount === 6) {
  5111. onfinish(loadedImages);
  5112. }
  5113. };
  5114. var onerror = function () {
  5115. scene._removePendingData(img);
  5116. };
  5117. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5118. scene._addPendingData(img);
  5119. };
  5120. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5121. var loadedImages = [];
  5122. loadedImages._internalCount = 0;
  5123. for (var index = 0; index < 6; index++) {
  5124. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5125. }
  5126. };
  5127. var EngineCapabilities = (function () {
  5128. function EngineCapabilities() {
  5129. }
  5130. return EngineCapabilities;
  5131. })();
  5132. BABYLON.EngineCapabilities = EngineCapabilities;
  5133. /**
  5134. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5135. */
  5136. var Engine = (function () {
  5137. /**
  5138. * @constructor
  5139. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5140. * @param {boolean} [antialias] - enable antialias
  5141. * @param options - further options to be sent to the getContext function
  5142. */
  5143. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5144. var _this = this;
  5145. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5146. // Public members
  5147. this.isFullscreen = false;
  5148. this.isPointerLock = false;
  5149. this.cullBackFaces = true;
  5150. this.renderEvenInBackground = true;
  5151. // To enable/disable IDB support and avoid XHR on .manifest
  5152. this.enableOfflineSupport = true;
  5153. this.scenes = new Array();
  5154. this._windowIsBackground = false;
  5155. this._drawCalls = 0;
  5156. this._renderingQueueLaunched = false;
  5157. this._activeRenderLoops = [];
  5158. // FPS
  5159. this.fpsRange = 60;
  5160. this.previousFramesDuration = [];
  5161. this.fps = 60;
  5162. this.deltaTime = 0;
  5163. // States
  5164. this._depthCullingState = new _DepthCullingState();
  5165. this._alphaState = new _AlphaState();
  5166. this._alphaMode = Engine.ALPHA_DISABLE;
  5167. // Cache
  5168. this._loadedTexturesCache = new Array();
  5169. this._maxTextureChannels = 16;
  5170. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5171. this._compiledEffects = {};
  5172. this._uintIndicesCurrentlySet = false;
  5173. this._renderingCanvas = canvas;
  5174. options = options || {};
  5175. options.antialias = antialias;
  5176. if (options.preserveDrawingBuffer === undefined) {
  5177. options.preserveDrawingBuffer = false;
  5178. }
  5179. // GL
  5180. try {
  5181. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5182. }
  5183. catch (e) {
  5184. throw new Error("WebGL not supported");
  5185. }
  5186. if (!this._gl) {
  5187. throw new Error("WebGL not supported");
  5188. }
  5189. this._onBlur = function () {
  5190. _this._windowIsBackground = true;
  5191. };
  5192. this._onFocus = function () {
  5193. _this._windowIsBackground = false;
  5194. };
  5195. window.addEventListener("blur", this._onBlur);
  5196. window.addEventListener("focus", this._onFocus);
  5197. // Viewport
  5198. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5199. this.resize();
  5200. // Caps
  5201. this._caps = new EngineCapabilities();
  5202. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5203. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5204. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5205. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5206. // Infos
  5207. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5208. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5209. if (rendererInfo != null) {
  5210. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5211. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5212. }
  5213. if (!this._glVendor) {
  5214. this._glVendor = "Unknown vendor";
  5215. }
  5216. if (!this._glRenderer) {
  5217. this._glRenderer = "Unknown renderer";
  5218. }
  5219. // Extensions
  5220. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5221. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5222. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5223. 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');
  5224. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5225. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5226. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5227. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5228. this._caps.highPrecisionShaderSupported = true;
  5229. if (this._gl.getShaderPrecisionFormat) {
  5230. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5231. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5232. }
  5233. // Depth buffer
  5234. this.setDepthBuffer(true);
  5235. this.setDepthFunctionToLessOrEqual();
  5236. this.setDepthWrite(true);
  5237. // Fullscreen
  5238. this._onFullscreenChange = function () {
  5239. if (document.fullscreen !== undefined) {
  5240. _this.isFullscreen = document.fullscreen;
  5241. }
  5242. else if (document.mozFullScreen !== undefined) {
  5243. _this.isFullscreen = document.mozFullScreen;
  5244. }
  5245. else if (document.webkitIsFullScreen !== undefined) {
  5246. _this.isFullscreen = document.webkitIsFullScreen;
  5247. }
  5248. else if (document.msIsFullScreen !== undefined) {
  5249. _this.isFullscreen = document.msIsFullScreen;
  5250. }
  5251. // Pointer lock
  5252. if (_this.isFullscreen && _this._pointerLockRequested) {
  5253. canvas.requestPointerLock = canvas.requestPointerLock ||
  5254. canvas.msRequestPointerLock ||
  5255. canvas.mozRequestPointerLock ||
  5256. canvas.webkitRequestPointerLock;
  5257. if (canvas.requestPointerLock) {
  5258. canvas.requestPointerLock();
  5259. }
  5260. }
  5261. };
  5262. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5263. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5264. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5265. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5266. // Pointer lock
  5267. this._onPointerLockChange = function () {
  5268. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5269. document.webkitPointerLockElement === canvas ||
  5270. document.msPointerLockElement === canvas ||
  5271. document.pointerLockElement === canvas);
  5272. };
  5273. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5274. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5275. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5276. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5277. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5278. Engine.audioEngine = new BABYLON.AudioEngine();
  5279. }
  5280. //default loading screen
  5281. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5282. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5283. }
  5284. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5285. get: function () {
  5286. return Engine._ALPHA_DISABLE;
  5287. },
  5288. enumerable: true,
  5289. configurable: true
  5290. });
  5291. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5292. get: function () {
  5293. return Engine._ALPHA_ONEONE;
  5294. },
  5295. enumerable: true,
  5296. configurable: true
  5297. });
  5298. Object.defineProperty(Engine, "ALPHA_ADD", {
  5299. get: function () {
  5300. return Engine._ALPHA_ADD;
  5301. },
  5302. enumerable: true,
  5303. configurable: true
  5304. });
  5305. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5306. get: function () {
  5307. return Engine._ALPHA_COMBINE;
  5308. },
  5309. enumerable: true,
  5310. configurable: true
  5311. });
  5312. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5313. get: function () {
  5314. return Engine._ALPHA_SUBTRACT;
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5320. get: function () {
  5321. return Engine._ALPHA_MULTIPLY;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5327. get: function () {
  5328. return Engine._ALPHA_MAXIMIZED;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5334. get: function () {
  5335. return Engine._DELAYLOADSTATE_NONE;
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5341. get: function () {
  5342. return Engine._DELAYLOADSTATE_LOADED;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5348. get: function () {
  5349. return Engine._DELAYLOADSTATE_LOADING;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5355. get: function () {
  5356. return Engine._DELAYLOADSTATE_NOTLOADED;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5362. get: function () {
  5363. return Engine._TEXTUREFORMAT_ALPHA;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5369. get: function () {
  5370. return Engine._TEXTUREFORMAT_LUMINANCE;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5376. get: function () {
  5377. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5383. get: function () {
  5384. return Engine._TEXTUREFORMAT_RGB;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5390. get: function () {
  5391. return Engine._TEXTUREFORMAT_RGBA;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5397. get: function () {
  5398. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5404. get: function () {
  5405. return Engine._TEXTURETYPE_FLOAT;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "Version", {
  5411. get: function () {
  5412. return "2.3.0-beta";
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Engine.prototype._prepareWorkingCanvas = function () {
  5418. if (this._workingCanvas) {
  5419. return;
  5420. }
  5421. this._workingCanvas = document.createElement("canvas");
  5422. this._workingContext = this._workingCanvas.getContext("2d");
  5423. };
  5424. Engine.prototype.resetTextureCache = function () {
  5425. for (var index = 0; index < this._maxTextureChannels; index++) {
  5426. this._activeTexturesCache[index] = null;
  5427. }
  5428. };
  5429. Engine.prototype.getGlInfo = function () {
  5430. return {
  5431. vendor: this._glVendor,
  5432. renderer: this._glRenderer,
  5433. version: this._glVersion
  5434. };
  5435. };
  5436. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5437. if (useScreen === void 0) { useScreen = false; }
  5438. var viewport = camera.viewport;
  5439. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5440. };
  5441. Engine.prototype.getRenderWidth = function (useScreen) {
  5442. if (useScreen === void 0) { useScreen = false; }
  5443. if (!useScreen && this._currentRenderTarget) {
  5444. return this._currentRenderTarget._width;
  5445. }
  5446. return this._renderingCanvas.width;
  5447. };
  5448. Engine.prototype.getRenderHeight = function (useScreen) {
  5449. if (useScreen === void 0) { useScreen = false; }
  5450. if (!useScreen && this._currentRenderTarget) {
  5451. return this._currentRenderTarget._height;
  5452. }
  5453. return this._renderingCanvas.height;
  5454. };
  5455. Engine.prototype.getRenderingCanvas = function () {
  5456. return this._renderingCanvas;
  5457. };
  5458. Engine.prototype.getRenderingCanvasClientRect = function () {
  5459. return this._renderingCanvas.getBoundingClientRect();
  5460. };
  5461. Engine.prototype.setHardwareScalingLevel = function (level) {
  5462. this._hardwareScalingLevel = level;
  5463. this.resize();
  5464. };
  5465. Engine.prototype.getHardwareScalingLevel = function () {
  5466. return this._hardwareScalingLevel;
  5467. };
  5468. Engine.prototype.getLoadedTexturesCache = function () {
  5469. return this._loadedTexturesCache;
  5470. };
  5471. Engine.prototype.getCaps = function () {
  5472. return this._caps;
  5473. };
  5474. Object.defineProperty(Engine.prototype, "drawCalls", {
  5475. get: function () {
  5476. return this._drawCalls;
  5477. },
  5478. enumerable: true,
  5479. configurable: true
  5480. });
  5481. // Methods
  5482. Engine.prototype.resetDrawCalls = function () {
  5483. this._drawCalls = 0;
  5484. };
  5485. Engine.prototype.setDepthFunctionToGreater = function () {
  5486. this._depthCullingState.depthFunc = this._gl.GREATER;
  5487. };
  5488. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5489. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5490. };
  5491. Engine.prototype.setDepthFunctionToLess = function () {
  5492. this._depthCullingState.depthFunc = this._gl.LESS;
  5493. };
  5494. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5495. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5496. };
  5497. /**
  5498. * stop executing a render loop function and remove it from the execution array
  5499. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5500. */
  5501. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5502. if (!renderFunction) {
  5503. this._activeRenderLoops = [];
  5504. return;
  5505. }
  5506. var index = this._activeRenderLoops.indexOf(renderFunction);
  5507. if (index >= 0) {
  5508. this._activeRenderLoops.splice(index, 1);
  5509. }
  5510. };
  5511. Engine.prototype._renderLoop = function () {
  5512. var shouldRender = true;
  5513. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5514. shouldRender = false;
  5515. }
  5516. if (shouldRender) {
  5517. // Start new frame
  5518. this.beginFrame();
  5519. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5520. var renderFunction = this._activeRenderLoops[index];
  5521. renderFunction();
  5522. }
  5523. // Present
  5524. this.endFrame();
  5525. }
  5526. if (this._activeRenderLoops.length > 0) {
  5527. // Register new frame
  5528. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5529. }
  5530. else {
  5531. this._renderingQueueLaunched = false;
  5532. }
  5533. };
  5534. /**
  5535. * Register and execute a render loop. The engine can have more than one render function.
  5536. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5537. * @example
  5538. * engine.runRenderLoop(function () {
  5539. * scene.render()
  5540. * })
  5541. */
  5542. Engine.prototype.runRenderLoop = function (renderFunction) {
  5543. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5544. return;
  5545. }
  5546. this._activeRenderLoops.push(renderFunction);
  5547. if (!this._renderingQueueLaunched) {
  5548. this._renderingQueueLaunched = true;
  5549. this._bindedRenderFunction = this._renderLoop.bind(this);
  5550. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5551. }
  5552. };
  5553. /**
  5554. * Toggle full screen mode.
  5555. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5556. */
  5557. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5558. if (this.isFullscreen) {
  5559. BABYLON.Tools.ExitFullscreen();
  5560. }
  5561. else {
  5562. this._pointerLockRequested = requestPointerLock;
  5563. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5564. }
  5565. };
  5566. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5567. this.applyStates();
  5568. if (backBuffer) {
  5569. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5570. }
  5571. if (depthStencil && this._depthCullingState.depthMask) {
  5572. this._gl.clearDepth(1.0);
  5573. }
  5574. var mode = 0;
  5575. if (backBuffer) {
  5576. mode |= this._gl.COLOR_BUFFER_BIT;
  5577. }
  5578. if (depthStencil && this._depthCullingState.depthMask) {
  5579. mode |= this._gl.DEPTH_BUFFER_BIT;
  5580. }
  5581. this._gl.clear(mode);
  5582. };
  5583. /**
  5584. * Set the WebGL's viewport
  5585. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5586. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5587. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5588. */
  5589. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5590. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5591. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5592. var x = viewport.x || 0;
  5593. var y = viewport.y || 0;
  5594. this._cachedViewport = viewport;
  5595. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5596. };
  5597. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5598. this._cachedViewport = null;
  5599. this._gl.viewport(x, y, width, height);
  5600. };
  5601. Engine.prototype.beginFrame = function () {
  5602. this._measureFps();
  5603. };
  5604. Engine.prototype.endFrame = function () {
  5605. //this.flushFramebuffer();
  5606. };
  5607. /**
  5608. * resize the view according to the canvas' size.
  5609. * @example
  5610. * window.addEventListener("resize", function () {
  5611. * engine.resize();
  5612. * });
  5613. */
  5614. Engine.prototype.resize = function () {
  5615. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5616. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5617. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5618. for (var index = 0; index < this.scenes.length; index++) {
  5619. var scene = this.scenes[index];
  5620. if (scene.debugLayer.isVisible()) {
  5621. scene.debugLayer._syncPositions();
  5622. }
  5623. }
  5624. };
  5625. /**
  5626. * force a specific size of the canvas
  5627. * @param {number} width - the new canvas' width
  5628. * @param {number} height - the new canvas' height
  5629. */
  5630. Engine.prototype.setSize = function (width, height) {
  5631. this._renderingCanvas.width = width;
  5632. this._renderingCanvas.height = height;
  5633. for (var index = 0; index < this.scenes.length; index++) {
  5634. var scene = this.scenes[index];
  5635. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5636. var cam = scene.cameras[camIndex];
  5637. cam._currentRenderId = 0;
  5638. }
  5639. }
  5640. };
  5641. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5642. this._currentRenderTarget = texture;
  5643. var gl = this._gl;
  5644. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5645. if (texture.isCube) {
  5646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5647. }
  5648. else {
  5649. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5650. }
  5651. this._gl.viewport(0, 0, texture._width, texture._height);
  5652. this.wipeCaches();
  5653. };
  5654. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5655. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5656. this._currentRenderTarget = null;
  5657. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5658. var gl = this._gl;
  5659. gl.bindTexture(gl.TEXTURE_2D, texture);
  5660. gl.generateMipmap(gl.TEXTURE_2D);
  5661. gl.bindTexture(gl.TEXTURE_2D, null);
  5662. }
  5663. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5664. };
  5665. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5666. if (texture.generateMipMaps) {
  5667. var gl = this._gl;
  5668. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5669. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5670. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5671. }
  5672. };
  5673. Engine.prototype.flushFramebuffer = function () {
  5674. this._gl.flush();
  5675. };
  5676. Engine.prototype.restoreDefaultFramebuffer = function () {
  5677. this._currentRenderTarget = null;
  5678. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5679. this.setViewport(this._cachedViewport);
  5680. this.wipeCaches();
  5681. };
  5682. // VBOs
  5683. Engine.prototype._resetVertexBufferBinding = function () {
  5684. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5685. this._cachedVertexBuffers = null;
  5686. };
  5687. Engine.prototype.createVertexBuffer = function (vertices) {
  5688. var vbo = this._gl.createBuffer();
  5689. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5690. if (vertices instanceof Float32Array) {
  5691. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5692. }
  5693. else {
  5694. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5695. }
  5696. this._resetVertexBufferBinding();
  5697. vbo.references = 1;
  5698. return vbo;
  5699. };
  5700. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5701. var vbo = this._gl.createBuffer();
  5702. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5703. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5704. this._resetVertexBufferBinding();
  5705. vbo.references = 1;
  5706. return vbo;
  5707. };
  5708. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5709. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5710. if (offset === undefined) {
  5711. offset = 0;
  5712. }
  5713. if (vertices instanceof Float32Array) {
  5714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5715. }
  5716. else {
  5717. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5718. }
  5719. this._resetVertexBufferBinding();
  5720. };
  5721. Engine.prototype._resetIndexBufferBinding = function () {
  5722. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5723. this._cachedIndexBuffer = null;
  5724. };
  5725. Engine.prototype.createIndexBuffer = function (indices) {
  5726. var vbo = this._gl.createBuffer();
  5727. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5728. // Check for 32 bits indices
  5729. var arrayBuffer;
  5730. var need32Bits = false;
  5731. if (this._caps.uintIndices) {
  5732. for (var index = 0; index < indices.length; index++) {
  5733. if (indices[index] > 65535) {
  5734. need32Bits = true;
  5735. break;
  5736. }
  5737. }
  5738. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5739. }
  5740. else {
  5741. arrayBuffer = new Uint16Array(indices);
  5742. }
  5743. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5744. this._resetIndexBufferBinding();
  5745. vbo.references = 1;
  5746. vbo.is32Bits = need32Bits;
  5747. return vbo;
  5748. };
  5749. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5750. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5751. this._cachedVertexBuffers = vertexBuffer;
  5752. this._cachedEffectForVertexBuffers = effect;
  5753. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5754. var offset = 0;
  5755. for (var index = 0; index < vertexDeclaration.length; index++) {
  5756. var order = effect.getAttributeLocation(index);
  5757. if (order >= 0) {
  5758. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5759. }
  5760. offset += vertexDeclaration[index] * 4;
  5761. }
  5762. }
  5763. if (this._cachedIndexBuffer !== indexBuffer) {
  5764. this._cachedIndexBuffer = indexBuffer;
  5765. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5766. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5767. }
  5768. };
  5769. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5770. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5771. this._cachedVertexBuffers = vertexBuffers;
  5772. this._cachedEffectForVertexBuffers = effect;
  5773. var attributes = effect.getAttributesNames();
  5774. for (var index = 0; index < attributes.length; index++) {
  5775. var order = effect.getAttributeLocation(index);
  5776. if (order >= 0) {
  5777. var vertexBuffer = vertexBuffers[attributes[index]];
  5778. if (!vertexBuffer) {
  5779. continue;
  5780. }
  5781. var stride = vertexBuffer.getStrideSize();
  5782. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5783. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5784. }
  5785. }
  5786. }
  5787. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5788. this._cachedIndexBuffer = indexBuffer;
  5789. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5790. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5791. }
  5792. };
  5793. Engine.prototype._releaseBuffer = function (buffer) {
  5794. buffer.references--;
  5795. if (buffer.references === 0) {
  5796. this._gl.deleteBuffer(buffer);
  5797. return true;
  5798. }
  5799. return false;
  5800. };
  5801. Engine.prototype.createInstancesBuffer = function (capacity) {
  5802. var buffer = this._gl.createBuffer();
  5803. buffer.capacity = capacity;
  5804. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5805. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5806. return buffer;
  5807. };
  5808. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5809. this._gl.deleteBuffer(buffer);
  5810. };
  5811. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5814. for (var index = 0; index < 4; index++) {
  5815. var offsetLocation = offsetLocations[index];
  5816. this._gl.enableVertexAttribArray(offsetLocation);
  5817. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5818. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5819. }
  5820. };
  5821. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5822. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5823. for (var index = 0; index < 4; index++) {
  5824. var offsetLocation = offsetLocations[index];
  5825. this._gl.disableVertexAttribArray(offsetLocation);
  5826. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5827. }
  5828. };
  5829. Engine.prototype.applyStates = function () {
  5830. this._depthCullingState.apply(this._gl);
  5831. this._alphaState.apply(this._gl);
  5832. };
  5833. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5834. // Apply states
  5835. this.applyStates();
  5836. this._drawCalls++;
  5837. // Render
  5838. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5839. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5840. if (instancesCount) {
  5841. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5842. return;
  5843. }
  5844. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5845. };
  5846. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5847. // Apply states
  5848. this.applyStates();
  5849. this._drawCalls++;
  5850. if (instancesCount) {
  5851. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5852. return;
  5853. }
  5854. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5855. };
  5856. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5857. // Apply states
  5858. this.applyStates();
  5859. this._drawCalls++;
  5860. if (instancesCount) {
  5861. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5862. return;
  5863. }
  5864. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5865. };
  5866. // Shaders
  5867. Engine.prototype._releaseEffect = function (effect) {
  5868. if (this._compiledEffects[effect._key]) {
  5869. delete this._compiledEffects[effect._key];
  5870. if (effect.getProgram()) {
  5871. this._gl.deleteProgram(effect.getProgram());
  5872. }
  5873. }
  5874. };
  5875. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5876. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5877. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5878. var name = vertex + "+" + fragment + "@" + defines;
  5879. if (this._compiledEffects[name]) {
  5880. return this._compiledEffects[name];
  5881. }
  5882. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5883. effect._key = name;
  5884. this._compiledEffects[name] = effect;
  5885. return effect;
  5886. };
  5887. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5888. if (uniformsNames === void 0) { uniformsNames = []; }
  5889. if (samplers === void 0) { samplers = []; }
  5890. if (defines === void 0) { defines = ""; }
  5891. return this.createEffect({
  5892. vertex: "particles",
  5893. fragmentElement: fragmentName
  5894. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5895. };
  5896. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5897. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5898. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5899. var shaderProgram = this._gl.createProgram();
  5900. this._gl.attachShader(shaderProgram, vertexShader);
  5901. this._gl.attachShader(shaderProgram, fragmentShader);
  5902. this._gl.linkProgram(shaderProgram);
  5903. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5904. if (!linked) {
  5905. var error = this._gl.getProgramInfoLog(shaderProgram);
  5906. if (error) {
  5907. throw new Error(error);
  5908. }
  5909. }
  5910. this._gl.deleteShader(vertexShader);
  5911. this._gl.deleteShader(fragmentShader);
  5912. return shaderProgram;
  5913. };
  5914. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5915. var results = [];
  5916. for (var index = 0; index < uniformsNames.length; index++) {
  5917. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5918. }
  5919. return results;
  5920. };
  5921. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5922. var results = [];
  5923. for (var index = 0; index < attributesNames.length; index++) {
  5924. try {
  5925. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5926. }
  5927. catch (e) {
  5928. results.push(-1);
  5929. }
  5930. }
  5931. return results;
  5932. };
  5933. Engine.prototype.enableEffect = function (effect) {
  5934. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5935. if (effect && effect.onBind) {
  5936. effect.onBind(effect);
  5937. }
  5938. return;
  5939. }
  5940. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5941. // Use program
  5942. this._gl.useProgram(effect.getProgram());
  5943. for (var i in this._vertexAttribArrays) {
  5944. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5945. continue;
  5946. }
  5947. this._vertexAttribArrays[i] = false;
  5948. this._gl.disableVertexAttribArray(i);
  5949. }
  5950. var attributesCount = effect.getAttributesCount();
  5951. for (var index = 0; index < attributesCount; index++) {
  5952. // Attributes
  5953. var order = effect.getAttributeLocation(index);
  5954. if (order >= 0) {
  5955. this._vertexAttribArrays[order] = true;
  5956. this._gl.enableVertexAttribArray(order);
  5957. }
  5958. }
  5959. this._currentEffect = effect;
  5960. if (effect.onBind) {
  5961. effect.onBind(effect);
  5962. }
  5963. };
  5964. Engine.prototype.setArray = function (uniform, array) {
  5965. if (!uniform)
  5966. return;
  5967. this._gl.uniform1fv(uniform, array);
  5968. };
  5969. Engine.prototype.setArray2 = function (uniform, array) {
  5970. if (!uniform || array.length % 2 !== 0)
  5971. return;
  5972. this._gl.uniform2fv(uniform, array);
  5973. };
  5974. Engine.prototype.setArray3 = function (uniform, array) {
  5975. if (!uniform || array.length % 3 !== 0)
  5976. return;
  5977. this._gl.uniform3fv(uniform, array);
  5978. };
  5979. Engine.prototype.setArray4 = function (uniform, array) {
  5980. if (!uniform || array.length % 4 !== 0)
  5981. return;
  5982. this._gl.uniform4fv(uniform, array);
  5983. };
  5984. Engine.prototype.setMatrices = function (uniform, matrices) {
  5985. if (!uniform)
  5986. return;
  5987. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5988. };
  5989. Engine.prototype.setMatrix = function (uniform, matrix) {
  5990. if (!uniform)
  5991. return;
  5992. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5993. };
  5994. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5995. if (!uniform)
  5996. return;
  5997. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5998. };
  5999. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6000. if (!uniform)
  6001. return;
  6002. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6003. };
  6004. Engine.prototype.setFloat = function (uniform, value) {
  6005. if (!uniform)
  6006. return;
  6007. this._gl.uniform1f(uniform, value);
  6008. };
  6009. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6010. if (!uniform)
  6011. return;
  6012. this._gl.uniform2f(uniform, x, y);
  6013. };
  6014. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6015. if (!uniform)
  6016. return;
  6017. this._gl.uniform3f(uniform, x, y, z);
  6018. };
  6019. Engine.prototype.setBool = function (uniform, bool) {
  6020. if (!uniform)
  6021. return;
  6022. this._gl.uniform1i(uniform, bool);
  6023. };
  6024. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6025. if (!uniform)
  6026. return;
  6027. this._gl.uniform4f(uniform, x, y, z, w);
  6028. };
  6029. Engine.prototype.setColor3 = function (uniform, color3) {
  6030. if (!uniform)
  6031. return;
  6032. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6033. };
  6034. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6035. if (!uniform)
  6036. return;
  6037. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6038. };
  6039. // States
  6040. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6041. if (zOffset === void 0) { zOffset = 0; }
  6042. if (reverseSide === void 0) { reverseSide = false; }
  6043. // Culling
  6044. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6045. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6046. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6047. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6048. if (culling) {
  6049. this._depthCullingState.cullFace = cullFace;
  6050. this._depthCullingState.cull = true;
  6051. }
  6052. else {
  6053. this._depthCullingState.cull = false;
  6054. }
  6055. }
  6056. // Z offset
  6057. this._depthCullingState.zOffset = zOffset;
  6058. };
  6059. Engine.prototype.setDepthBuffer = function (enable) {
  6060. this._depthCullingState.depthTest = enable;
  6061. };
  6062. Engine.prototype.getDepthWrite = function () {
  6063. return this._depthCullingState.depthMask;
  6064. };
  6065. Engine.prototype.setDepthWrite = function (enable) {
  6066. this._depthCullingState.depthMask = enable;
  6067. };
  6068. Engine.prototype.setColorWrite = function (enable) {
  6069. this._gl.colorMask(enable, enable, enable, enable);
  6070. };
  6071. Engine.prototype.setAlphaMode = function (mode) {
  6072. if (this._alphaMode === mode) {
  6073. return;
  6074. }
  6075. switch (mode) {
  6076. case Engine.ALPHA_DISABLE:
  6077. this.setDepthWrite(true);
  6078. this._alphaState.alphaBlend = false;
  6079. break;
  6080. case Engine.ALPHA_COMBINE:
  6081. this.setDepthWrite(false);
  6082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6083. this._alphaState.alphaBlend = true;
  6084. break;
  6085. case Engine.ALPHA_ONEONE:
  6086. this.setDepthWrite(false);
  6087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6088. this._alphaState.alphaBlend = true;
  6089. break;
  6090. case Engine.ALPHA_ADD:
  6091. this.setDepthWrite(false);
  6092. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6093. this._alphaState.alphaBlend = true;
  6094. break;
  6095. case Engine.ALPHA_SUBTRACT:
  6096. this.setDepthWrite(false);
  6097. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6098. this._alphaState.alphaBlend = true;
  6099. break;
  6100. case Engine.ALPHA_MULTIPLY:
  6101. this.setDepthWrite(false);
  6102. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6103. this._alphaState.alphaBlend = true;
  6104. break;
  6105. case Engine.ALPHA_MAXIMIZED:
  6106. this.setDepthWrite(false);
  6107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6108. this._alphaState.alphaBlend = true;
  6109. break;
  6110. }
  6111. this._alphaMode = mode;
  6112. };
  6113. Engine.prototype.getAlphaMode = function () {
  6114. return this._alphaMode;
  6115. };
  6116. Engine.prototype.setAlphaTesting = function (enable) {
  6117. this._alphaTest = enable;
  6118. };
  6119. Engine.prototype.getAlphaTesting = function () {
  6120. return this._alphaTest;
  6121. };
  6122. // Textures
  6123. Engine.prototype.wipeCaches = function () {
  6124. this.resetTextureCache();
  6125. this._currentEffect = null;
  6126. this._depthCullingState.reset();
  6127. this._alphaState.reset();
  6128. this._cachedVertexBuffers = null;
  6129. this._cachedIndexBuffer = null;
  6130. this._cachedEffectForVertexBuffers = null;
  6131. };
  6132. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6133. var gl = this._gl;
  6134. gl.bindTexture(gl.TEXTURE_2D, texture);
  6135. var magFilter = gl.NEAREST;
  6136. var minFilter = gl.NEAREST;
  6137. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6138. magFilter = gl.LINEAR;
  6139. minFilter = gl.LINEAR;
  6140. }
  6141. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6142. magFilter = gl.LINEAR;
  6143. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6144. }
  6145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6147. gl.bindTexture(gl.TEXTURE_2D, null);
  6148. texture.samplingMode = samplingMode;
  6149. };
  6150. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6151. var _this = this;
  6152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6153. if (onLoad === void 0) { onLoad = null; }
  6154. if (onError === void 0) { onError = null; }
  6155. if (buffer === void 0) { buffer = null; }
  6156. var texture = this._gl.createTexture();
  6157. var extension;
  6158. var fromData = false;
  6159. if (url.substr(0, 5) === "data:") {
  6160. fromData = true;
  6161. }
  6162. if (!fromData)
  6163. extension = url.substr(url.length - 4, 4).toLowerCase();
  6164. else {
  6165. var oldUrl = url;
  6166. fromData = oldUrl.split(':');
  6167. url = oldUrl;
  6168. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6169. }
  6170. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6171. var isTGA = (extension === ".tga");
  6172. scene._addPendingData(texture);
  6173. texture.url = url;
  6174. texture.noMipmap = noMipmap;
  6175. texture.references = 1;
  6176. texture.samplingMode = samplingMode;
  6177. this._loadedTexturesCache.push(texture);
  6178. var onerror = function () {
  6179. scene._removePendingData(texture);
  6180. if (onError) {
  6181. onError();
  6182. }
  6183. };
  6184. var callback;
  6185. if (isTGA) {
  6186. callback = function (arrayBuffer) {
  6187. var data = new Uint8Array(arrayBuffer);
  6188. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6189. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6190. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6191. if (onLoad) {
  6192. onLoad();
  6193. }
  6194. }, samplingMode);
  6195. };
  6196. if (!(fromData instanceof Array))
  6197. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6198. callback(arrayBuffer);
  6199. }, onerror, scene.database, true);
  6200. else
  6201. callback(buffer);
  6202. }
  6203. else if (isDDS) {
  6204. callback = function (data) {
  6205. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6206. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6207. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6208. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6209. if (onLoad) {
  6210. onLoad();
  6211. }
  6212. }, samplingMode);
  6213. };
  6214. if (!(fromData instanceof Array))
  6215. BABYLON.Tools.LoadFile(url, function (data) {
  6216. callback(data);
  6217. }, onerror, scene.database, true);
  6218. else
  6219. callback(buffer);
  6220. }
  6221. else {
  6222. var onload = function (img) {
  6223. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6224. var isPot = (img.width === potWidth && img.height === potHeight);
  6225. if (!isPot) {
  6226. _this._prepareWorkingCanvas();
  6227. _this._workingCanvas.width = potWidth;
  6228. _this._workingCanvas.height = potHeight;
  6229. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6230. _this._workingContext.imageSmoothingEnabled = false;
  6231. _this._workingContext.mozImageSmoothingEnabled = false;
  6232. _this._workingContext.oImageSmoothingEnabled = false;
  6233. _this._workingContext.webkitImageSmoothingEnabled = false;
  6234. _this._workingContext.msImageSmoothingEnabled = false;
  6235. }
  6236. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6237. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6238. _this._workingContext.imageSmoothingEnabled = true;
  6239. _this._workingContext.mozImageSmoothingEnabled = true;
  6240. _this._workingContext.oImageSmoothingEnabled = true;
  6241. _this._workingContext.webkitImageSmoothingEnabled = true;
  6242. _this._workingContext.msImageSmoothingEnabled = true;
  6243. }
  6244. }
  6245. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6246. if (onLoad) {
  6247. onLoad();
  6248. }
  6249. }, samplingMode);
  6250. };
  6251. if (!(fromData instanceof Array))
  6252. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6253. else
  6254. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6255. }
  6256. return texture;
  6257. };
  6258. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6259. if (compression === void 0) { compression = null; }
  6260. var internalFormat = this._gl.RGBA;
  6261. switch (format) {
  6262. case Engine.TEXTUREFORMAT_ALPHA:
  6263. internalFormat = this._gl.ALPHA;
  6264. break;
  6265. case Engine.TEXTUREFORMAT_LUMINANCE:
  6266. internalFormat = this._gl.LUMINANCE;
  6267. break;
  6268. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6269. internalFormat = this._gl.LUMINANCE_ALPHA;
  6270. break;
  6271. case Engine.TEXTUREFORMAT_RGB:
  6272. internalFormat = this._gl.RGB;
  6273. break;
  6274. case Engine.TEXTUREFORMAT_RGBA:
  6275. internalFormat = this._gl.RGBA;
  6276. break;
  6277. }
  6278. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6279. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6280. if (compression) {
  6281. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6282. }
  6283. else {
  6284. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6285. }
  6286. if (texture.generateMipMaps) {
  6287. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6288. }
  6289. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6290. this.resetTextureCache();
  6291. texture.isReady = true;
  6292. };
  6293. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6294. if (compression === void 0) { compression = null; }
  6295. var texture = this._gl.createTexture();
  6296. texture._baseWidth = width;
  6297. texture._baseHeight = height;
  6298. texture._width = width;
  6299. texture._height = height;
  6300. texture.references = 1;
  6301. this.updateRawTexture(texture, data, format, invertY, compression);
  6302. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6303. // Filters
  6304. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6307. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6308. texture.samplingMode = samplingMode;
  6309. this._loadedTexturesCache.push(texture);
  6310. return texture;
  6311. };
  6312. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6313. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6314. var texture = this._gl.createTexture();
  6315. texture._baseWidth = width;
  6316. texture._baseHeight = height;
  6317. if (forceExponantOfTwo) {
  6318. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6319. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6320. }
  6321. this.resetTextureCache();
  6322. texture._width = width;
  6323. texture._height = height;
  6324. texture.isReady = false;
  6325. texture.generateMipMaps = generateMipMaps;
  6326. texture.references = 1;
  6327. texture.samplingMode = samplingMode;
  6328. this.updateTextureSamplingMode(samplingMode, texture);
  6329. this._loadedTexturesCache.push(texture);
  6330. return texture;
  6331. };
  6332. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6333. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6334. if (texture.isCube) {
  6335. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6336. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6337. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6338. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6339. }
  6340. else {
  6341. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6342. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6343. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6344. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6345. }
  6346. };
  6347. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6348. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6349. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6350. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6351. if (texture.generateMipMaps) {
  6352. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6353. }
  6354. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6355. this.resetTextureCache();
  6356. texture.isReady = true;
  6357. };
  6358. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6359. if (texture._isDisabled) {
  6360. return;
  6361. }
  6362. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6363. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6364. try {
  6365. // Testing video texture support
  6366. if (this._videoTextureSupported === undefined) {
  6367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6368. if (this._gl.getError() !== 0) {
  6369. this._videoTextureSupported = false;
  6370. }
  6371. else {
  6372. this._videoTextureSupported = true;
  6373. }
  6374. }
  6375. // Copy video through the current working canvas if video texture is not supported
  6376. if (!this._videoTextureSupported) {
  6377. if (!texture._workingCanvas) {
  6378. texture._workingCanvas = document.createElement("canvas");
  6379. texture._workingContext = texture._workingCanvas.getContext("2d");
  6380. texture._workingCanvas.width = texture._width;
  6381. texture._workingCanvas.height = texture._height;
  6382. }
  6383. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6385. }
  6386. else {
  6387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6388. }
  6389. if (texture.generateMipMaps) {
  6390. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6391. }
  6392. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6393. this.resetTextureCache();
  6394. texture.isReady = true;
  6395. }
  6396. catch (ex) {
  6397. // Something unexpected
  6398. // Let's disable the texture
  6399. texture._isDisabled = true;
  6400. }
  6401. };
  6402. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6403. // old version had a "generateMipMaps" arg instead of options.
  6404. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6405. // in the same way, generateDepthBuffer is defaulted to true
  6406. var generateMipMaps = false;
  6407. var generateDepthBuffer = true;
  6408. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6409. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6410. if (options !== undefined) {
  6411. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6412. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6413. type = options.type === undefined ? type : options.type;
  6414. if (options.samplingMode !== undefined) {
  6415. samplingMode = options.samplingMode;
  6416. }
  6417. if (type === Engine.TEXTURETYPE_FLOAT) {
  6418. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6419. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6420. }
  6421. }
  6422. var gl = this._gl;
  6423. var texture = gl.createTexture();
  6424. gl.bindTexture(gl.TEXTURE_2D, texture);
  6425. var width = size.width || size;
  6426. var height = size.height || size;
  6427. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6428. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6429. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6430. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6431. }
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6436. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6437. var depthBuffer;
  6438. // Create the depth buffer
  6439. if (generateDepthBuffer) {
  6440. depthBuffer = gl.createRenderbuffer();
  6441. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6442. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6443. }
  6444. // Create the framebuffer
  6445. var framebuffer = gl.createFramebuffer();
  6446. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6447. if (generateDepthBuffer) {
  6448. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6449. }
  6450. if (generateMipMaps) {
  6451. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6452. }
  6453. // Unbind
  6454. gl.bindTexture(gl.TEXTURE_2D, null);
  6455. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6456. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6457. texture._framebuffer = framebuffer;
  6458. if (generateDepthBuffer) {
  6459. texture._depthBuffer = depthBuffer;
  6460. }
  6461. texture._width = width;
  6462. texture._height = height;
  6463. texture.isReady = true;
  6464. texture.generateMipMaps = generateMipMaps;
  6465. texture.references = 1;
  6466. texture.samplingMode = samplingMode;
  6467. this.resetTextureCache();
  6468. this._loadedTexturesCache.push(texture);
  6469. return texture;
  6470. };
  6471. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6472. var gl = this._gl;
  6473. var texture = gl.createTexture();
  6474. var generateMipMaps = true;
  6475. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6476. if (options !== undefined) {
  6477. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6478. if (options.samplingMode !== undefined) {
  6479. samplingMode = options.samplingMode;
  6480. }
  6481. }
  6482. texture.isCube = true;
  6483. texture.references = 1;
  6484. texture.generateMipMaps = generateMipMaps;
  6485. texture.references = 1;
  6486. texture.samplingMode = samplingMode;
  6487. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6488. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6489. for (var face = 0; face < 6; face++) {
  6490. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6491. }
  6492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6496. // Create the depth buffer
  6497. var depthBuffer = gl.createRenderbuffer();
  6498. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6499. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6500. // Create the framebuffer
  6501. var framebuffer = gl.createFramebuffer();
  6502. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6503. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6504. // mipmaps
  6505. if (texture.generateMipMaps) {
  6506. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6507. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6508. }
  6509. // Unbind
  6510. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6511. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6512. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6513. texture._framebuffer = framebuffer;
  6514. texture._depthBuffer = depthBuffer;
  6515. this.resetTextureCache();
  6516. texture._width = size;
  6517. texture._height = size;
  6518. texture.isReady = true;
  6519. return texture;
  6520. };
  6521. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6522. var _this = this;
  6523. var gl = this._gl;
  6524. var texture = gl.createTexture();
  6525. texture.isCube = true;
  6526. texture.url = rootUrl;
  6527. texture.references = 1;
  6528. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6529. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6530. if (isDDS) {
  6531. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6532. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6533. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6534. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6535. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6536. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6537. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6538. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6539. }
  6540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6544. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6545. _this.resetTextureCache();
  6546. texture._width = info.width;
  6547. texture._height = info.height;
  6548. texture.isReady = true;
  6549. }, null, null, true);
  6550. }
  6551. else {
  6552. cascadeLoad(rootUrl, scene, function (imgs) {
  6553. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6554. var height = width;
  6555. _this._prepareWorkingCanvas();
  6556. _this._workingCanvas.width = width;
  6557. _this._workingCanvas.height = height;
  6558. var faces = [
  6559. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6560. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6561. ];
  6562. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6563. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6564. for (var index = 0; index < faces.length; index++) {
  6565. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6566. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6567. }
  6568. if (!noMipmap) {
  6569. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6570. }
  6571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6575. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6576. _this.resetTextureCache();
  6577. texture._width = width;
  6578. texture._height = height;
  6579. texture.isReady = true;
  6580. }, extensions);
  6581. }
  6582. return texture;
  6583. };
  6584. Engine.prototype._releaseTexture = function (texture) {
  6585. var gl = this._gl;
  6586. if (texture._framebuffer) {
  6587. gl.deleteFramebuffer(texture._framebuffer);
  6588. }
  6589. if (texture._depthBuffer) {
  6590. gl.deleteRenderbuffer(texture._depthBuffer);
  6591. }
  6592. gl.deleteTexture(texture);
  6593. // Unbind channels
  6594. this.unbindAllTextures();
  6595. var index = this._loadedTexturesCache.indexOf(texture);
  6596. if (index !== -1) {
  6597. this._loadedTexturesCache.splice(index, 1);
  6598. }
  6599. };
  6600. Engine.prototype.bindSamplers = function (effect) {
  6601. this._gl.useProgram(effect.getProgram());
  6602. var samplers = effect.getSamplers();
  6603. for (var index = 0; index < samplers.length; index++) {
  6604. var uniform = effect.getUniform(samplers[index]);
  6605. this._gl.uniform1i(uniform, index);
  6606. }
  6607. this._currentEffect = null;
  6608. };
  6609. Engine.prototype._bindTexture = function (channel, texture) {
  6610. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6611. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6612. this._activeTexturesCache[channel] = null;
  6613. };
  6614. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6615. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6616. };
  6617. Engine.prototype.unbindAllTextures = function () {
  6618. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6619. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6620. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6621. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6622. this._activeTexturesCache[channel] = null;
  6623. }
  6624. };
  6625. Engine.prototype.setTexture = function (channel, texture) {
  6626. if (channel < 0) {
  6627. return;
  6628. }
  6629. // Not ready?
  6630. if (!texture || !texture.isReady()) {
  6631. if (this._activeTexturesCache[channel] != null) {
  6632. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6633. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6634. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6635. this._activeTexturesCache[channel] = null;
  6636. }
  6637. return;
  6638. }
  6639. // Video
  6640. var alreadyActivated = false;
  6641. if (texture instanceof BABYLON.VideoTexture) {
  6642. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6643. alreadyActivated = true;
  6644. texture.update();
  6645. }
  6646. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6647. texture.delayLoad();
  6648. return;
  6649. }
  6650. if (this._activeTexturesCache[channel] === texture) {
  6651. return;
  6652. }
  6653. this._activeTexturesCache[channel] = texture;
  6654. var internalTexture = texture.getInternalTexture();
  6655. if (!alreadyActivated) {
  6656. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6657. }
  6658. if (internalTexture.isCube) {
  6659. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6660. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6661. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6662. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6663. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6664. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6665. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6666. }
  6667. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6668. }
  6669. else {
  6670. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6671. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6672. internalTexture._cachedWrapU = texture.wrapU;
  6673. switch (texture.wrapU) {
  6674. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6675. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6676. break;
  6677. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6678. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6679. break;
  6680. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6682. break;
  6683. }
  6684. }
  6685. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6686. internalTexture._cachedWrapV = texture.wrapV;
  6687. switch (texture.wrapV) {
  6688. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6689. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6690. break;
  6691. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6693. break;
  6694. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6696. break;
  6697. }
  6698. }
  6699. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6700. }
  6701. };
  6702. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6703. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6704. var value = texture.anisotropicFilteringLevel;
  6705. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6706. value = 1;
  6707. }
  6708. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6709. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6710. texture._cachedAnisotropicFilteringLevel = value;
  6711. }
  6712. };
  6713. Engine.prototype.readPixels = function (x, y, width, height) {
  6714. var data = new Uint8Array(height * width * 4);
  6715. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6716. return data;
  6717. };
  6718. Engine.prototype.releaseInternalTexture = function (texture) {
  6719. if (!texture) {
  6720. return;
  6721. }
  6722. texture.references--;
  6723. // Final reference ?
  6724. if (texture.references === 0) {
  6725. var texturesCache = this.getLoadedTexturesCache();
  6726. var index = texturesCache.indexOf(texture);
  6727. if (index > -1) {
  6728. texturesCache.splice(index, 1);
  6729. }
  6730. this._releaseTexture(texture);
  6731. }
  6732. };
  6733. // Dispose
  6734. Engine.prototype.dispose = function () {
  6735. this.hideLoadingUI();
  6736. this.stopRenderLoop();
  6737. // Release scenes
  6738. while (this.scenes.length) {
  6739. this.scenes[0].dispose();
  6740. }
  6741. // Release audio engine
  6742. Engine.audioEngine.dispose();
  6743. // Release effects
  6744. for (var name in this._compiledEffects) {
  6745. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6746. }
  6747. // Unbind
  6748. for (var i in this._vertexAttribArrays) {
  6749. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6750. continue;
  6751. }
  6752. this._gl.disableVertexAttribArray(i);
  6753. }
  6754. this._gl = null;
  6755. // Events
  6756. window.removeEventListener("blur", this._onBlur);
  6757. window.removeEventListener("focus", this._onFocus);
  6758. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6759. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6760. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6761. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6762. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6763. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6764. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6765. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6766. };
  6767. // Loading screen
  6768. Engine.prototype.displayLoadingUI = function () {
  6769. this._loadingScreen.displayLoadingUI();
  6770. };
  6771. Engine.prototype.hideLoadingUI = function () {
  6772. this._loadingScreen.hideLoadingUI();
  6773. };
  6774. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6775. get: function () {
  6776. return this._loadingScreen;
  6777. },
  6778. set: function (loadingScreen) {
  6779. this._loadingScreen = loadingScreen;
  6780. },
  6781. enumerable: true,
  6782. configurable: true
  6783. });
  6784. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6785. set: function (text) {
  6786. this._loadingScreen.loadingUIText = text;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6792. set: function (color) {
  6793. this._loadingScreen.loadingUIBackgroundColor = color;
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. // FPS
  6799. Engine.prototype.getFps = function () {
  6800. return this.fps;
  6801. };
  6802. Engine.prototype.getDeltaTime = function () {
  6803. return this.deltaTime;
  6804. };
  6805. Engine.prototype._measureFps = function () {
  6806. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6807. var length = this.previousFramesDuration.length;
  6808. if (length >= 2) {
  6809. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6810. }
  6811. if (length >= this.fpsRange) {
  6812. if (length > this.fpsRange) {
  6813. this.previousFramesDuration.splice(0, 1);
  6814. length = this.previousFramesDuration.length;
  6815. }
  6816. var sum = 0;
  6817. for (var id = 0; id < length - 1; id++) {
  6818. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6819. }
  6820. this.fps = 1000.0 / (sum / (length - 1));
  6821. }
  6822. };
  6823. // Statics
  6824. Engine.isSupported = function () {
  6825. try {
  6826. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6827. if (navigator.isCocoonJS) {
  6828. return true;
  6829. }
  6830. var tempcanvas = document.createElement("canvas");
  6831. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6832. return gl != null && !!window.WebGLRenderingContext;
  6833. }
  6834. catch (e) {
  6835. return false;
  6836. }
  6837. };
  6838. // Const statics
  6839. Engine._ALPHA_DISABLE = 0;
  6840. Engine._ALPHA_ADD = 1;
  6841. Engine._ALPHA_COMBINE = 2;
  6842. Engine._ALPHA_SUBTRACT = 3;
  6843. Engine._ALPHA_MULTIPLY = 4;
  6844. Engine._ALPHA_MAXIMIZED = 5;
  6845. Engine._ALPHA_ONEONE = 6;
  6846. Engine._DELAYLOADSTATE_NONE = 0;
  6847. Engine._DELAYLOADSTATE_LOADED = 1;
  6848. Engine._DELAYLOADSTATE_LOADING = 2;
  6849. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6850. Engine._TEXTUREFORMAT_ALPHA = 0;
  6851. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6852. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6853. Engine._TEXTUREFORMAT_RGB = 4;
  6854. Engine._TEXTUREFORMAT_RGBA = 5;
  6855. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6856. Engine._TEXTURETYPE_FLOAT = 1;
  6857. // Updatable statics so stick with vars here
  6858. Engine.Epsilon = 0.001;
  6859. Engine.CollisionsEpsilon = 0.001;
  6860. Engine.CodeRepository = "src/";
  6861. Engine.ShadersRepository = "src/Shaders/";
  6862. return Engine;
  6863. })();
  6864. BABYLON.Engine = Engine;
  6865. })(BABYLON || (BABYLON = {}));
  6866. var BABYLON;
  6867. (function (BABYLON) {
  6868. /**
  6869. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6870. */
  6871. var Node = (function () {
  6872. /**
  6873. * @constructor
  6874. * @param {string} name - the name and id to be given to this node
  6875. * @param {BABYLON.Scene} the scene this node will be added to
  6876. */
  6877. function Node(name, scene) {
  6878. this.state = "";
  6879. this.animations = new Array();
  6880. this._childrenFlag = -1;
  6881. this._isEnabled = true;
  6882. this._isReady = true;
  6883. this._currentRenderId = -1;
  6884. this._parentRenderId = -1;
  6885. this.name = name;
  6886. this.id = name;
  6887. this._scene = scene;
  6888. this._initCache();
  6889. }
  6890. Node.prototype.getScene = function () {
  6891. return this._scene;
  6892. };
  6893. Node.prototype.getEngine = function () {
  6894. return this._scene.getEngine();
  6895. };
  6896. // override it in derived class
  6897. Node.prototype.getWorldMatrix = function () {
  6898. return BABYLON.Matrix.Identity();
  6899. };
  6900. // override it in derived class if you add new variables to the cache
  6901. // and call the parent class method
  6902. Node.prototype._initCache = function () {
  6903. this._cache = {};
  6904. this._cache.parent = undefined;
  6905. };
  6906. Node.prototype.updateCache = function (force) {
  6907. if (!force && this.isSynchronized())
  6908. return;
  6909. this._cache.parent = this.parent;
  6910. this._updateCache();
  6911. };
  6912. // override it in derived class if you add new variables to the cache
  6913. // and call the parent class method if !ignoreParentClass
  6914. Node.prototype._updateCache = function (ignoreParentClass) {
  6915. };
  6916. // override it in derived class if you add new variables to the cache
  6917. Node.prototype._isSynchronized = function () {
  6918. return true;
  6919. };
  6920. Node.prototype._markSyncedWithParent = function () {
  6921. this._parentRenderId = this.parent._currentRenderId;
  6922. };
  6923. Node.prototype.isSynchronizedWithParent = function () {
  6924. if (!this.parent) {
  6925. return true;
  6926. }
  6927. if (this._parentRenderId !== this.parent._currentRenderId) {
  6928. return false;
  6929. }
  6930. return this.parent.isSynchronized();
  6931. };
  6932. Node.prototype.isSynchronized = function (updateCache) {
  6933. var check = this.hasNewParent();
  6934. check = check || !this.isSynchronizedWithParent();
  6935. check = check || !this._isSynchronized();
  6936. if (updateCache)
  6937. this.updateCache(true);
  6938. return !check;
  6939. };
  6940. Node.prototype.hasNewParent = function (update) {
  6941. if (this._cache.parent === this.parent)
  6942. return false;
  6943. if (update)
  6944. this._cache.parent = this.parent;
  6945. return true;
  6946. };
  6947. /**
  6948. * Is this node ready to be used/rendered
  6949. * @return {boolean} is it ready
  6950. */
  6951. Node.prototype.isReady = function () {
  6952. return this._isReady;
  6953. };
  6954. /**
  6955. * Is this node enabled.
  6956. * If the node has a parent and is enabled, the parent will be inspected as well.
  6957. * @return {boolean} whether this node (and its parent) is enabled.
  6958. * @see setEnabled
  6959. */
  6960. Node.prototype.isEnabled = function () {
  6961. if (!this._isEnabled) {
  6962. return false;
  6963. }
  6964. if (this.parent) {
  6965. return this.parent.isEnabled();
  6966. }
  6967. return true;
  6968. };
  6969. /**
  6970. * Set the enabled state of this node.
  6971. * @param {boolean} value - the new enabled state
  6972. * @see isEnabled
  6973. */
  6974. Node.prototype.setEnabled = function (value) {
  6975. this._isEnabled = value;
  6976. };
  6977. /**
  6978. * Is this node a descendant of the given node.
  6979. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6980. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6981. * @see parent
  6982. */
  6983. Node.prototype.isDescendantOf = function (ancestor) {
  6984. if (this.parent) {
  6985. if (this.parent === ancestor) {
  6986. return true;
  6987. }
  6988. return this.parent.isDescendantOf(ancestor);
  6989. }
  6990. return false;
  6991. };
  6992. Node.prototype._getDescendants = function (list, results) {
  6993. for (var index = 0; index < list.length; index++) {
  6994. var item = list[index];
  6995. if (item.isDescendantOf(this)) {
  6996. results.push(item);
  6997. }
  6998. }
  6999. };
  7000. /**
  7001. * Will return all nodes that have this node as parent.
  7002. * @return {BABYLON.Node[]} all children nodes of all types.
  7003. */
  7004. Node.prototype.getDescendants = function () {
  7005. var results = [];
  7006. this._getDescendants(this._scene.meshes, results);
  7007. this._getDescendants(this._scene.lights, results);
  7008. this._getDescendants(this._scene.cameras, results);
  7009. return results;
  7010. };
  7011. Node.prototype._setReady = function (state) {
  7012. if (state === this._isReady) {
  7013. return;
  7014. }
  7015. if (!state) {
  7016. this._isReady = false;
  7017. return;
  7018. }
  7019. this._isReady = true;
  7020. if (this.onReady) {
  7021. this.onReady(this);
  7022. }
  7023. };
  7024. Node.prototype.getAnimationByName = function (name) {
  7025. for (var i = 0; i < this.animations.length; i++) {
  7026. var animation = this.animations[i];
  7027. if (animation.name === name) {
  7028. return animation;
  7029. }
  7030. }
  7031. return null;
  7032. };
  7033. return Node;
  7034. })();
  7035. BABYLON.Node = Node;
  7036. })(BABYLON || (BABYLON = {}));
  7037. var BABYLON;
  7038. (function (BABYLON) {
  7039. var FilesInput = (function () {
  7040. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7041. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7042. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7043. this._engine = p_engine;
  7044. this._canvas = p_canvas;
  7045. this._currentScene = p_scene;
  7046. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7047. this._progressCallback = p_progressCallback;
  7048. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7049. this._textureLoadingCallback = p_textureLoadingCallback;
  7050. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7051. }
  7052. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7053. var _this = this;
  7054. if (p_elementToMonitor) {
  7055. this._elementToMonitor = p_elementToMonitor;
  7056. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7057. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7058. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7059. }
  7060. };
  7061. FilesInput.prototype.renderFunction = function () {
  7062. if (this._additionnalRenderLoopLogicCallback) {
  7063. this._additionnalRenderLoopLogicCallback();
  7064. }
  7065. if (this._currentScene) {
  7066. if (this._textureLoadingCallback) {
  7067. var remaining = this._currentScene.getWaitingItemsCount();
  7068. if (remaining > 0) {
  7069. this._textureLoadingCallback(remaining);
  7070. }
  7071. }
  7072. this._currentScene.render();
  7073. }
  7074. };
  7075. FilesInput.prototype.drag = function (e) {
  7076. e.stopPropagation();
  7077. e.preventDefault();
  7078. };
  7079. FilesInput.prototype.drop = function (eventDrop) {
  7080. eventDrop.stopPropagation();
  7081. eventDrop.preventDefault();
  7082. this.loadFiles(eventDrop);
  7083. };
  7084. FilesInput.prototype.loadFiles = function (event) {
  7085. if (this._startingProcessingFilesCallback)
  7086. this._startingProcessingFilesCallback();
  7087. // Handling data transfer via drag'n'drop
  7088. if (event && event.dataTransfer && event.dataTransfer.files) {
  7089. this._filesToLoad = event.dataTransfer.files;
  7090. }
  7091. // Handling files from input files
  7092. if (event && event.target && event.target.files) {
  7093. this._filesToLoad = event.target.files;
  7094. }
  7095. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7096. for (var i = 0; i < this._filesToLoad.length; i++) {
  7097. switch (this._filesToLoad[i].type) {
  7098. case "image/jpeg":
  7099. case "image/png":
  7100. case "image/bmp":
  7101. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7102. break;
  7103. case "image/targa":
  7104. case "image/vnd.ms-dds":
  7105. case "audio/wav":
  7106. case "audio/x-wav":
  7107. case "audio/mp3":
  7108. case "audio/mpeg":
  7109. case "audio/mpeg3":
  7110. case "audio/x-mpeg-3":
  7111. case "audio/ogg":
  7112. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7113. break;
  7114. default:
  7115. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7116. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7117. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7118. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7119. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7120. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7121. this._sceneFileToLoad = this._filesToLoad[i];
  7122. }
  7123. break;
  7124. }
  7125. }
  7126. this.reload();
  7127. }
  7128. };
  7129. FilesInput.prototype.reload = function () {
  7130. var _this = this;
  7131. var that = this;
  7132. // If a ".babylon" file has been provided
  7133. if (this._sceneFileToLoad) {
  7134. if (this._currentScene) {
  7135. if (BABYLON.Tools.errorsCount > 0) {
  7136. BABYLON.Tools.ClearLogCache();
  7137. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7138. }
  7139. this._engine.stopRenderLoop();
  7140. this._currentScene.dispose();
  7141. }
  7142. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7143. that._currentScene = newScene;
  7144. // Wait for textures and shaders to be ready
  7145. that._currentScene.executeWhenReady(function () {
  7146. // Attach camera to canvas inputs
  7147. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7148. that._currentScene.createDefaultCameraOrLight();
  7149. }
  7150. that._currentScene.activeCamera.attachControl(that._canvas);
  7151. if (that._sceneLoadedCallback) {
  7152. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7153. }
  7154. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7155. });
  7156. }, function (progress) {
  7157. if (_this._progressCallback) {
  7158. _this._progressCallback(progress);
  7159. }
  7160. });
  7161. }
  7162. else {
  7163. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7164. }
  7165. };
  7166. FilesInput.FilesTextures = new Array();
  7167. FilesInput.FilesToLoad = new Array();
  7168. return FilesInput;
  7169. })();
  7170. BABYLON.FilesInput = FilesInput;
  7171. })(BABYLON || (BABYLON = {}));
  7172. var BABYLON;
  7173. (function (BABYLON) {
  7174. var IntersectionInfo = (function () {
  7175. function IntersectionInfo(bu, bv, distance) {
  7176. this.bu = bu;
  7177. this.bv = bv;
  7178. this.distance = distance;
  7179. this.faceId = 0;
  7180. this.subMeshId = 0;
  7181. }
  7182. return IntersectionInfo;
  7183. })();
  7184. BABYLON.IntersectionInfo = IntersectionInfo;
  7185. var PickingInfo = (function () {
  7186. function PickingInfo() {
  7187. this.hit = false;
  7188. this.distance = 0;
  7189. this.pickedPoint = null;
  7190. this.pickedMesh = null;
  7191. this.bu = 0;
  7192. this.bv = 0;
  7193. this.faceId = -1;
  7194. this.subMeshId = 0;
  7195. this.pickedSprite = null;
  7196. }
  7197. // Methods
  7198. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7199. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7200. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7201. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7202. return null;
  7203. }
  7204. var indices = this.pickedMesh.getIndices();
  7205. var result;
  7206. if (useVerticesNormals) {
  7207. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7208. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7209. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7210. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7211. normal0 = normal0.scale(this.bu);
  7212. normal1 = normal1.scale(this.bv);
  7213. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7214. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7215. }
  7216. else {
  7217. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7218. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7219. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7220. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7221. var p1p2 = vertex1.subtract(vertex2);
  7222. var p3p2 = vertex3.subtract(vertex2);
  7223. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7224. }
  7225. if (useWorldCoordinates) {
  7226. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7227. }
  7228. return BABYLON.Vector3.Normalize(result);
  7229. };
  7230. PickingInfo.prototype.getTextureCoordinates = function () {
  7231. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7232. return null;
  7233. }
  7234. var indices = this.pickedMesh.getIndices();
  7235. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7236. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7237. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7238. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7239. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7240. uv1 = uv1.scale(this.bu);
  7241. uv2 = uv2.scale(this.bv);
  7242. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7243. };
  7244. return PickingInfo;
  7245. })();
  7246. BABYLON.PickingInfo = PickingInfo;
  7247. })(BABYLON || (BABYLON = {}));
  7248. var BABYLON;
  7249. (function (BABYLON) {
  7250. var BoundingSphere = (function () {
  7251. function BoundingSphere(minimum, maximum) {
  7252. this.minimum = minimum;
  7253. this.maximum = maximum;
  7254. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7255. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7256. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7257. this.radius = distance * 0.5;
  7258. this.centerWorld = BABYLON.Vector3.Zero();
  7259. this._update(BABYLON.Matrix.Identity());
  7260. }
  7261. // Methods
  7262. BoundingSphere.prototype._update = function (world) {
  7263. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7264. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7265. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7266. };
  7267. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7268. for (var i = 0; i < 6; i++) {
  7269. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7270. return false;
  7271. }
  7272. return true;
  7273. };
  7274. BoundingSphere.prototype.intersectsPoint = function (point) {
  7275. var x = this.centerWorld.x - point.x;
  7276. var y = this.centerWorld.y - point.y;
  7277. var z = this.centerWorld.z - point.z;
  7278. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7279. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7280. return false;
  7281. return true;
  7282. };
  7283. // Statics
  7284. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7285. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7286. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7287. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7288. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7289. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7290. return false;
  7291. return true;
  7292. };
  7293. return BoundingSphere;
  7294. })();
  7295. BABYLON.BoundingSphere = BoundingSphere;
  7296. })(BABYLON || (BABYLON = {}));
  7297. var BABYLON;
  7298. (function (BABYLON) {
  7299. var BoundingBox = (function () {
  7300. function BoundingBox(minimum, maximum) {
  7301. this.minimum = minimum;
  7302. this.maximum = maximum;
  7303. this.vectors = new Array();
  7304. this.vectorsWorld = new Array();
  7305. // Bounding vectors
  7306. this.vectors.push(this.minimum.clone());
  7307. this.vectors.push(this.maximum.clone());
  7308. this.vectors.push(this.minimum.clone());
  7309. this.vectors[2].x = this.maximum.x;
  7310. this.vectors.push(this.minimum.clone());
  7311. this.vectors[3].y = this.maximum.y;
  7312. this.vectors.push(this.minimum.clone());
  7313. this.vectors[4].z = this.maximum.z;
  7314. this.vectors.push(this.maximum.clone());
  7315. this.vectors[5].z = this.minimum.z;
  7316. this.vectors.push(this.maximum.clone());
  7317. this.vectors[6].x = this.minimum.x;
  7318. this.vectors.push(this.maximum.clone());
  7319. this.vectors[7].y = this.minimum.y;
  7320. // OBB
  7321. this.center = this.maximum.add(this.minimum).scale(0.5);
  7322. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7323. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7324. // World
  7325. for (var index = 0; index < this.vectors.length; index++) {
  7326. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7327. }
  7328. this.minimumWorld = BABYLON.Vector3.Zero();
  7329. this.maximumWorld = BABYLON.Vector3.Zero();
  7330. this._update(BABYLON.Matrix.Identity());
  7331. }
  7332. // Methods
  7333. BoundingBox.prototype.getWorldMatrix = function () {
  7334. return this._worldMatrix;
  7335. };
  7336. BoundingBox.prototype._update = function (world) {
  7337. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7338. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7339. for (var index = 0; index < this.vectors.length; index++) {
  7340. var v = this.vectorsWorld[index];
  7341. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7342. if (v.x < this.minimumWorld.x)
  7343. this.minimumWorld.x = v.x;
  7344. if (v.y < this.minimumWorld.y)
  7345. this.minimumWorld.y = v.y;
  7346. if (v.z < this.minimumWorld.z)
  7347. this.minimumWorld.z = v.z;
  7348. if (v.x > this.maximumWorld.x)
  7349. this.maximumWorld.x = v.x;
  7350. if (v.y > this.maximumWorld.y)
  7351. this.maximumWorld.y = v.y;
  7352. if (v.z > this.maximumWorld.z)
  7353. this.maximumWorld.z = v.z;
  7354. }
  7355. // OBB
  7356. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7357. this.center.scaleInPlace(0.5);
  7358. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7359. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7360. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7361. this._worldMatrix = world;
  7362. };
  7363. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7364. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7365. };
  7366. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7367. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7368. };
  7369. BoundingBox.prototype.intersectsPoint = function (point) {
  7370. var delta = -BABYLON.Engine.Epsilon;
  7371. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7372. return false;
  7373. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7374. return false;
  7375. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7376. return false;
  7377. return true;
  7378. };
  7379. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7380. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7381. };
  7382. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7383. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7384. return false;
  7385. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7386. return false;
  7387. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7388. return false;
  7389. return true;
  7390. };
  7391. // Statics
  7392. BoundingBox.Intersects = function (box0, box1) {
  7393. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7394. return false;
  7395. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7396. return false;
  7397. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7398. return false;
  7399. return true;
  7400. };
  7401. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7402. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7403. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7404. return (num <= (sphereRadius * sphereRadius));
  7405. };
  7406. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7407. for (var p = 0; p < 6; p++) {
  7408. for (var i = 0; i < 8; i++) {
  7409. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7410. return false;
  7411. }
  7412. }
  7413. }
  7414. return true;
  7415. };
  7416. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7417. for (var p = 0; p < 6; p++) {
  7418. var inCount = 8;
  7419. for (var i = 0; i < 8; i++) {
  7420. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7421. --inCount;
  7422. }
  7423. else {
  7424. break;
  7425. }
  7426. }
  7427. if (inCount === 0)
  7428. return false;
  7429. }
  7430. return true;
  7431. };
  7432. return BoundingBox;
  7433. })();
  7434. BABYLON.BoundingBox = BoundingBox;
  7435. })(BABYLON || (BABYLON = {}));
  7436. var BABYLON;
  7437. (function (BABYLON) {
  7438. var computeBoxExtents = function (axis, box) {
  7439. var p = BABYLON.Vector3.Dot(box.center, axis);
  7440. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7441. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7442. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7443. var r = r0 + r1 + r2;
  7444. return {
  7445. min: p - r,
  7446. max: p + r
  7447. };
  7448. };
  7449. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7450. var axisOverlap = function (axis, box0, box1) {
  7451. var result0 = computeBoxExtents(axis, box0);
  7452. var result1 = computeBoxExtents(axis, box1);
  7453. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7454. };
  7455. var BoundingInfo = (function () {
  7456. function BoundingInfo(minimum, maximum) {
  7457. this.minimum = minimum;
  7458. this.maximum = maximum;
  7459. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7460. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7461. }
  7462. // Methods
  7463. BoundingInfo.prototype._update = function (world) {
  7464. this.boundingBox._update(world);
  7465. this.boundingSphere._update(world);
  7466. };
  7467. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7468. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7469. return false;
  7470. return this.boundingBox.isInFrustum(frustumPlanes);
  7471. };
  7472. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7473. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7474. };
  7475. BoundingInfo.prototype._checkCollision = function (collider) {
  7476. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7477. };
  7478. BoundingInfo.prototype.intersectsPoint = function (point) {
  7479. if (!this.boundingSphere.centerWorld) {
  7480. return false;
  7481. }
  7482. if (!this.boundingSphere.intersectsPoint(point)) {
  7483. return false;
  7484. }
  7485. if (!this.boundingBox.intersectsPoint(point)) {
  7486. return false;
  7487. }
  7488. return true;
  7489. };
  7490. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7491. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7492. return false;
  7493. }
  7494. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7495. return false;
  7496. }
  7497. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7498. return false;
  7499. }
  7500. if (!precise) {
  7501. return true;
  7502. }
  7503. var box0 = this.boundingBox;
  7504. var box1 = boundingInfo.boundingBox;
  7505. if (!axisOverlap(box0.directions[0], box0, box1))
  7506. return false;
  7507. if (!axisOverlap(box0.directions[1], box0, box1))
  7508. return false;
  7509. if (!axisOverlap(box0.directions[2], box0, box1))
  7510. return false;
  7511. if (!axisOverlap(box1.directions[0], box0, box1))
  7512. return false;
  7513. if (!axisOverlap(box1.directions[1], box0, box1))
  7514. return false;
  7515. if (!axisOverlap(box1.directions[2], box0, box1))
  7516. return false;
  7517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7518. return false;
  7519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7520. return false;
  7521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7522. return false;
  7523. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7524. return false;
  7525. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7526. return false;
  7527. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7528. return false;
  7529. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7530. return false;
  7531. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7532. return false;
  7533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7534. return false;
  7535. return true;
  7536. };
  7537. return BoundingInfo;
  7538. })();
  7539. BABYLON.BoundingInfo = BoundingInfo;
  7540. })(BABYLON || (BABYLON = {}));
  7541. var BABYLON;
  7542. (function (BABYLON) {
  7543. var AbstractMesh = (function (_super) {
  7544. __extends(AbstractMesh, _super);
  7545. function AbstractMesh(name, scene) {
  7546. var _this = this;
  7547. _super.call(this, name, scene);
  7548. // Properties
  7549. this.definedFacingForward = true; // orientation for POV movement & rotation
  7550. this.position = new BABYLON.Vector3(0, 0, 0);
  7551. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7552. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7553. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7554. this.visibility = 1.0;
  7555. this.alphaIndex = Number.MAX_VALUE;
  7556. this.infiniteDistance = false;
  7557. this.isVisible = true;
  7558. this.isPickable = true;
  7559. this.showBoundingBox = false;
  7560. this.showSubMeshesBoundingBox = false;
  7561. this.onDispose = null;
  7562. this.isBlocker = false;
  7563. this.renderingGroupId = 0;
  7564. this.receiveShadows = false;
  7565. this.renderOutline = false;
  7566. this.outlineColor = BABYLON.Color3.Red();
  7567. this.outlineWidth = 0.02;
  7568. this.renderOverlay = false;
  7569. this.overlayColor = BABYLON.Color3.Red();
  7570. this.overlayAlpha = 0.5;
  7571. this.hasVertexAlpha = false;
  7572. this.useVertexColors = true;
  7573. this.applyFog = true;
  7574. this.computeBonesUsingShaders = true;
  7575. this.scalingDeterminant = 1;
  7576. this.numBoneInfluencers = 4;
  7577. this.useOctreeForRenderingSelection = true;
  7578. this.useOctreeForPicking = true;
  7579. this.useOctreeForCollisions = true;
  7580. this.layerMask = 0x0FFFFFFF;
  7581. this.alwaysSelectAsActiveMesh = false;
  7582. // Physics
  7583. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7584. // Collisions
  7585. this._checkCollisions = false;
  7586. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7587. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7588. this._collider = new BABYLON.Collider();
  7589. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7590. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7591. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7592. // Edges
  7593. this.edgesWidth = 1;
  7594. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7595. // Cache
  7596. this._localScaling = BABYLON.Matrix.Zero();
  7597. this._localRotation = BABYLON.Matrix.Zero();
  7598. this._localTranslation = BABYLON.Matrix.Zero();
  7599. this._localBillboard = BABYLON.Matrix.Zero();
  7600. this._localPivotScaling = BABYLON.Matrix.Zero();
  7601. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7602. this._localWorld = BABYLON.Matrix.Zero();
  7603. this._worldMatrix = BABYLON.Matrix.Zero();
  7604. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7605. this._absolutePosition = BABYLON.Vector3.Zero();
  7606. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7607. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7608. this._isDirty = false;
  7609. this._pivotMatrix = BABYLON.Matrix.Identity();
  7610. this._isDisposed = false;
  7611. this._renderId = 0;
  7612. this._intersectionsInProgress = new Array();
  7613. this._onAfterWorldMatrixUpdate = new Array();
  7614. this._isWorldMatrixFrozen = false;
  7615. this._unIndexed = false;
  7616. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7617. if (collidedMesh === void 0) { collidedMesh = null; }
  7618. //TODO move this to the collision coordinator!
  7619. if (_this.getScene().workerCollisions)
  7620. newPosition.multiplyInPlace(_this._collider.radius);
  7621. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7622. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7623. _this.position.addInPlace(_this._diffPositionForCollisions);
  7624. }
  7625. if (_this.onCollide && collidedMesh) {
  7626. _this.onCollide(collidedMesh);
  7627. }
  7628. if (_this.onCollisionPositionChange) {
  7629. _this.onCollisionPositionChange(_this.position);
  7630. }
  7631. };
  7632. scene.addMesh(this);
  7633. }
  7634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7635. get: function () {
  7636. return AbstractMesh._BILLBOARDMODE_NONE;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7642. get: function () {
  7643. return AbstractMesh._BILLBOARDMODE_X;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7649. get: function () {
  7650. return AbstractMesh._BILLBOARDMODE_Y;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7656. get: function () {
  7657. return AbstractMesh._BILLBOARDMODE_Z;
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7663. get: function () {
  7664. return AbstractMesh._BILLBOARDMODE_ALL;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. // Methods
  7670. AbstractMesh.prototype.disableEdgesRendering = function () {
  7671. if (this._edgesRenderer !== undefined) {
  7672. this._edgesRenderer.dispose();
  7673. this._edgesRenderer = undefined;
  7674. }
  7675. };
  7676. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7677. if (epsilon === void 0) { epsilon = 0.95; }
  7678. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7679. this.disableEdgesRendering();
  7680. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7681. };
  7682. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7683. get: function () {
  7684. return false;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. AbstractMesh.prototype.getLOD = function (camera) {
  7690. return this;
  7691. };
  7692. AbstractMesh.prototype.getTotalVertices = function () {
  7693. return 0;
  7694. };
  7695. AbstractMesh.prototype.getIndices = function () {
  7696. return null;
  7697. };
  7698. AbstractMesh.prototype.getVerticesData = function (kind) {
  7699. return null;
  7700. };
  7701. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7702. return false;
  7703. };
  7704. AbstractMesh.prototype.getBoundingInfo = function () {
  7705. if (this._masterMesh) {
  7706. return this._masterMesh.getBoundingInfo();
  7707. }
  7708. if (!this._boundingInfo) {
  7709. this._updateBoundingInfo();
  7710. }
  7711. return this._boundingInfo;
  7712. };
  7713. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7714. get: function () {
  7715. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. AbstractMesh.prototype._preActivate = function () {
  7721. };
  7722. AbstractMesh.prototype._activate = function (renderId) {
  7723. this._renderId = renderId;
  7724. };
  7725. AbstractMesh.prototype.getWorldMatrix = function () {
  7726. if (this._masterMesh) {
  7727. return this._masterMesh.getWorldMatrix();
  7728. }
  7729. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7730. this.computeWorldMatrix();
  7731. }
  7732. return this._worldMatrix;
  7733. };
  7734. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7735. get: function () {
  7736. return this._worldMatrix;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7742. get: function () {
  7743. return this._absolutePosition;
  7744. },
  7745. enumerable: true,
  7746. configurable: true
  7747. });
  7748. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7749. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7750. this.computeWorldMatrix(true);
  7751. this._isWorldMatrixFrozen = true;
  7752. };
  7753. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7754. this._isWorldMatrixFrozen = false;
  7755. this.computeWorldMatrix(true);
  7756. };
  7757. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7758. get: function () {
  7759. return this._isWorldMatrixFrozen;
  7760. },
  7761. enumerable: true,
  7762. configurable: true
  7763. });
  7764. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7765. axis.normalize();
  7766. if (!this.rotationQuaternion) {
  7767. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7768. this.rotation = BABYLON.Vector3.Zero();
  7769. }
  7770. var rotationQuaternion;
  7771. if (!space || space === BABYLON.Space.LOCAL) {
  7772. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7773. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7774. }
  7775. else {
  7776. if (this.parent) {
  7777. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7778. invertParentWorldMatrix.invert();
  7779. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7780. }
  7781. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7782. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7783. }
  7784. };
  7785. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7786. var displacementVector = axis.scale(distance);
  7787. if (!space || space === BABYLON.Space.LOCAL) {
  7788. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7789. this.setPositionWithLocalVector(tempV3);
  7790. }
  7791. else {
  7792. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7793. }
  7794. };
  7795. AbstractMesh.prototype.getAbsolutePosition = function () {
  7796. this.computeWorldMatrix();
  7797. return this._absolutePosition;
  7798. };
  7799. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7800. if (!absolutePosition) {
  7801. return;
  7802. }
  7803. var absolutePositionX;
  7804. var absolutePositionY;
  7805. var absolutePositionZ;
  7806. if (absolutePosition.x === undefined) {
  7807. if (arguments.length < 3) {
  7808. return;
  7809. }
  7810. absolutePositionX = arguments[0];
  7811. absolutePositionY = arguments[1];
  7812. absolutePositionZ = arguments[2];
  7813. }
  7814. else {
  7815. absolutePositionX = absolutePosition.x;
  7816. absolutePositionY = absolutePosition.y;
  7817. absolutePositionZ = absolutePosition.z;
  7818. }
  7819. if (this.parent) {
  7820. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7821. invertParentWorldMatrix.invert();
  7822. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7823. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7824. }
  7825. else {
  7826. this.position.x = absolutePositionX;
  7827. this.position.y = absolutePositionY;
  7828. this.position.z = absolutePositionZ;
  7829. }
  7830. };
  7831. // ================================== Point of View Movement =================================
  7832. /**
  7833. * Perform relative position change from the point of view of behind the front of the mesh.
  7834. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7835. * Supports definition of mesh facing forward or backward.
  7836. * @param {number} amountRight
  7837. * @param {number} amountUp
  7838. * @param {number} amountForward
  7839. */
  7840. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7841. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7842. };
  7843. /**
  7844. * Calculate relative position change from the point of view of behind the front of the mesh.
  7845. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7846. * Supports definition of mesh facing forward or backward.
  7847. * @param {number} amountRight
  7848. * @param {number} amountUp
  7849. * @param {number} amountForward
  7850. */
  7851. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7852. var rotMatrix = new BABYLON.Matrix();
  7853. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7854. rotQuaternion.toRotationMatrix(rotMatrix);
  7855. var translationDelta = BABYLON.Vector3.Zero();
  7856. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7857. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7858. return translationDelta;
  7859. };
  7860. // ================================== Point of View Rotation =================================
  7861. /**
  7862. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7863. * Supports definition of mesh facing forward or backward.
  7864. * @param {number} flipBack
  7865. * @param {number} twirlClockwise
  7866. * @param {number} tiltRight
  7867. */
  7868. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7869. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7870. };
  7871. /**
  7872. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7873. * Supports definition of mesh facing forward or backward.
  7874. * @param {number} flipBack
  7875. * @param {number} twirlClockwise
  7876. * @param {number} tiltRight
  7877. */
  7878. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7879. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7880. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7881. };
  7882. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7883. this._pivotMatrix = matrix;
  7884. this._cache.pivotMatrixUpdated = true;
  7885. };
  7886. AbstractMesh.prototype.getPivotMatrix = function () {
  7887. return this._pivotMatrix;
  7888. };
  7889. AbstractMesh.prototype._isSynchronized = function () {
  7890. if (this._isDirty) {
  7891. return false;
  7892. }
  7893. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7894. return false;
  7895. if (this._cache.pivotMatrixUpdated) {
  7896. return false;
  7897. }
  7898. if (this.infiniteDistance) {
  7899. return false;
  7900. }
  7901. if (!this._cache.position.equals(this.position))
  7902. return false;
  7903. if (this.rotationQuaternion) {
  7904. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7905. return false;
  7906. }
  7907. else {
  7908. if (!this._cache.rotation.equals(this.rotation))
  7909. return false;
  7910. }
  7911. if (!this._cache.scaling.equals(this.scaling))
  7912. return false;
  7913. return true;
  7914. };
  7915. AbstractMesh.prototype._initCache = function () {
  7916. _super.prototype._initCache.call(this);
  7917. this._cache.localMatrixUpdated = false;
  7918. this._cache.position = BABYLON.Vector3.Zero();
  7919. this._cache.scaling = BABYLON.Vector3.Zero();
  7920. this._cache.rotation = BABYLON.Vector3.Zero();
  7921. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7922. this._cache.billboardMode = -1;
  7923. };
  7924. AbstractMesh.prototype.markAsDirty = function (property) {
  7925. if (property === "rotation") {
  7926. this.rotationQuaternion = null;
  7927. }
  7928. this._currentRenderId = Number.MAX_VALUE;
  7929. this._isDirty = true;
  7930. };
  7931. AbstractMesh.prototype._updateBoundingInfo = function () {
  7932. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7933. this._boundingInfo._update(this.worldMatrixFromCache);
  7934. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7935. };
  7936. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7937. if (!this.subMeshes) {
  7938. return;
  7939. }
  7940. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7941. var subMesh = this.subMeshes[subIndex];
  7942. if (!subMesh.IsGlobal) {
  7943. subMesh.updateBoundingInfo(matrix);
  7944. }
  7945. }
  7946. };
  7947. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7948. if (this._isWorldMatrixFrozen) {
  7949. return this._worldMatrix;
  7950. }
  7951. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7952. this._currentRenderId = this.getScene().getRenderId();
  7953. return this._worldMatrix;
  7954. }
  7955. this._cache.position.copyFrom(this.position);
  7956. this._cache.scaling.copyFrom(this.scaling);
  7957. this._cache.pivotMatrixUpdated = false;
  7958. this._cache.billboardMode = this.billboardMode;
  7959. this._currentRenderId = this.getScene().getRenderId();
  7960. this._isDirty = false;
  7961. // Scaling
  7962. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7963. // Rotation
  7964. if (this.rotationQuaternion) {
  7965. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7966. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7967. }
  7968. else {
  7969. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7970. this._cache.rotation.copyFrom(this.rotation);
  7971. }
  7972. // Translation
  7973. if (this.infiniteDistance && !this.parent) {
  7974. var camera = this.getScene().activeCamera;
  7975. if (camera) {
  7976. var cameraWorldMatrix = camera.getWorldMatrix();
  7977. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7978. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7979. }
  7980. }
  7981. else {
  7982. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7983. }
  7984. // Composing transformations
  7985. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7986. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7987. // Billboarding
  7988. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7989. var localPosition = this.position.clone();
  7990. var zero = this.getScene().activeCamera.globalPosition.clone();
  7991. if (this.parent && this.parent.position) {
  7992. localPosition.addInPlace(this.parent.position);
  7993. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7994. }
  7995. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7996. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7997. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7998. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7999. zero.y = localPosition.y + 0.001;
  8000. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8001. zero.z = localPosition.z + 0.001;
  8002. }
  8003. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8004. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8005. this._localBillboard.invert();
  8006. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8007. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8008. }
  8009. // Local world
  8010. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8011. // Parent
  8012. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8013. this._markSyncedWithParent();
  8014. if (this._meshToBoneReferal) {
  8015. if (!this._localMeshReferalTransform) {
  8016. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8017. }
  8018. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8019. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8020. }
  8021. else {
  8022. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8023. }
  8024. }
  8025. else {
  8026. this._worldMatrix.copyFrom(this._localWorld);
  8027. }
  8028. // Bounding info
  8029. this._updateBoundingInfo();
  8030. // Absolute position
  8031. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8032. // Callbacks
  8033. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8034. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8035. }
  8036. return this._worldMatrix;
  8037. };
  8038. /**
  8039. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8040. * @param func: callback function to add
  8041. */
  8042. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8043. this._onAfterWorldMatrixUpdate.push(func);
  8044. };
  8045. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8046. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8047. if (index > -1) {
  8048. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8049. }
  8050. };
  8051. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8052. this.computeWorldMatrix();
  8053. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8054. };
  8055. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8056. this.computeWorldMatrix();
  8057. var invLocalWorldMatrix = this._localWorld.clone();
  8058. invLocalWorldMatrix.invert();
  8059. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8060. };
  8061. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8062. this.computeWorldMatrix(true);
  8063. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8064. };
  8065. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8066. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8067. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8068. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8069. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8070. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8071. /// <returns>Mesh oriented towards targetMesh</returns>
  8072. yawCor = yawCor || 0; // default to zero if undefined
  8073. pitchCor = pitchCor || 0;
  8074. rollCor = rollCor || 0;
  8075. var dv = targetPoint.subtract(this.position);
  8076. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8077. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8078. var pitch = Math.atan2(dv.y, len);
  8079. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8080. };
  8081. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8082. this._meshToBoneReferal = affectedMesh;
  8083. this.parent = bone;
  8084. if (bone.getWorldMatrix().determinant() < 0) {
  8085. this.scalingDeterminant *= -1;
  8086. }
  8087. };
  8088. AbstractMesh.prototype.detachFromBone = function () {
  8089. if (this.parent.getWorldMatrix().determinant() < 0) {
  8090. this.scalingDeterminant *= -1;
  8091. }
  8092. this._meshToBoneReferal = null;
  8093. this.parent = null;
  8094. };
  8095. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8096. return this._boundingInfo.isInFrustum(frustumPlanes);
  8097. };
  8098. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8099. if (!camera) {
  8100. camera = this.getScene().activeCamera;
  8101. }
  8102. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8103. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8104. return false;
  8105. }
  8106. return true;
  8107. };
  8108. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8109. if (!this._boundingInfo || !mesh._boundingInfo) {
  8110. return false;
  8111. }
  8112. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8113. };
  8114. AbstractMesh.prototype.intersectsPoint = function (point) {
  8115. if (!this._boundingInfo) {
  8116. return false;
  8117. }
  8118. return this._boundingInfo.intersectsPoint(point);
  8119. };
  8120. // Physics
  8121. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8122. var physicsEngine = this.getScene().getPhysicsEngine();
  8123. if (!physicsEngine) {
  8124. return null;
  8125. }
  8126. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8127. if (impostor.impostor) {
  8128. // Old API
  8129. options = impostor;
  8130. impostor = impostor.impostor;
  8131. }
  8132. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8133. physicsEngine._unregisterMesh(this);
  8134. return null;
  8135. }
  8136. if (!options) {
  8137. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8138. }
  8139. else {
  8140. if (!options.mass && options.mass !== 0)
  8141. options.mass = 0;
  8142. if (!options.friction && options.friction !== 0)
  8143. options.friction = 0.2;
  8144. if (!options.restitution && options.restitution !== 0)
  8145. options.restitution = 0.2;
  8146. }
  8147. this._physicImpostor = impostor;
  8148. this._physicsMass = options.mass;
  8149. this._physicsFriction = options.friction;
  8150. this._physicRestitution = options.restitution;
  8151. return physicsEngine._registerMesh(this, impostor, options);
  8152. };
  8153. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8154. if (!this._physicImpostor) {
  8155. return BABYLON.PhysicsEngine.NoImpostor;
  8156. }
  8157. return this._physicImpostor;
  8158. };
  8159. AbstractMesh.prototype.getPhysicsMass = function () {
  8160. if (!this._physicsMass) {
  8161. return 0;
  8162. }
  8163. return this._physicsMass;
  8164. };
  8165. AbstractMesh.prototype.getPhysicsFriction = function () {
  8166. if (!this._physicsFriction) {
  8167. return 0;
  8168. }
  8169. return this._physicsFriction;
  8170. };
  8171. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8172. if (!this._physicRestitution) {
  8173. return 0;
  8174. }
  8175. return this._physicRestitution;
  8176. };
  8177. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8178. if (!camera) {
  8179. camera = this.getScene().activeCamera;
  8180. }
  8181. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8182. };
  8183. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8184. if (!camera) {
  8185. camera = this.getScene().activeCamera;
  8186. }
  8187. return this.absolutePosition.subtract(camera.position).length();
  8188. };
  8189. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8190. if (!this._physicImpostor) {
  8191. return;
  8192. }
  8193. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8194. };
  8195. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8196. if (!this._physicImpostor) {
  8197. return;
  8198. }
  8199. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8200. };
  8201. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8202. if (!this._physicImpostor) {
  8203. return;
  8204. }
  8205. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8206. };
  8207. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8208. // Collisions
  8209. get: function () {
  8210. return this._checkCollisions;
  8211. },
  8212. set: function (collisionEnabled) {
  8213. this._checkCollisions = collisionEnabled;
  8214. if (this.getScene().workerCollisions) {
  8215. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8216. }
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8222. var globalPosition = this.getAbsolutePosition();
  8223. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8224. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8225. this._collider.radius = this.ellipsoid;
  8226. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8227. };
  8228. // Submeshes octree
  8229. /**
  8230. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8231. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8232. */
  8233. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8234. if (maxCapacity === void 0) { maxCapacity = 64; }
  8235. if (maxDepth === void 0) { maxDepth = 2; }
  8236. if (!this._submeshesOctree) {
  8237. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8238. }
  8239. this.computeWorldMatrix(true);
  8240. // Update octree
  8241. var bbox = this.getBoundingInfo().boundingBox;
  8242. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8243. return this._submeshesOctree;
  8244. };
  8245. // Collisions
  8246. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8247. this._generatePointsArray();
  8248. // Transformation
  8249. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8250. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8251. subMesh._lastColliderWorldVertices = [];
  8252. subMesh._trianglePlanes = [];
  8253. var start = subMesh.verticesStart;
  8254. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8255. for (var i = start; i < end; i++) {
  8256. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8257. }
  8258. }
  8259. // Collide
  8260. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8261. if (collider.collisionFound) {
  8262. collider.collidedMesh = this;
  8263. }
  8264. };
  8265. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8266. var subMeshes;
  8267. var len;
  8268. // Octrees
  8269. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8270. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8271. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8272. len = intersections.length;
  8273. subMeshes = intersections.data;
  8274. }
  8275. else {
  8276. subMeshes = this.subMeshes;
  8277. len = subMeshes.length;
  8278. }
  8279. for (var index = 0; index < len; index++) {
  8280. var subMesh = subMeshes[index];
  8281. // Bounding test
  8282. if (len > 1 && !subMesh._checkCollision(collider))
  8283. continue;
  8284. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8285. }
  8286. };
  8287. AbstractMesh.prototype._checkCollision = function (collider) {
  8288. // Bounding box test
  8289. if (!this._boundingInfo._checkCollision(collider))
  8290. return;
  8291. // Transformation matrix
  8292. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8293. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8294. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8295. };
  8296. // Picking
  8297. AbstractMesh.prototype._generatePointsArray = function () {
  8298. return false;
  8299. };
  8300. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8301. var pickingInfo = new BABYLON.PickingInfo();
  8302. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8303. return pickingInfo;
  8304. }
  8305. if (!this._generatePointsArray()) {
  8306. return pickingInfo;
  8307. }
  8308. var intersectInfo = null;
  8309. // Octrees
  8310. var subMeshes;
  8311. var len;
  8312. if (this._submeshesOctree && this.useOctreeForPicking) {
  8313. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8314. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8315. len = intersections.length;
  8316. subMeshes = intersections.data;
  8317. }
  8318. else {
  8319. subMeshes = this.subMeshes;
  8320. len = subMeshes.length;
  8321. }
  8322. for (var index = 0; index < len; index++) {
  8323. var subMesh = subMeshes[index];
  8324. // Bounding test
  8325. if (len > 1 && !subMesh.canIntersects(ray))
  8326. continue;
  8327. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8328. if (currentIntersectInfo) {
  8329. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8330. intersectInfo = currentIntersectInfo;
  8331. intersectInfo.subMeshId = index;
  8332. if (fastCheck) {
  8333. break;
  8334. }
  8335. }
  8336. }
  8337. }
  8338. if (intersectInfo) {
  8339. // Get picked point
  8340. var world = this.getWorldMatrix();
  8341. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8342. var direction = ray.direction.clone();
  8343. direction = direction.scale(intersectInfo.distance);
  8344. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8345. var pickedPoint = worldOrigin.add(worldDirection);
  8346. // Return result
  8347. pickingInfo.hit = true;
  8348. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8349. pickingInfo.pickedPoint = pickedPoint;
  8350. pickingInfo.pickedMesh = this;
  8351. pickingInfo.bu = intersectInfo.bu;
  8352. pickingInfo.bv = intersectInfo.bv;
  8353. pickingInfo.faceId = intersectInfo.faceId;
  8354. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8355. return pickingInfo;
  8356. }
  8357. return pickingInfo;
  8358. };
  8359. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8360. return null;
  8361. };
  8362. AbstractMesh.prototype.releaseSubMeshes = function () {
  8363. if (this.subMeshes) {
  8364. while (this.subMeshes.length) {
  8365. this.subMeshes[0].dispose();
  8366. }
  8367. }
  8368. else {
  8369. this.subMeshes = new Array();
  8370. }
  8371. };
  8372. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8373. var index;
  8374. // Animations
  8375. this.getScene().stopAnimation(this);
  8376. // Physics
  8377. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8378. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8379. }
  8380. // Intersections in progress
  8381. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8382. var other = this._intersectionsInProgress[index];
  8383. var pos = other._intersectionsInProgress.indexOf(this);
  8384. other._intersectionsInProgress.splice(pos, 1);
  8385. }
  8386. this._intersectionsInProgress = [];
  8387. // Edges
  8388. if (this._edgesRenderer) {
  8389. this._edgesRenderer.dispose();
  8390. this._edgesRenderer = null;
  8391. }
  8392. // SubMeshes
  8393. this.releaseSubMeshes();
  8394. // Remove from scene
  8395. this.getScene().removeMesh(this);
  8396. if (!doNotRecurse) {
  8397. // Particles
  8398. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8399. if (this.getScene().particleSystems[index].emitter === this) {
  8400. this.getScene().particleSystems[index].dispose();
  8401. index--;
  8402. }
  8403. }
  8404. // Children
  8405. var objects = this.getScene().meshes.slice(0);
  8406. for (index = 0; index < objects.length; index++) {
  8407. if (objects[index].parent === this) {
  8408. objects[index].dispose();
  8409. }
  8410. }
  8411. }
  8412. else {
  8413. for (index = 0; index < this.getScene().meshes.length; index++) {
  8414. var obj = this.getScene().meshes[index];
  8415. if (obj.parent === this) {
  8416. obj.parent = null;
  8417. obj.computeWorldMatrix(true);
  8418. }
  8419. }
  8420. }
  8421. this._onAfterWorldMatrixUpdate = [];
  8422. this._isDisposed = true;
  8423. // Callback
  8424. if (this.onDispose) {
  8425. this.onDispose();
  8426. }
  8427. };
  8428. // Statics
  8429. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8430. AbstractMesh._BILLBOARDMODE_X = 1;
  8431. AbstractMesh._BILLBOARDMODE_Y = 2;
  8432. AbstractMesh._BILLBOARDMODE_Z = 4;
  8433. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8434. return AbstractMesh;
  8435. })(BABYLON.Node);
  8436. BABYLON.AbstractMesh = AbstractMesh;
  8437. })(BABYLON || (BABYLON = {}));
  8438. var BABYLON;
  8439. (function (BABYLON) {
  8440. var Light = (function (_super) {
  8441. __extends(Light, _super);
  8442. function Light(name, scene) {
  8443. _super.call(this, name, scene);
  8444. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8445. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8446. this.intensity = 1.0;
  8447. this.range = Number.MAX_VALUE;
  8448. this.includeOnlyWithLayerMask = 0;
  8449. this.includedOnlyMeshes = new Array();
  8450. this.excludedMeshes = new Array();
  8451. this.excludeWithLayerMask = 0;
  8452. this._excludedMeshesIds = new Array();
  8453. this._includedOnlyMeshesIds = new Array();
  8454. scene.addLight(this);
  8455. }
  8456. Light.prototype.getShadowGenerator = function () {
  8457. return this._shadowGenerator;
  8458. };
  8459. Light.prototype.getAbsolutePosition = function () {
  8460. return BABYLON.Vector3.Zero();
  8461. };
  8462. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8463. };
  8464. Light.prototype._getWorldMatrix = function () {
  8465. return BABYLON.Matrix.Identity();
  8466. };
  8467. Light.prototype.canAffectMesh = function (mesh) {
  8468. if (!mesh) {
  8469. return true;
  8470. }
  8471. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8472. return false;
  8473. }
  8474. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8475. return false;
  8476. }
  8477. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8478. return false;
  8479. }
  8480. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8481. return false;
  8482. }
  8483. return true;
  8484. };
  8485. Light.prototype.getWorldMatrix = function () {
  8486. this._currentRenderId = this.getScene().getRenderId();
  8487. var worldMatrix = this._getWorldMatrix();
  8488. if (this.parent && this.parent.getWorldMatrix) {
  8489. if (!this._parentedWorldMatrix) {
  8490. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8491. }
  8492. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8493. this._markSyncedWithParent();
  8494. return this._parentedWorldMatrix;
  8495. }
  8496. return worldMatrix;
  8497. };
  8498. Light.prototype.dispose = function () {
  8499. if (this._shadowGenerator) {
  8500. this._shadowGenerator.dispose();
  8501. this._shadowGenerator = null;
  8502. }
  8503. // Animations
  8504. this.getScene().stopAnimation(this);
  8505. // Remove from scene
  8506. this.getScene().removeLight(this);
  8507. };
  8508. Light.prototype.serialize = function () {
  8509. var serializationObject = {};
  8510. serializationObject.name = this.name;
  8511. serializationObject.id = this.id;
  8512. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8513. if (this.intensity) {
  8514. serializationObject.intensity = this.intensity;
  8515. }
  8516. serializationObject.range = this.range;
  8517. serializationObject.diffuse = this.diffuse.asArray();
  8518. serializationObject.specular = this.specular.asArray();
  8519. return serializationObject;
  8520. };
  8521. Light.Parse = function (parsedLight, scene) {
  8522. var light;
  8523. switch (parsedLight.type) {
  8524. case 0:
  8525. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8526. break;
  8527. case 1:
  8528. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8529. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8530. break;
  8531. case 2:
  8532. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8533. break;
  8534. case 3:
  8535. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8536. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8537. break;
  8538. }
  8539. light.id = parsedLight.id;
  8540. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8541. if (parsedLight.intensity !== undefined) {
  8542. light.intensity = parsedLight.intensity;
  8543. }
  8544. if (parsedLight.range) {
  8545. light.range = parsedLight.range;
  8546. }
  8547. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8548. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8549. if (parsedLight.excludedMeshesIds) {
  8550. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8551. }
  8552. // Parent
  8553. if (parsedLight.parentId) {
  8554. light._waitingParentId = parsedLight.parentId;
  8555. }
  8556. if (parsedLight.includedOnlyMeshesIds) {
  8557. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8558. }
  8559. // Animations
  8560. if (parsedLight.animations) {
  8561. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8562. var parsedAnimation = parsedLight.animations[animationIndex];
  8563. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8564. }
  8565. }
  8566. if (parsedLight.autoAnimate) {
  8567. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8568. }
  8569. return light;
  8570. };
  8571. return Light;
  8572. })(BABYLON.Node);
  8573. BABYLON.Light = Light;
  8574. })(BABYLON || (BABYLON = {}));
  8575. var BABYLON;
  8576. (function (BABYLON) {
  8577. var PointLight = (function (_super) {
  8578. __extends(PointLight, _super);
  8579. function PointLight(name, position, scene) {
  8580. _super.call(this, name, scene);
  8581. this.position = position;
  8582. }
  8583. PointLight.prototype.getAbsolutePosition = function () {
  8584. return this.transformedPosition ? this.transformedPosition : this.position;
  8585. };
  8586. PointLight.prototype.computeTransformedPosition = function () {
  8587. if (this.parent && this.parent.getWorldMatrix) {
  8588. if (!this.transformedPosition) {
  8589. this.transformedPosition = BABYLON.Vector3.Zero();
  8590. }
  8591. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8592. return true;
  8593. }
  8594. return false;
  8595. };
  8596. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8597. if (this.parent && this.parent.getWorldMatrix) {
  8598. this.computeTransformedPosition();
  8599. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8600. return;
  8601. }
  8602. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8603. };
  8604. PointLight.prototype.needCube = function () {
  8605. return true;
  8606. };
  8607. PointLight.prototype.supportsVSM = function () {
  8608. return false;
  8609. };
  8610. PointLight.prototype.needRefreshPerFrame = function () {
  8611. return false;
  8612. };
  8613. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8614. switch (faceIndex) {
  8615. case 0:
  8616. return new BABYLON.Vector3(1, 0, 0);
  8617. case 1:
  8618. return new BABYLON.Vector3(-1, 0, 0);
  8619. case 2:
  8620. return new BABYLON.Vector3(0, -1, 0);
  8621. case 3:
  8622. return new BABYLON.Vector3(0, 1, 0);
  8623. case 4:
  8624. return new BABYLON.Vector3(0, 0, 1);
  8625. case 5:
  8626. return new BABYLON.Vector3(0, 0, -1);
  8627. }
  8628. return BABYLON.Vector3.Zero();
  8629. };
  8630. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8631. var activeCamera = this.getScene().activeCamera;
  8632. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8633. };
  8634. PointLight.prototype._getWorldMatrix = function () {
  8635. if (!this._worldMatrix) {
  8636. this._worldMatrix = BABYLON.Matrix.Identity();
  8637. }
  8638. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8639. return this._worldMatrix;
  8640. };
  8641. PointLight.prototype.serialize = function () {
  8642. var serializationObject = _super.prototype.serialize.call(this);
  8643. serializationObject.type = 0;
  8644. serializationObject.position = this.position.asArray();
  8645. return serializationObject;
  8646. };
  8647. return PointLight;
  8648. })(BABYLON.Light);
  8649. BABYLON.PointLight = PointLight;
  8650. })(BABYLON || (BABYLON = {}));
  8651. var BABYLON;
  8652. (function (BABYLON) {
  8653. var SpotLight = (function (_super) {
  8654. __extends(SpotLight, _super);
  8655. function SpotLight(name, position, direction, angle, exponent, scene) {
  8656. _super.call(this, name, scene);
  8657. this.position = position;
  8658. this.direction = direction;
  8659. this.angle = angle;
  8660. this.exponent = exponent;
  8661. }
  8662. SpotLight.prototype.getAbsolutePosition = function () {
  8663. return this.transformedPosition ? this.transformedPosition : this.position;
  8664. };
  8665. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8666. var activeCamera = this.getScene().activeCamera;
  8667. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8668. };
  8669. SpotLight.prototype.needCube = function () {
  8670. return false;
  8671. };
  8672. SpotLight.prototype.supportsVSM = function () {
  8673. return true;
  8674. };
  8675. SpotLight.prototype.needRefreshPerFrame = function () {
  8676. return false;
  8677. };
  8678. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8679. return this.direction;
  8680. };
  8681. SpotLight.prototype.setDirectionToTarget = function (target) {
  8682. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8683. return this.direction;
  8684. };
  8685. SpotLight.prototype.computeTransformedPosition = function () {
  8686. if (this.parent && this.parent.getWorldMatrix) {
  8687. if (!this.transformedPosition) {
  8688. this.transformedPosition = BABYLON.Vector3.Zero();
  8689. }
  8690. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8691. return true;
  8692. }
  8693. return false;
  8694. };
  8695. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8696. var normalizeDirection;
  8697. if (this.parent && this.parent.getWorldMatrix) {
  8698. if (!this._transformedDirection) {
  8699. this._transformedDirection = BABYLON.Vector3.Zero();
  8700. }
  8701. this.computeTransformedPosition();
  8702. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8703. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8704. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8705. }
  8706. else {
  8707. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8708. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8709. }
  8710. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8711. };
  8712. SpotLight.prototype._getWorldMatrix = function () {
  8713. if (!this._worldMatrix) {
  8714. this._worldMatrix = BABYLON.Matrix.Identity();
  8715. }
  8716. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8717. return this._worldMatrix;
  8718. };
  8719. SpotLight.prototype.serialize = function () {
  8720. var serializationObject = _super.prototype.serialize.call(this);
  8721. serializationObject.type = 2;
  8722. serializationObject.position = this.position.asArray();
  8723. serializationObject.direction = this.position.asArray();
  8724. serializationObject.angle = this.angle;
  8725. serializationObject.exponent = this.exponent;
  8726. return serializationObject;
  8727. };
  8728. return SpotLight;
  8729. })(BABYLON.Light);
  8730. BABYLON.SpotLight = SpotLight;
  8731. })(BABYLON || (BABYLON = {}));
  8732. var BABYLON;
  8733. (function (BABYLON) {
  8734. var HemisphericLight = (function (_super) {
  8735. __extends(HemisphericLight, _super);
  8736. function HemisphericLight(name, direction, scene) {
  8737. _super.call(this, name, scene);
  8738. this.direction = direction;
  8739. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8740. }
  8741. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8742. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8743. return this.direction;
  8744. };
  8745. HemisphericLight.prototype.getShadowGenerator = function () {
  8746. return null;
  8747. };
  8748. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8749. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8750. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8751. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8752. };
  8753. HemisphericLight.prototype._getWorldMatrix = function () {
  8754. if (!this._worldMatrix) {
  8755. this._worldMatrix = BABYLON.Matrix.Identity();
  8756. }
  8757. return this._worldMatrix;
  8758. };
  8759. HemisphericLight.prototype.serialize = function () {
  8760. var serializationObject = _super.prototype.serialize.call(this);
  8761. serializationObject.type = 3;
  8762. serializationObject.direction = this.direction.asArray();
  8763. serializationObject.groundColor = this.groundColor.asArray();
  8764. return serializationObject;
  8765. };
  8766. return HemisphericLight;
  8767. })(BABYLON.Light);
  8768. BABYLON.HemisphericLight = HemisphericLight;
  8769. })(BABYLON || (BABYLON = {}));
  8770. var BABYLON;
  8771. (function (BABYLON) {
  8772. var DirectionalLight = (function (_super) {
  8773. __extends(DirectionalLight, _super);
  8774. function DirectionalLight(name, direction, scene) {
  8775. _super.call(this, name, scene);
  8776. this.direction = direction;
  8777. this.shadowOrthoScale = 0.5;
  8778. this.autoUpdateExtends = true;
  8779. // Cache
  8780. this._orthoLeft = Number.MAX_VALUE;
  8781. this._orthoRight = Number.MIN_VALUE;
  8782. this._orthoTop = Number.MIN_VALUE;
  8783. this._orthoBottom = Number.MAX_VALUE;
  8784. this.position = direction.scale(-1);
  8785. }
  8786. DirectionalLight.prototype.getAbsolutePosition = function () {
  8787. return this.transformedPosition ? this.transformedPosition : this.position;
  8788. };
  8789. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8790. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8791. return this.direction;
  8792. };
  8793. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8794. var activeCamera = this.getScene().activeCamera;
  8795. // Check extends
  8796. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8797. var tempVector3 = BABYLON.Vector3.Zero();
  8798. this._orthoLeft = Number.MAX_VALUE;
  8799. this._orthoRight = Number.MIN_VALUE;
  8800. this._orthoTop = Number.MIN_VALUE;
  8801. this._orthoBottom = Number.MAX_VALUE;
  8802. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8803. var mesh = renderList[meshIndex];
  8804. if (!mesh) {
  8805. continue;
  8806. }
  8807. var boundingInfo = mesh.getBoundingInfo();
  8808. if (!boundingInfo) {
  8809. continue;
  8810. }
  8811. var boundingBox = boundingInfo.boundingBox;
  8812. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8813. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8814. if (tempVector3.x < this._orthoLeft)
  8815. this._orthoLeft = tempVector3.x;
  8816. if (tempVector3.y < this._orthoBottom)
  8817. this._orthoBottom = tempVector3.y;
  8818. if (tempVector3.x > this._orthoRight)
  8819. this._orthoRight = tempVector3.x;
  8820. if (tempVector3.y > this._orthoTop)
  8821. this._orthoTop = tempVector3.y;
  8822. }
  8823. }
  8824. }
  8825. var xOffset = this._orthoRight - this._orthoLeft;
  8826. var yOffset = this._orthoTop - this._orthoBottom;
  8827. 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);
  8828. };
  8829. DirectionalLight.prototype.supportsVSM = function () {
  8830. return true;
  8831. };
  8832. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8833. return true;
  8834. };
  8835. DirectionalLight.prototype.needCube = function () {
  8836. return false;
  8837. };
  8838. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8839. return this.direction;
  8840. };
  8841. DirectionalLight.prototype.computeTransformedPosition = function () {
  8842. if (this.parent && this.parent.getWorldMatrix) {
  8843. if (!this.transformedPosition) {
  8844. this.transformedPosition = BABYLON.Vector3.Zero();
  8845. }
  8846. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8847. return true;
  8848. }
  8849. return false;
  8850. };
  8851. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8852. if (this.parent && this.parent.getWorldMatrix) {
  8853. if (!this._transformedDirection) {
  8854. this._transformedDirection = BABYLON.Vector3.Zero();
  8855. }
  8856. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8857. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8858. return;
  8859. }
  8860. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8861. };
  8862. DirectionalLight.prototype._getWorldMatrix = function () {
  8863. if (!this._worldMatrix) {
  8864. this._worldMatrix = BABYLON.Matrix.Identity();
  8865. }
  8866. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8867. return this._worldMatrix;
  8868. };
  8869. DirectionalLight.prototype.serialize = function () {
  8870. var serializationObject = _super.prototype.serialize.call(this);
  8871. serializationObject.type = 1;
  8872. serializationObject.position = this.position.asArray();
  8873. serializationObject.direction = this.direction.asArray();
  8874. return serializationObject;
  8875. };
  8876. return DirectionalLight;
  8877. })(BABYLON.Light);
  8878. BABYLON.DirectionalLight = DirectionalLight;
  8879. })(BABYLON || (BABYLON = {}));
  8880. var BABYLON;
  8881. (function (BABYLON) {
  8882. var ShadowGenerator = (function () {
  8883. function ShadowGenerator(mapSize, light) {
  8884. var _this = this;
  8885. // Members
  8886. this._filter = ShadowGenerator.FILTER_NONE;
  8887. this.blurScale = 2;
  8888. this._blurBoxOffset = 0;
  8889. this._bias = 0.00005;
  8890. this._lightDirection = BABYLON.Vector3.Zero();
  8891. this.forceBackFacesOnly = false;
  8892. this._darkness = 0;
  8893. this._transparencyShadow = false;
  8894. this._viewMatrix = BABYLON.Matrix.Zero();
  8895. this._projectionMatrix = BABYLON.Matrix.Zero();
  8896. this._transformMatrix = BABYLON.Matrix.Zero();
  8897. this._worldViewProjection = BABYLON.Matrix.Zero();
  8898. this._currentFaceIndex = 0;
  8899. this._currentFaceIndexCache = 0;
  8900. this._light = light;
  8901. this._scene = light.getScene();
  8902. this._mapSize = mapSize;
  8903. light._shadowGenerator = this;
  8904. // Render target
  8905. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8906. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8907. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8908. this._shadowMap.anisotropicFilteringLevel = 1;
  8909. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8910. this._shadowMap.renderParticles = false;
  8911. this._shadowMap.onBeforeRender = function (faceIndex) {
  8912. _this._currentFaceIndex = faceIndex;
  8913. };
  8914. this._shadowMap.onAfterUnbind = function () {
  8915. if (!_this.useBlurVarianceShadowMap) {
  8916. return;
  8917. }
  8918. if (!_this._shadowMap2) {
  8919. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8920. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8921. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8922. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8923. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8924. _this._downSamplePostprocess.onApply = function (effect) {
  8925. effect.setTexture("textureSampler", _this._shadowMap);
  8926. };
  8927. _this.blurBoxOffset = 1;
  8928. }
  8929. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8930. };
  8931. // Custom render function
  8932. var renderSubMesh = function (subMesh) {
  8933. var mesh = subMesh.getRenderingMesh();
  8934. var scene = _this._scene;
  8935. var engine = scene.getEngine();
  8936. // Culling
  8937. engine.setState(subMesh.getMaterial().backFaceCulling);
  8938. // Managing instances
  8939. var batch = mesh._getInstancesRenderList(subMesh._id);
  8940. if (batch.mustReturn) {
  8941. return;
  8942. }
  8943. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  8944. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8945. engine.enableEffect(_this._effect);
  8946. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8947. var material = subMesh.getMaterial();
  8948. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8949. _this._effect.setVector3("lightPosition", _this.getLight().position);
  8950. if (_this.getLight().needCube()) {
  8951. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  8952. }
  8953. // Alpha test
  8954. if (material && material.needAlphaTesting()) {
  8955. var alphaTexture = material.getAlphaTestTexture();
  8956. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8957. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8958. }
  8959. // Bones
  8960. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8961. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8962. }
  8963. if (_this.forceBackFacesOnly) {
  8964. engine.setState(true, 0, false, true);
  8965. }
  8966. // Draw
  8967. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8968. if (_this.forceBackFacesOnly) {
  8969. engine.setState(true, 0, false, false);
  8970. }
  8971. }
  8972. else {
  8973. // Need to reset refresh rate of the shadowMap
  8974. _this._shadowMap.resetRefreshCounter();
  8975. }
  8976. };
  8977. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8978. var index;
  8979. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8980. renderSubMesh(opaqueSubMeshes.data[index]);
  8981. }
  8982. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8983. renderSubMesh(alphaTestSubMeshes.data[index]);
  8984. }
  8985. if (_this._transparencyShadow) {
  8986. for (index = 0; index < transparentSubMeshes.length; index++) {
  8987. renderSubMesh(transparentSubMeshes.data[index]);
  8988. }
  8989. }
  8990. };
  8991. this._shadowMap.onClear = function (engine) {
  8992. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8993. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8994. }
  8995. else {
  8996. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8997. }
  8998. };
  8999. }
  9000. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9001. // Static
  9002. get: function () {
  9003. return ShadowGenerator._FILTER_NONE;
  9004. },
  9005. enumerable: true,
  9006. configurable: true
  9007. });
  9008. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9009. get: function () {
  9010. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9016. get: function () {
  9017. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9023. get: function () {
  9024. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9030. get: function () {
  9031. return this._bias;
  9032. },
  9033. set: function (bias) {
  9034. this._bias = bias;
  9035. },
  9036. enumerable: true,
  9037. configurable: true
  9038. });
  9039. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9040. get: function () {
  9041. return this._blurBoxOffset;
  9042. },
  9043. set: function (value) {
  9044. var _this = this;
  9045. if (this._blurBoxOffset === value) {
  9046. return;
  9047. }
  9048. this._blurBoxOffset = value;
  9049. if (this._boxBlurPostprocess) {
  9050. this._boxBlurPostprocess.dispose();
  9051. }
  9052. 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);
  9053. this._boxBlurPostprocess.onApply = function (effect) {
  9054. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9055. };
  9056. },
  9057. enumerable: true,
  9058. configurable: true
  9059. });
  9060. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9061. get: function () {
  9062. return this._filter;
  9063. },
  9064. set: function (value) {
  9065. if (this._filter === value) {
  9066. return;
  9067. }
  9068. this._filter = value;
  9069. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9070. this._shadowMap.anisotropicFilteringLevel = 16;
  9071. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9072. }
  9073. else {
  9074. this._shadowMap.anisotropicFilteringLevel = 1;
  9075. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9076. }
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9082. get: function () {
  9083. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9084. },
  9085. set: function (value) {
  9086. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9092. get: function () {
  9093. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9094. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9095. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9096. },
  9097. set: function (value) {
  9098. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9104. get: function () {
  9105. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9106. },
  9107. set: function (value) {
  9108. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9114. var defines = [];
  9115. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9116. defines.push("#define VSM");
  9117. }
  9118. if (this.getLight().needCube()) {
  9119. defines.push("#define CUBEMAP");
  9120. }
  9121. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9122. var mesh = subMesh.getMesh();
  9123. var material = subMesh.getMaterial();
  9124. // Alpha test
  9125. if (material && material.needAlphaTesting()) {
  9126. defines.push("#define ALPHATEST");
  9127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9128. attribs.push(BABYLON.VertexBuffer.UVKind);
  9129. defines.push("#define UV1");
  9130. }
  9131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9132. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9133. defines.push("#define UV2");
  9134. }
  9135. }
  9136. // Bones
  9137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9140. if (mesh.numBoneInfluencers > 4) {
  9141. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9142. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9143. }
  9144. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9145. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9146. }
  9147. else {
  9148. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9149. }
  9150. // Instances
  9151. if (useInstances) {
  9152. defines.push("#define INSTANCES");
  9153. attribs.push("world0");
  9154. attribs.push("world1");
  9155. attribs.push("world2");
  9156. attribs.push("world3");
  9157. }
  9158. // Get correct effect
  9159. var join = defines.join("\n");
  9160. if (this._cachedDefines !== join) {
  9161. this._cachedDefines = join;
  9162. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9163. }
  9164. return this._effect.isReady();
  9165. };
  9166. ShadowGenerator.prototype.getShadowMap = function () {
  9167. return this._shadowMap;
  9168. };
  9169. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9170. if (this._shadowMap2) {
  9171. return this._shadowMap2;
  9172. }
  9173. return this._shadowMap;
  9174. };
  9175. ShadowGenerator.prototype.getLight = function () {
  9176. return this._light;
  9177. };
  9178. // Methods
  9179. ShadowGenerator.prototype.getTransformMatrix = function () {
  9180. var scene = this._scene;
  9181. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9182. return this._transformMatrix;
  9183. }
  9184. this._currentRenderID = scene.getRenderId();
  9185. this._currentFaceIndexCache = this._currentFaceIndex;
  9186. var lightPosition = this._light.position;
  9187. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9188. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9189. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9190. }
  9191. if (this._light.computeTransformedPosition()) {
  9192. lightPosition = this._light.transformedPosition;
  9193. }
  9194. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9195. this._cachedPosition = lightPosition.clone();
  9196. this._cachedDirection = this._lightDirection.clone();
  9197. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9198. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9199. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9200. }
  9201. return this._transformMatrix;
  9202. };
  9203. ShadowGenerator.prototype.getDarkness = function () {
  9204. return this._darkness;
  9205. };
  9206. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9207. if (darkness >= 1.0)
  9208. this._darkness = 1.0;
  9209. else if (darkness <= 0.0)
  9210. this._darkness = 0.0;
  9211. else
  9212. this._darkness = darkness;
  9213. };
  9214. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9215. this._transparencyShadow = hasShadow;
  9216. };
  9217. ShadowGenerator.prototype._packHalf = function (depth) {
  9218. var scale = depth * 255.0;
  9219. var fract = scale - Math.floor(scale);
  9220. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9221. };
  9222. ShadowGenerator.prototype.dispose = function () {
  9223. this._shadowMap.dispose();
  9224. if (this._shadowMap2) {
  9225. this._shadowMap2.dispose();
  9226. }
  9227. if (this._downSamplePostprocess) {
  9228. this._downSamplePostprocess.dispose();
  9229. }
  9230. if (this._boxBlurPostprocess) {
  9231. this._boxBlurPostprocess.dispose();
  9232. }
  9233. };
  9234. ShadowGenerator.prototype.serialize = function () {
  9235. var serializationObject = {};
  9236. serializationObject.lightId = this._light.id;
  9237. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9238. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9239. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9240. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9241. serializationObject.renderList = [];
  9242. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9243. var mesh = this.getShadowMap().renderList[meshIndex];
  9244. serializationObject.renderList.push(mesh.id);
  9245. }
  9246. return serializationObject;
  9247. };
  9248. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9249. //casting to point light, as light is missing the position attr and typescript complains.
  9250. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9251. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9252. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9253. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9254. shadowGenerator.getShadowMap().renderList.push(mesh);
  9255. }
  9256. if (parsedShadowGenerator.usePoissonSampling) {
  9257. shadowGenerator.usePoissonSampling = true;
  9258. }
  9259. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9260. shadowGenerator.useVarianceShadowMap = true;
  9261. }
  9262. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9263. shadowGenerator.useBlurVarianceShadowMap = true;
  9264. if (parsedShadowGenerator.blurScale) {
  9265. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9266. }
  9267. if (parsedShadowGenerator.blurBoxOffset) {
  9268. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9269. }
  9270. }
  9271. if (parsedShadowGenerator.bias !== undefined) {
  9272. shadowGenerator.bias = parsedShadowGenerator.bias;
  9273. }
  9274. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9275. return shadowGenerator;
  9276. };
  9277. ShadowGenerator._FILTER_NONE = 0;
  9278. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9279. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9280. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9281. return ShadowGenerator;
  9282. })();
  9283. BABYLON.ShadowGenerator = ShadowGenerator;
  9284. })(BABYLON || (BABYLON = {}));
  9285. var BABYLON;
  9286. (function (BABYLON) {
  9287. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9288. if (boxMin.x > sphereCenter.x + sphereRadius)
  9289. return false;
  9290. if (sphereCenter.x - sphereRadius > boxMax.x)
  9291. return false;
  9292. if (boxMin.y > sphereCenter.y + sphereRadius)
  9293. return false;
  9294. if (sphereCenter.y - sphereRadius > boxMax.y)
  9295. return false;
  9296. if (boxMin.z > sphereCenter.z + sphereRadius)
  9297. return false;
  9298. if (sphereCenter.z - sphereRadius > boxMax.z)
  9299. return false;
  9300. return true;
  9301. };
  9302. var getLowestRoot = function (a, b, c, maxR) {
  9303. var determinant = b * b - 4.0 * a * c;
  9304. var result = { root: 0, found: false };
  9305. if (determinant < 0)
  9306. return result;
  9307. var sqrtD = Math.sqrt(determinant);
  9308. var r1 = (-b - sqrtD) / (2.0 * a);
  9309. var r2 = (-b + sqrtD) / (2.0 * a);
  9310. if (r1 > r2) {
  9311. var temp = r2;
  9312. r2 = r1;
  9313. r1 = temp;
  9314. }
  9315. if (r1 > 0 && r1 < maxR) {
  9316. result.root = r1;
  9317. result.found = true;
  9318. return result;
  9319. }
  9320. if (r2 > 0 && r2 < maxR) {
  9321. result.root = r2;
  9322. result.found = true;
  9323. return result;
  9324. }
  9325. return result;
  9326. };
  9327. var Collider = (function () {
  9328. function Collider() {
  9329. this.radius = new BABYLON.Vector3(1, 1, 1);
  9330. this.retry = 0;
  9331. this.basePointWorld = BABYLON.Vector3.Zero();
  9332. this.velocityWorld = BABYLON.Vector3.Zero();
  9333. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9334. this._collisionPoint = BABYLON.Vector3.Zero();
  9335. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9336. this._tempVector = BABYLON.Vector3.Zero();
  9337. this._tempVector2 = BABYLON.Vector3.Zero();
  9338. this._tempVector3 = BABYLON.Vector3.Zero();
  9339. this._tempVector4 = BABYLON.Vector3.Zero();
  9340. this._edge = BABYLON.Vector3.Zero();
  9341. this._baseToVertex = BABYLON.Vector3.Zero();
  9342. this._destinationPoint = BABYLON.Vector3.Zero();
  9343. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9344. this._displacementVector = BABYLON.Vector3.Zero();
  9345. }
  9346. // Methods
  9347. Collider.prototype._initialize = function (source, dir, e) {
  9348. this.velocity = dir;
  9349. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9350. this.basePoint = source;
  9351. source.multiplyToRef(this.radius, this.basePointWorld);
  9352. dir.multiplyToRef(this.radius, this.velocityWorld);
  9353. this.velocityWorldLength = this.velocityWorld.length();
  9354. this.epsilon = e;
  9355. this.collisionFound = false;
  9356. };
  9357. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9358. pa.subtractToRef(point, this._tempVector);
  9359. pb.subtractToRef(point, this._tempVector2);
  9360. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9361. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9362. if (d < 0)
  9363. return false;
  9364. pc.subtractToRef(point, this._tempVector3);
  9365. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9366. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9367. if (d < 0)
  9368. return false;
  9369. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9370. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9371. return d >= 0;
  9372. };
  9373. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9374. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9375. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9376. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9377. return false;
  9378. }
  9379. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9380. return false;
  9381. return true;
  9382. };
  9383. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9384. var t0;
  9385. var embeddedInPlane = false;
  9386. //defensive programming, actually not needed.
  9387. if (!trianglePlaneArray) {
  9388. trianglePlaneArray = [];
  9389. }
  9390. if (!trianglePlaneArray[faceIndex]) {
  9391. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9392. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9393. }
  9394. var trianglePlane = trianglePlaneArray[faceIndex];
  9395. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9396. return;
  9397. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9398. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9399. if (normalDotVelocity == 0) {
  9400. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9401. return;
  9402. embeddedInPlane = true;
  9403. t0 = 0;
  9404. }
  9405. else {
  9406. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9407. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9408. if (t0 > t1) {
  9409. var temp = t1;
  9410. t1 = t0;
  9411. t0 = temp;
  9412. }
  9413. if (t0 > 1.0 || t1 < 0.0)
  9414. return;
  9415. if (t0 < 0)
  9416. t0 = 0;
  9417. if (t0 > 1.0)
  9418. t0 = 1.0;
  9419. }
  9420. this._collisionPoint.copyFromFloats(0, 0, 0);
  9421. var found = false;
  9422. var t = 1.0;
  9423. if (!embeddedInPlane) {
  9424. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9425. this.velocity.scaleToRef(t0, this._tempVector);
  9426. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9427. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9428. found = true;
  9429. t = t0;
  9430. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9431. }
  9432. }
  9433. if (!found) {
  9434. var velocitySquaredLength = this.velocity.lengthSquared();
  9435. var a = velocitySquaredLength;
  9436. this.basePoint.subtractToRef(p1, this._tempVector);
  9437. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9438. var c = this._tempVector.lengthSquared() - 1.0;
  9439. var lowestRoot = getLowestRoot(a, b, c, t);
  9440. if (lowestRoot.found) {
  9441. t = lowestRoot.root;
  9442. found = true;
  9443. this._collisionPoint.copyFrom(p1);
  9444. }
  9445. this.basePoint.subtractToRef(p2, this._tempVector);
  9446. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9447. c = this._tempVector.lengthSquared() - 1.0;
  9448. lowestRoot = getLowestRoot(a, b, c, t);
  9449. if (lowestRoot.found) {
  9450. t = lowestRoot.root;
  9451. found = true;
  9452. this._collisionPoint.copyFrom(p2);
  9453. }
  9454. this.basePoint.subtractToRef(p3, this._tempVector);
  9455. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9456. c = this._tempVector.lengthSquared() - 1.0;
  9457. lowestRoot = getLowestRoot(a, b, c, t);
  9458. if (lowestRoot.found) {
  9459. t = lowestRoot.root;
  9460. found = true;
  9461. this._collisionPoint.copyFrom(p3);
  9462. }
  9463. p2.subtractToRef(p1, this._edge);
  9464. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9465. var edgeSquaredLength = this._edge.lengthSquared();
  9466. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9467. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9468. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9469. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9470. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9471. lowestRoot = getLowestRoot(a, b, c, t);
  9472. if (lowestRoot.found) {
  9473. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9474. if (f >= 0.0 && f <= 1.0) {
  9475. t = lowestRoot.root;
  9476. found = true;
  9477. this._edge.scaleInPlace(f);
  9478. p1.addToRef(this._edge, this._collisionPoint);
  9479. }
  9480. }
  9481. p3.subtractToRef(p2, this._edge);
  9482. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9483. edgeSquaredLength = this._edge.lengthSquared();
  9484. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9485. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9486. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9487. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9488. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9489. lowestRoot = getLowestRoot(a, b, c, t);
  9490. if (lowestRoot.found) {
  9491. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9492. if (f >= 0.0 && f <= 1.0) {
  9493. t = lowestRoot.root;
  9494. found = true;
  9495. this._edge.scaleInPlace(f);
  9496. p2.addToRef(this._edge, this._collisionPoint);
  9497. }
  9498. }
  9499. p1.subtractToRef(p3, this._edge);
  9500. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9501. edgeSquaredLength = this._edge.lengthSquared();
  9502. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9503. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9504. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9505. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9506. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9507. lowestRoot = getLowestRoot(a, b, c, t);
  9508. if (lowestRoot.found) {
  9509. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9510. if (f >= 0.0 && f <= 1.0) {
  9511. t = lowestRoot.root;
  9512. found = true;
  9513. this._edge.scaleInPlace(f);
  9514. p3.addToRef(this._edge, this._collisionPoint);
  9515. }
  9516. }
  9517. }
  9518. if (found) {
  9519. var distToCollision = t * this.velocity.length();
  9520. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9521. if (!this.intersectionPoint) {
  9522. this.intersectionPoint = this._collisionPoint.clone();
  9523. }
  9524. else {
  9525. this.intersectionPoint.copyFrom(this._collisionPoint);
  9526. }
  9527. this.nearestDistance = distToCollision;
  9528. this.collisionFound = true;
  9529. }
  9530. }
  9531. };
  9532. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9533. for (var i = indexStart; i < indexEnd; i += 3) {
  9534. var p1 = pts[indices[i] - decal];
  9535. var p2 = pts[indices[i + 1] - decal];
  9536. var p3 = pts[indices[i + 2] - decal];
  9537. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9538. }
  9539. };
  9540. Collider.prototype._getResponse = function (pos, vel) {
  9541. pos.addToRef(vel, this._destinationPoint);
  9542. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9543. this.basePoint.addToRef(vel, pos);
  9544. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9545. this._slidePlaneNormal.normalize();
  9546. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9547. pos.addInPlace(this._displacementVector);
  9548. this.intersectionPoint.addInPlace(this._displacementVector);
  9549. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9550. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9551. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9552. };
  9553. return Collider;
  9554. })();
  9555. BABYLON.Collider = Collider;
  9556. })(BABYLON || (BABYLON = {}));
  9557. var BABYLON;
  9558. (function (BABYLON) {
  9559. //WebWorker code will be inserted to this variable.
  9560. BABYLON.CollisionWorker = "";
  9561. (function (WorkerTaskType) {
  9562. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9563. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9564. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9565. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9566. var WorkerTaskType = BABYLON.WorkerTaskType;
  9567. (function (WorkerReplyType) {
  9568. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9569. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9570. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9571. var WorkerReplyType = BABYLON.WorkerReplyType;
  9572. var CollisionCoordinatorWorker = (function () {
  9573. function CollisionCoordinatorWorker() {
  9574. var _this = this;
  9575. this._scaledPosition = BABYLON.Vector3.Zero();
  9576. this._scaledVelocity = BABYLON.Vector3.Zero();
  9577. this.onMeshUpdated = function (mesh) {
  9578. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9579. };
  9580. this.onGeometryUpdated = function (geometry) {
  9581. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9582. };
  9583. this._afterRender = function () {
  9584. if (!_this._init)
  9585. return;
  9586. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9587. return;
  9588. }
  9589. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9590. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9591. if (_this._runningUpdated > 4) {
  9592. return;
  9593. }
  9594. ++_this._runningUpdated;
  9595. var payload = {
  9596. updatedMeshes: _this._addUpdateMeshesList,
  9597. updatedGeometries: _this._addUpdateGeometriesList,
  9598. removedGeometries: _this._toRemoveGeometryArray,
  9599. removedMeshes: _this._toRemoveMeshesArray
  9600. };
  9601. var message = {
  9602. payload: payload,
  9603. taskType: WorkerTaskType.UPDATE
  9604. };
  9605. var serializable = [];
  9606. for (var id in payload.updatedGeometries) {
  9607. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9608. //prepare transferables
  9609. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9610. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9611. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9612. }
  9613. }
  9614. _this._worker.postMessage(message, serializable);
  9615. _this._addUpdateMeshesList = {};
  9616. _this._addUpdateGeometriesList = {};
  9617. _this._toRemoveGeometryArray = [];
  9618. _this._toRemoveMeshesArray = [];
  9619. };
  9620. this._onMessageFromWorker = function (e) {
  9621. var returnData = e.data;
  9622. if (returnData.error != WorkerReplyType.SUCCESS) {
  9623. //TODO what errors can be returned from the worker?
  9624. BABYLON.Tools.Warn("error returned from worker!");
  9625. return;
  9626. }
  9627. switch (returnData.taskType) {
  9628. case WorkerTaskType.INIT:
  9629. _this._init = true;
  9630. //Update the worked with ALL of the scene's current state
  9631. _this._scene.meshes.forEach(function (mesh) {
  9632. _this.onMeshAdded(mesh);
  9633. });
  9634. _this._scene.getGeometries().forEach(function (geometry) {
  9635. _this.onGeometryAdded(geometry);
  9636. });
  9637. break;
  9638. case WorkerTaskType.UPDATE:
  9639. _this._runningUpdated--;
  9640. break;
  9641. case WorkerTaskType.COLLIDE:
  9642. _this._runningCollisionTask = false;
  9643. var returnPayload = returnData.payload;
  9644. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9645. return;
  9646. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9647. //cleanup
  9648. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9649. break;
  9650. }
  9651. };
  9652. this._collisionsCallbackArray = [];
  9653. this._init = false;
  9654. this._runningUpdated = 0;
  9655. this._runningCollisionTask = false;
  9656. this._addUpdateMeshesList = {};
  9657. this._addUpdateGeometriesList = {};
  9658. this._toRemoveGeometryArray = [];
  9659. this._toRemoveMeshesArray = [];
  9660. }
  9661. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9662. if (!this._init)
  9663. return;
  9664. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9665. return;
  9666. position.divideToRef(collider.radius, this._scaledPosition);
  9667. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9668. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9669. var payload = {
  9670. collider: {
  9671. position: this._scaledPosition.asArray(),
  9672. velocity: this._scaledVelocity.asArray(),
  9673. radius: collider.radius.asArray()
  9674. },
  9675. collisionId: collisionIndex,
  9676. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9677. maximumRetry: maximumRetry
  9678. };
  9679. var message = {
  9680. payload: payload,
  9681. taskType: WorkerTaskType.COLLIDE
  9682. };
  9683. this._worker.postMessage(message);
  9684. };
  9685. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9686. this._scene = scene;
  9687. this._scene.registerAfterRender(this._afterRender);
  9688. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9689. this._worker = new Worker(workerUrl);
  9690. this._worker.onmessage = this._onMessageFromWorker;
  9691. var message = {
  9692. payload: {},
  9693. taskType: WorkerTaskType.INIT
  9694. };
  9695. this._worker.postMessage(message);
  9696. };
  9697. CollisionCoordinatorWorker.prototype.destroy = function () {
  9698. this._scene.unregisterAfterRender(this._afterRender);
  9699. this._worker.terminate();
  9700. };
  9701. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9702. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9703. this.onMeshUpdated(mesh);
  9704. };
  9705. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9706. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9707. };
  9708. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9709. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9710. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9711. this.onGeometryUpdated(geometry);
  9712. };
  9713. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9714. this._toRemoveGeometryArray.push(geometry.id);
  9715. };
  9716. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9717. var submeshes = [];
  9718. if (mesh.subMeshes) {
  9719. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9720. return {
  9721. position: idx,
  9722. verticesStart: sm.verticesStart,
  9723. verticesCount: sm.verticesCount,
  9724. indexStart: sm.indexStart,
  9725. indexCount: sm.indexCount,
  9726. hasMaterial: !!sm.getMaterial(),
  9727. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9728. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9729. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9730. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9731. };
  9732. });
  9733. }
  9734. var geometryId = null;
  9735. if (mesh instanceof BABYLON.Mesh) {
  9736. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9737. }
  9738. else if (mesh instanceof BABYLON.InstancedMesh) {
  9739. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9740. }
  9741. return {
  9742. uniqueId: mesh.uniqueId,
  9743. id: mesh.id,
  9744. name: mesh.name,
  9745. geometryId: geometryId,
  9746. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9747. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9748. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9749. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9750. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9751. subMeshes: submeshes,
  9752. checkCollisions: mesh.checkCollisions
  9753. };
  9754. };
  9755. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9756. return {
  9757. id: geometry.id,
  9758. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9759. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9760. indices: new Int32Array(geometry.getIndices() || []),
  9761. };
  9762. };
  9763. return CollisionCoordinatorWorker;
  9764. })();
  9765. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9766. var CollisionCoordinatorLegacy = (function () {
  9767. function CollisionCoordinatorLegacy() {
  9768. this._scaledPosition = BABYLON.Vector3.Zero();
  9769. this._scaledVelocity = BABYLON.Vector3.Zero();
  9770. this._finalPosition = BABYLON.Vector3.Zero();
  9771. }
  9772. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9773. position.divideToRef(collider.radius, this._scaledPosition);
  9774. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9775. collider.collidedMesh = null;
  9776. collider.retry = 0;
  9777. collider.initialVelocity = this._scaledVelocity;
  9778. collider.initialPosition = this._scaledPosition;
  9779. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9780. this._finalPosition.multiplyInPlace(collider.radius);
  9781. //run the callback
  9782. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9783. };
  9784. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9785. this._scene = scene;
  9786. };
  9787. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9788. //Legacy need no destruction method.
  9789. };
  9790. //No update in legacy mode
  9791. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9792. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9793. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9794. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9795. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9796. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9797. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9798. if (excludedMesh === void 0) { excludedMesh = null; }
  9799. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9800. if (collider.retry >= maximumRetry) {
  9801. finalPosition.copyFrom(position);
  9802. return;
  9803. }
  9804. collider._initialize(position, velocity, closeDistance);
  9805. // Check all meshes
  9806. for (var index = 0; index < this._scene.meshes.length; index++) {
  9807. var mesh = this._scene.meshes[index];
  9808. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9809. mesh._checkCollision(collider);
  9810. }
  9811. }
  9812. if (!collider.collisionFound) {
  9813. position.addToRef(velocity, finalPosition);
  9814. return;
  9815. }
  9816. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9817. collider._getResponse(position, velocity);
  9818. }
  9819. if (velocity.length() <= closeDistance) {
  9820. finalPosition.copyFrom(position);
  9821. return;
  9822. }
  9823. collider.retry++;
  9824. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9825. };
  9826. return CollisionCoordinatorLegacy;
  9827. })();
  9828. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9829. })(BABYLON || (BABYLON = {}));
  9830. var BABYLON;
  9831. (function (BABYLON) {
  9832. var VRCameraMetrics = (function () {
  9833. function VRCameraMetrics() {
  9834. this.compensateDistortion = true;
  9835. }
  9836. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9837. get: function () {
  9838. return this.hResolution / (2 * this.vResolution);
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9844. get: function () {
  9845. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9851. get: function () {
  9852. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9853. var h = (4 * meters) / this.hScreenSize;
  9854. return BABYLON.Matrix.Translation(h, 0, 0);
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9860. get: function () {
  9861. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9862. var h = (4 * meters) / this.hScreenSize;
  9863. return BABYLON.Matrix.Translation(-h, 0, 0);
  9864. },
  9865. enumerable: true,
  9866. configurable: true
  9867. });
  9868. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9869. get: function () {
  9870. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9871. },
  9872. enumerable: true,
  9873. configurable: true
  9874. });
  9875. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9876. get: function () {
  9877. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. VRCameraMetrics.GetDefault = function () {
  9883. var result = new VRCameraMetrics();
  9884. result.hResolution = 1280;
  9885. result.vResolution = 800;
  9886. result.hScreenSize = 0.149759993;
  9887. result.vScreenSize = 0.0935999975;
  9888. result.vScreenCenter = 0.0467999987,
  9889. result.eyeToScreenDistance = 0.0410000011;
  9890. result.lensSeparationDistance = 0.0635000020;
  9891. result.interpupillaryDistance = 0.0640000030;
  9892. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9893. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9894. result.postProcessScaleFactor = 1.714605507808412;
  9895. result.lensCenterOffset = 0.151976421;
  9896. return result;
  9897. };
  9898. return VRCameraMetrics;
  9899. })();
  9900. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9901. var Camera = (function (_super) {
  9902. __extends(Camera, _super);
  9903. function Camera(name, position, scene) {
  9904. _super.call(this, name, scene);
  9905. this.position = position;
  9906. // Members
  9907. this.upVector = BABYLON.Vector3.Up();
  9908. this.orthoLeft = null;
  9909. this.orthoRight = null;
  9910. this.orthoBottom = null;
  9911. this.orthoTop = null;
  9912. this.fov = 0.8;
  9913. this.minZ = 1.0;
  9914. this.maxZ = 10000.0;
  9915. this.inertia = 0.9;
  9916. this.mode = Camera.PERSPECTIVE_CAMERA;
  9917. this.isIntermediate = false;
  9918. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9919. this.layerMask = 0x0FFFFFFF;
  9920. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9921. // Camera rig members
  9922. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9923. this._rigCameras = new Array();
  9924. // Cache
  9925. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9926. this._projectionMatrix = new BABYLON.Matrix();
  9927. this._postProcesses = new Array();
  9928. this._postProcessesTakenIndices = [];
  9929. this._activeMeshes = new BABYLON.SmartArray(256);
  9930. this._globalPosition = BABYLON.Vector3.Zero();
  9931. scene.addCamera(this);
  9932. if (!scene.activeCamera) {
  9933. scene.activeCamera = this;
  9934. }
  9935. }
  9936. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9937. get: function () {
  9938. return Camera._PERSPECTIVE_CAMERA;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9944. get: function () {
  9945. return Camera._ORTHOGRAPHIC_CAMERA;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9951. get: function () {
  9952. return Camera._FOVMODE_VERTICAL_FIXED;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9958. get: function () {
  9959. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9965. get: function () {
  9966. return Camera._RIG_MODE_NONE;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9972. get: function () {
  9973. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9979. get: function () {
  9980. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9986. get: function () {
  9987. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9993. get: function () {
  9994. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10000. get: function () {
  10001. return Camera._RIG_MODE_VR;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Camera.prototype, "globalPosition", {
  10007. get: function () {
  10008. return this._globalPosition;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Camera.prototype.getActiveMeshes = function () {
  10014. return this._activeMeshes;
  10015. };
  10016. Camera.prototype.isActiveMesh = function (mesh) {
  10017. return (this._activeMeshes.indexOf(mesh) !== -1);
  10018. };
  10019. //Cache
  10020. Camera.prototype._initCache = function () {
  10021. _super.prototype._initCache.call(this);
  10022. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10023. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10024. this._cache.mode = undefined;
  10025. this._cache.minZ = undefined;
  10026. this._cache.maxZ = undefined;
  10027. this._cache.fov = undefined;
  10028. this._cache.aspectRatio = undefined;
  10029. this._cache.orthoLeft = undefined;
  10030. this._cache.orthoRight = undefined;
  10031. this._cache.orthoBottom = undefined;
  10032. this._cache.orthoTop = undefined;
  10033. this._cache.renderWidth = undefined;
  10034. this._cache.renderHeight = undefined;
  10035. };
  10036. Camera.prototype._updateCache = function (ignoreParentClass) {
  10037. if (!ignoreParentClass) {
  10038. _super.prototype._updateCache.call(this);
  10039. }
  10040. var engine = this.getEngine();
  10041. this._cache.position.copyFrom(this.position);
  10042. this._cache.upVector.copyFrom(this.upVector);
  10043. this._cache.mode = this.mode;
  10044. this._cache.minZ = this.minZ;
  10045. this._cache.maxZ = this.maxZ;
  10046. this._cache.fov = this.fov;
  10047. this._cache.aspectRatio = engine.getAspectRatio(this);
  10048. this._cache.orthoLeft = this.orthoLeft;
  10049. this._cache.orthoRight = this.orthoRight;
  10050. this._cache.orthoBottom = this.orthoBottom;
  10051. this._cache.orthoTop = this.orthoTop;
  10052. this._cache.renderWidth = engine.getRenderWidth();
  10053. this._cache.renderHeight = engine.getRenderHeight();
  10054. };
  10055. Camera.prototype._updateFromScene = function () {
  10056. this.updateCache();
  10057. this._update();
  10058. };
  10059. // Synchronized
  10060. Camera.prototype._isSynchronized = function () {
  10061. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10062. };
  10063. Camera.prototype._isSynchronizedViewMatrix = function () {
  10064. if (!_super.prototype._isSynchronized.call(this))
  10065. return false;
  10066. return this._cache.position.equals(this.position)
  10067. && this._cache.upVector.equals(this.upVector)
  10068. && this.isSynchronizedWithParent();
  10069. };
  10070. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10071. var check = this._cache.mode === this.mode
  10072. && this._cache.minZ === this.minZ
  10073. && this._cache.maxZ === this.maxZ;
  10074. if (!check) {
  10075. return false;
  10076. }
  10077. var engine = this.getEngine();
  10078. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10079. check = this._cache.fov === this.fov
  10080. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10081. }
  10082. else {
  10083. check = this._cache.orthoLeft === this.orthoLeft
  10084. && this._cache.orthoRight === this.orthoRight
  10085. && this._cache.orthoBottom === this.orthoBottom
  10086. && this._cache.orthoTop === this.orthoTop
  10087. && this._cache.renderWidth === engine.getRenderWidth()
  10088. && this._cache.renderHeight === engine.getRenderHeight();
  10089. }
  10090. return check;
  10091. };
  10092. // Controls
  10093. Camera.prototype.attachControl = function (element) {
  10094. };
  10095. Camera.prototype.detachControl = function (element) {
  10096. };
  10097. Camera.prototype._update = function () {
  10098. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10099. this._updateRigCameras();
  10100. }
  10101. this._checkInputs();
  10102. };
  10103. Camera.prototype._checkInputs = function () {
  10104. };
  10105. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10106. if (insertAt === void 0) { insertAt = null; }
  10107. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10108. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10109. return 0;
  10110. }
  10111. if (insertAt == null || insertAt < 0) {
  10112. this._postProcesses.push(postProcess);
  10113. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10114. return this._postProcesses.length - 1;
  10115. }
  10116. var add = 0;
  10117. var i;
  10118. var start;
  10119. if (this._postProcesses[insertAt]) {
  10120. start = this._postProcesses.length - 1;
  10121. for (i = start; i >= insertAt + 1; --i) {
  10122. this._postProcesses[i + 1] = this._postProcesses[i];
  10123. }
  10124. add = 1;
  10125. }
  10126. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10127. if (this._postProcessesTakenIndices[i] < insertAt) {
  10128. continue;
  10129. }
  10130. start = this._postProcessesTakenIndices.length - 1;
  10131. for (var j = start; j >= i; --j) {
  10132. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10133. }
  10134. this._postProcessesTakenIndices[i] = insertAt;
  10135. break;
  10136. }
  10137. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10138. this._postProcessesTakenIndices.push(insertAt);
  10139. }
  10140. var result = insertAt + add;
  10141. this._postProcesses[result] = postProcess;
  10142. return result;
  10143. };
  10144. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10145. if (atIndices === void 0) { atIndices = null; }
  10146. var result = [];
  10147. var i;
  10148. var index;
  10149. if (!atIndices) {
  10150. var length = this._postProcesses.length;
  10151. for (i = 0; i < length; i++) {
  10152. if (this._postProcesses[i] !== postProcess) {
  10153. continue;
  10154. }
  10155. delete this._postProcesses[i];
  10156. index = this._postProcessesTakenIndices.indexOf(i);
  10157. this._postProcessesTakenIndices.splice(index, 1);
  10158. }
  10159. }
  10160. else {
  10161. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10162. for (i = 0; i < atIndices.length; i++) {
  10163. var foundPostProcess = this._postProcesses[atIndices[i]];
  10164. if (foundPostProcess !== postProcess) {
  10165. result.push(i);
  10166. continue;
  10167. }
  10168. delete this._postProcesses[atIndices[i]];
  10169. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10170. this._postProcessesTakenIndices.splice(index, 1);
  10171. }
  10172. }
  10173. return result;
  10174. };
  10175. Camera.prototype.getWorldMatrix = function () {
  10176. if (!this._worldMatrix) {
  10177. this._worldMatrix = BABYLON.Matrix.Identity();
  10178. }
  10179. var viewMatrix = this.getViewMatrix();
  10180. viewMatrix.invertToRef(this._worldMatrix);
  10181. return this._worldMatrix;
  10182. };
  10183. Camera.prototype._getViewMatrix = function () {
  10184. return BABYLON.Matrix.Identity();
  10185. };
  10186. Camera.prototype.getViewMatrix = function (force) {
  10187. this._computedViewMatrix = this._computeViewMatrix(force);
  10188. if (!force && this._isSynchronizedViewMatrix()) {
  10189. return this._computedViewMatrix;
  10190. }
  10191. if (!this.parent || !this.parent.getWorldMatrix) {
  10192. this._globalPosition.copyFrom(this.position);
  10193. }
  10194. else {
  10195. if (!this._worldMatrix) {
  10196. this._worldMatrix = BABYLON.Matrix.Identity();
  10197. }
  10198. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10199. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10200. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10201. this._computedViewMatrix.invert();
  10202. this._markSyncedWithParent();
  10203. }
  10204. this._currentRenderId = this.getScene().getRenderId();
  10205. return this._computedViewMatrix;
  10206. };
  10207. Camera.prototype._computeViewMatrix = function (force) {
  10208. if (!force && this._isSynchronizedViewMatrix()) {
  10209. return this._computedViewMatrix;
  10210. }
  10211. this._computedViewMatrix = this._getViewMatrix();
  10212. this._currentRenderId = this.getScene().getRenderId();
  10213. return this._computedViewMatrix;
  10214. };
  10215. Camera.prototype.getProjectionMatrix = function (force) {
  10216. if (!force && this._isSynchronizedProjectionMatrix()) {
  10217. return this._projectionMatrix;
  10218. }
  10219. var engine = this.getEngine();
  10220. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10221. if (this.minZ <= 0) {
  10222. this.minZ = 0.1;
  10223. }
  10224. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10225. return this._projectionMatrix;
  10226. }
  10227. var halfWidth = engine.getRenderWidth() / 2.0;
  10228. var halfHeight = engine.getRenderHeight() / 2.0;
  10229. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10230. return this._projectionMatrix;
  10231. };
  10232. Camera.prototype.dispose = function () {
  10233. // Animations
  10234. this.getScene().stopAnimation(this);
  10235. // Remove from scene
  10236. this.getScene().removeCamera(this);
  10237. while (this._rigCameras.length > 0) {
  10238. this._rigCameras.pop().dispose();
  10239. }
  10240. // Postprocesses
  10241. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10242. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10243. }
  10244. };
  10245. // ---- Camera rigs section ----
  10246. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10247. while (this._rigCameras.length > 0) {
  10248. this._rigCameras.pop().dispose();
  10249. }
  10250. this.cameraRigMode = mode;
  10251. this._cameraRigParams = {};
  10252. switch (this.cameraRigMode) {
  10253. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10254. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10255. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10256. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10257. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10258. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10259. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10260. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10261. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10262. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10263. break;
  10264. }
  10265. var postProcesses = new Array();
  10266. switch (this.cameraRigMode) {
  10267. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10268. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10269. this._rigCameras[0].isIntermediate = true;
  10270. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10271. postProcesses[1].onApply = function (effect) {
  10272. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10273. };
  10274. break;
  10275. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10276. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10277. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10278. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10279. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10280. var secondCamIndex = 1 - firstCamIndex;
  10281. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10282. this._rigCameras[firstCamIndex].isIntermediate = true;
  10283. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10284. break;
  10285. case Camera.RIG_MODE_VR:
  10286. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10287. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10288. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10289. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10290. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10291. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10292. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10293. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10294. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10295. if (metrics.compensateDistortion) {
  10296. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10297. }
  10298. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10299. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10300. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10301. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10302. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10303. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10304. if (metrics.compensateDistortion) {
  10305. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10306. }
  10307. break;
  10308. }
  10309. this._update();
  10310. };
  10311. Camera.prototype._getVRProjectionMatrix = function () {
  10312. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10313. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10314. return this._projectionMatrix;
  10315. };
  10316. Camera.prototype.setCameraRigParameter = function (name, value) {
  10317. this._cameraRigParams[name] = value;
  10318. //provisionnally:
  10319. if (name === "interaxialDistance") {
  10320. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10321. }
  10322. };
  10323. /**
  10324. * May needs to be overridden by children so sub has required properties to be copied
  10325. */
  10326. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10327. return null;
  10328. };
  10329. /**
  10330. * May needs to be overridden by children
  10331. */
  10332. Camera.prototype._updateRigCameras = function () {
  10333. for (var i = 0; i < this._rigCameras.length; i++) {
  10334. this._rigCameras[i].minZ = this.minZ;
  10335. this._rigCameras[i].maxZ = this.maxZ;
  10336. this._rigCameras[i].fov = this.fov;
  10337. }
  10338. // only update viewport when ANAGLYPH
  10339. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10340. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10341. }
  10342. };
  10343. Camera.prototype.serialize = function () {
  10344. var serializationObject = {};
  10345. serializationObject.name = this.name;
  10346. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10347. serializationObject.id = this.id;
  10348. serializationObject.position = this.position.asArray();
  10349. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10350. // Parent
  10351. if (this.parent) {
  10352. serializationObject.parentId = this.parent.id;
  10353. }
  10354. serializationObject.fov = this.fov;
  10355. serializationObject.minZ = this.minZ;
  10356. serializationObject.maxZ = this.maxZ;
  10357. serializationObject.inertia = this.inertia;
  10358. // Animations
  10359. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10360. // Layer mask
  10361. serializationObject.layerMask = this.layerMask;
  10362. return serializationObject;
  10363. };
  10364. Camera.Parse = function (parsedCamera, scene) {
  10365. var camera;
  10366. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10367. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10368. var interaxial_distance;
  10369. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10370. var alpha = parsedCamera.alpha;
  10371. var beta = parsedCamera.beta;
  10372. var radius = parsedCamera.radius;
  10373. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10374. interaxial_distance = parsedCamera.interaxial_distance;
  10375. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10376. }
  10377. else {
  10378. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10379. }
  10380. }
  10381. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10382. interaxial_distance = parsedCamera.interaxial_distance;
  10383. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10384. }
  10385. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10386. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10387. }
  10388. else if (parsedCamera.type === "FollowCamera") {
  10389. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10390. camera.heightOffset = parsedCamera.heightOffset;
  10391. camera.radius = parsedCamera.radius;
  10392. camera.rotationOffset = parsedCamera.rotationOffset;
  10393. if (lockedTargetMesh)
  10394. camera.target = lockedTargetMesh;
  10395. }
  10396. else if (parsedCamera.type === "GamepadCamera") {
  10397. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10398. }
  10399. else if (parsedCamera.type === "TouchCamera") {
  10400. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10401. }
  10402. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10403. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10404. }
  10405. else if (parsedCamera.type === "WebVRFreeCamera") {
  10406. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10407. }
  10408. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10409. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10410. }
  10411. else {
  10412. // Free Camera is the default value
  10413. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10414. }
  10415. // apply 3d rig, when found
  10416. if (parsedCamera.cameraRigMode) {
  10417. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10418. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10419. }
  10420. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10421. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10422. camera.lockedTarget = lockedTargetMesh;
  10423. }
  10424. camera.id = parsedCamera.id;
  10425. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10426. // Parent
  10427. if (parsedCamera.parentId) {
  10428. camera._waitingParentId = parsedCamera.parentId;
  10429. }
  10430. // Target
  10431. if (parsedCamera.target) {
  10432. if (camera.setTarget) {
  10433. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10434. }
  10435. else {
  10436. //For ArcRotate
  10437. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10438. }
  10439. }
  10440. else {
  10441. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10442. }
  10443. camera.fov = parsedCamera.fov;
  10444. camera.minZ = parsedCamera.minZ;
  10445. camera.maxZ = parsedCamera.maxZ;
  10446. camera.speed = parsedCamera.speed;
  10447. camera.inertia = parsedCamera.inertia;
  10448. camera.checkCollisions = parsedCamera.checkCollisions;
  10449. camera.applyGravity = parsedCamera.applyGravity;
  10450. if (parsedCamera.ellipsoid) {
  10451. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10452. }
  10453. // Animations
  10454. if (parsedCamera.animations) {
  10455. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10456. var parsedAnimation = parsedCamera.animations[animationIndex];
  10457. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10458. }
  10459. }
  10460. if (parsedCamera.autoAnimate) {
  10461. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10462. }
  10463. // Layer Mask
  10464. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10465. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10466. }
  10467. else {
  10468. camera.layerMask = 0x0FFFFFFF;
  10469. }
  10470. return camera;
  10471. };
  10472. // Statics
  10473. Camera._PERSPECTIVE_CAMERA = 0;
  10474. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10475. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10476. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10477. Camera._RIG_MODE_NONE = 0;
  10478. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10480. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10481. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10482. Camera._RIG_MODE_VR = 20;
  10483. return Camera;
  10484. })(BABYLON.Node);
  10485. BABYLON.Camera = Camera;
  10486. })(BABYLON || (BABYLON = {}));
  10487. var BABYLON;
  10488. (function (BABYLON) {
  10489. var TargetCamera = (function (_super) {
  10490. __extends(TargetCamera, _super);
  10491. function TargetCamera(name, position, scene) {
  10492. _super.call(this, name, position, scene);
  10493. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10494. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10495. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10496. this.speed = 2.0;
  10497. this.noRotationConstraint = false;
  10498. this.lockedTarget = null;
  10499. this._currentTarget = BABYLON.Vector3.Zero();
  10500. this._viewMatrix = BABYLON.Matrix.Zero();
  10501. this._camMatrix = BABYLON.Matrix.Zero();
  10502. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10503. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10504. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10505. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10506. this._lookAtTemp = BABYLON.Matrix.Zero();
  10507. this._tempMatrix = BABYLON.Matrix.Zero();
  10508. }
  10509. TargetCamera.prototype.getFrontPosition = function (distance) {
  10510. var direction = this.getTarget().subtract(this.position);
  10511. direction.normalize();
  10512. direction.scaleInPlace(distance);
  10513. return this.globalPosition.add(direction);
  10514. };
  10515. TargetCamera.prototype._getLockedTargetPosition = function () {
  10516. if (!this.lockedTarget) {
  10517. return null;
  10518. }
  10519. return this.lockedTarget.position || this.lockedTarget;
  10520. };
  10521. // Cache
  10522. TargetCamera.prototype._initCache = function () {
  10523. _super.prototype._initCache.call(this);
  10524. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10525. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10526. };
  10527. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10528. if (!ignoreParentClass) {
  10529. _super.prototype._updateCache.call(this);
  10530. }
  10531. var lockedTargetPosition = this._getLockedTargetPosition();
  10532. if (!lockedTargetPosition) {
  10533. this._cache.lockedTarget = null;
  10534. }
  10535. else {
  10536. if (!this._cache.lockedTarget) {
  10537. this._cache.lockedTarget = lockedTargetPosition.clone();
  10538. }
  10539. else {
  10540. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10541. }
  10542. }
  10543. this._cache.rotation.copyFrom(this.rotation);
  10544. };
  10545. // Synchronized
  10546. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10547. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10548. return false;
  10549. }
  10550. var lockedTargetPosition = this._getLockedTargetPosition();
  10551. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10552. && this._cache.rotation.equals(this.rotation);
  10553. };
  10554. // Methods
  10555. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10556. var engine = this.getEngine();
  10557. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10558. };
  10559. // Target
  10560. TargetCamera.prototype.setTarget = function (target) {
  10561. this.upVector.normalize();
  10562. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10563. this._camMatrix.invert();
  10564. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10565. var vDir = target.subtract(this.position);
  10566. if (vDir.x >= 0.0) {
  10567. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10568. }
  10569. else {
  10570. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10571. }
  10572. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10573. if (isNaN(this.rotation.x)) {
  10574. this.rotation.x = 0;
  10575. }
  10576. if (isNaN(this.rotation.y)) {
  10577. this.rotation.y = 0;
  10578. }
  10579. if (isNaN(this.rotation.z)) {
  10580. this.rotation.z = 0;
  10581. }
  10582. };
  10583. TargetCamera.prototype.getTarget = function () {
  10584. return this._currentTarget;
  10585. };
  10586. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10587. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10588. };
  10589. TargetCamera.prototype._updatePosition = function () {
  10590. this.position.addInPlace(this.cameraDirection);
  10591. };
  10592. TargetCamera.prototype._checkInputs = function () {
  10593. var needToMove = this._decideIfNeedsToMove();
  10594. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10595. // Move
  10596. if (needToMove) {
  10597. this._updatePosition();
  10598. }
  10599. // Rotate
  10600. if (needToRotate) {
  10601. this.rotation.x += this.cameraRotation.x;
  10602. this.rotation.y += this.cameraRotation.y;
  10603. if (!this.noRotationConstraint) {
  10604. var limit = (Math.PI / 2) * 0.95;
  10605. if (this.rotation.x > limit)
  10606. this.rotation.x = limit;
  10607. if (this.rotation.x < -limit)
  10608. this.rotation.x = -limit;
  10609. }
  10610. }
  10611. // Inertia
  10612. if (needToMove) {
  10613. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10614. this.cameraDirection.x = 0;
  10615. }
  10616. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10617. this.cameraDirection.y = 0;
  10618. }
  10619. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10620. this.cameraDirection.z = 0;
  10621. }
  10622. this.cameraDirection.scaleInPlace(this.inertia);
  10623. }
  10624. if (needToRotate) {
  10625. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10626. this.cameraRotation.x = 0;
  10627. }
  10628. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10629. this.cameraRotation.y = 0;
  10630. }
  10631. this.cameraRotation.scaleInPlace(this.inertia);
  10632. }
  10633. _super.prototype._checkInputs.call(this);
  10634. };
  10635. TargetCamera.prototype._getViewMatrix = function () {
  10636. if (!this.lockedTarget) {
  10637. // Compute
  10638. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10639. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10640. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10641. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10642. this._lookAtTemp.invert();
  10643. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10644. }
  10645. else {
  10646. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10647. }
  10648. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10649. // Computing target and final matrix
  10650. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10651. }
  10652. else {
  10653. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10654. }
  10655. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10656. return this._viewMatrix;
  10657. };
  10658. TargetCamera.prototype._getVRViewMatrix = function () {
  10659. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10660. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10661. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10662. // Computing target and final matrix
  10663. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10664. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10665. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10666. return this._viewMatrix;
  10667. };
  10668. /**
  10669. * @override
  10670. * Override Camera.createRigCamera
  10671. */
  10672. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10673. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10674. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10675. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10676. rigCamera._cameraRigParams = {};
  10677. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10678. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10679. }
  10680. return rigCamera;
  10681. }
  10682. return null;
  10683. };
  10684. /**
  10685. * @override
  10686. * Override Camera._updateRigCameras
  10687. */
  10688. TargetCamera.prototype._updateRigCameras = function () {
  10689. switch (this.cameraRigMode) {
  10690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10694. case BABYLON.Camera.RIG_MODE_VR:
  10695. var camLeft = this._rigCameras[0];
  10696. var camRight = this._rigCameras[1];
  10697. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10698. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10699. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10700. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10701. camLeft.position.copyFrom(this.position);
  10702. camRight.position.copyFrom(this.position);
  10703. }
  10704. else {
  10705. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10706. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10707. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10708. camLeft.setTarget(this.getTarget());
  10709. camRight.setTarget(this.getTarget());
  10710. }
  10711. break;
  10712. }
  10713. _super.prototype._updateRigCameras.call(this);
  10714. };
  10715. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10716. if (!this._rigCamTransformMatrix) {
  10717. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10718. }
  10719. var target = this.getTarget();
  10720. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10721. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10722. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10723. };
  10724. TargetCamera.prototype.serialize = function () {
  10725. var serializationObject = _super.prototype.serialize.call(this);
  10726. serializationObject.speed = this.speed;
  10727. if (this.rotation) {
  10728. serializationObject.rotation = this.rotation.asArray();
  10729. }
  10730. if (this.lockedTarget && this.lockedTarget.id) {
  10731. serializationObject.lockedTargetId = this.lockedTarget.id;
  10732. }
  10733. return serializationObject;
  10734. };
  10735. return TargetCamera;
  10736. })(BABYLON.Camera);
  10737. BABYLON.TargetCamera = TargetCamera;
  10738. })(BABYLON || (BABYLON = {}));
  10739. var BABYLON;
  10740. (function (BABYLON) {
  10741. var FreeCamera = (function (_super) {
  10742. __extends(FreeCamera, _super);
  10743. function FreeCamera(name, position, scene) {
  10744. var _this = this;
  10745. _super.call(this, name, position, scene);
  10746. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10747. this.keysUp = [38];
  10748. this.keysDown = [40];
  10749. this.keysLeft = [37];
  10750. this.keysRight = [39];
  10751. this.checkCollisions = false;
  10752. this.applyGravity = false;
  10753. this.angularSensibility = 2000.0;
  10754. this._keys = [];
  10755. this._collider = new BABYLON.Collider();
  10756. this._needMoveForGravity = false;
  10757. this._oldPosition = BABYLON.Vector3.Zero();
  10758. this._diffPosition = BABYLON.Vector3.Zero();
  10759. this._newPosition = BABYLON.Vector3.Zero();
  10760. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10761. if (collidedMesh === void 0) { collidedMesh = null; }
  10762. //TODO move this to the collision coordinator!
  10763. if (_this.getScene().workerCollisions)
  10764. newPosition.multiplyInPlace(_this._collider.radius);
  10765. var updatePosition = function (newPos) {
  10766. _this._newPosition.copyFrom(newPos);
  10767. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10768. var oldPosition = _this.position.clone();
  10769. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10770. _this.position.addInPlace(_this._diffPosition);
  10771. if (_this.onCollide && collidedMesh) {
  10772. _this.onCollide(collidedMesh);
  10773. }
  10774. }
  10775. };
  10776. updatePosition(newPosition);
  10777. };
  10778. }
  10779. // Controls
  10780. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10781. var _this = this;
  10782. var previousPosition;
  10783. var engine = this.getEngine();
  10784. if (this._attachedElement) {
  10785. return;
  10786. }
  10787. this._attachedElement = element;
  10788. if (this._onMouseDown === undefined) {
  10789. this._onMouseDown = function (evt) {
  10790. previousPosition = {
  10791. x: evt.clientX,
  10792. y: evt.clientY
  10793. };
  10794. if (!noPreventDefault) {
  10795. evt.preventDefault();
  10796. }
  10797. };
  10798. this._onMouseUp = function (evt) {
  10799. previousPosition = null;
  10800. if (!noPreventDefault) {
  10801. evt.preventDefault();
  10802. }
  10803. };
  10804. this._onMouseOut = function (evt) {
  10805. previousPosition = null;
  10806. _this._keys = [];
  10807. if (!noPreventDefault) {
  10808. evt.preventDefault();
  10809. }
  10810. };
  10811. this._onMouseMove = function (evt) {
  10812. if (!previousPosition && !engine.isPointerLock) {
  10813. return;
  10814. }
  10815. var offsetX;
  10816. var offsetY;
  10817. if (!engine.isPointerLock) {
  10818. offsetX = evt.clientX - previousPosition.x;
  10819. offsetY = evt.clientY - previousPosition.y;
  10820. }
  10821. else {
  10822. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10823. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10824. }
  10825. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10826. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10827. previousPosition = {
  10828. x: evt.clientX,
  10829. y: evt.clientY
  10830. };
  10831. if (!noPreventDefault) {
  10832. evt.preventDefault();
  10833. }
  10834. };
  10835. this._onKeyDown = function (evt) {
  10836. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10837. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10838. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10839. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10840. var index = _this._keys.indexOf(evt.keyCode);
  10841. if (index === -1) {
  10842. _this._keys.push(evt.keyCode);
  10843. }
  10844. if (!noPreventDefault) {
  10845. evt.preventDefault();
  10846. }
  10847. }
  10848. };
  10849. this._onKeyUp = function (evt) {
  10850. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10851. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10852. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10853. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10854. var index = _this._keys.indexOf(evt.keyCode);
  10855. if (index >= 0) {
  10856. _this._keys.splice(index, 1);
  10857. }
  10858. if (!noPreventDefault) {
  10859. evt.preventDefault();
  10860. }
  10861. }
  10862. };
  10863. this._onLostFocus = function () {
  10864. _this._keys = [];
  10865. };
  10866. this._reset = function () {
  10867. _this._keys = [];
  10868. previousPosition = null;
  10869. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10870. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10871. };
  10872. }
  10873. element.addEventListener("mousedown", this._onMouseDown, false);
  10874. element.addEventListener("mouseup", this._onMouseUp, false);
  10875. element.addEventListener("mouseout", this._onMouseOut, false);
  10876. element.addEventListener("mousemove", this._onMouseMove, false);
  10877. BABYLON.Tools.RegisterTopRootEvents([
  10878. { name: "keydown", handler: this._onKeyDown },
  10879. { name: "keyup", handler: this._onKeyUp },
  10880. { name: "blur", handler: this._onLostFocus }
  10881. ]);
  10882. };
  10883. FreeCamera.prototype.detachControl = function (element) {
  10884. if (this._attachedElement !== element) {
  10885. return;
  10886. }
  10887. element.removeEventListener("mousedown", this._onMouseDown);
  10888. element.removeEventListener("mouseup", this._onMouseUp);
  10889. element.removeEventListener("mouseout", this._onMouseOut);
  10890. element.removeEventListener("mousemove", this._onMouseMove);
  10891. BABYLON.Tools.UnregisterTopRootEvents([
  10892. { name: "keydown", handler: this._onKeyDown },
  10893. { name: "keyup", handler: this._onKeyUp },
  10894. { name: "blur", handler: this._onLostFocus }
  10895. ]);
  10896. this._attachedElement = null;
  10897. if (this._reset) {
  10898. this._reset();
  10899. }
  10900. };
  10901. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10902. var globalPosition;
  10903. if (this.parent) {
  10904. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10905. }
  10906. else {
  10907. globalPosition = this.position;
  10908. }
  10909. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10910. this._collider.radius = this.ellipsoid;
  10911. //no need for clone, as long as gravity is not on.
  10912. var actualVelocity = velocity;
  10913. //add gravity to the velocity to prevent the dual-collision checking
  10914. if (this.applyGravity) {
  10915. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10916. actualVelocity = velocity.add(this.getScene().gravity);
  10917. }
  10918. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10919. };
  10920. FreeCamera.prototype._checkInputs = function () {
  10921. if (!this._localDirection) {
  10922. this._localDirection = BABYLON.Vector3.Zero();
  10923. this._transformedDirection = BABYLON.Vector3.Zero();
  10924. }
  10925. // Keyboard
  10926. for (var index = 0; index < this._keys.length; index++) {
  10927. var keyCode = this._keys[index];
  10928. var speed = this._computeLocalCameraSpeed();
  10929. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10930. this._localDirection.copyFromFloats(-speed, 0, 0);
  10931. }
  10932. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10933. this._localDirection.copyFromFloats(0, 0, speed);
  10934. }
  10935. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10936. this._localDirection.copyFromFloats(speed, 0, 0);
  10937. }
  10938. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10939. this._localDirection.copyFromFloats(0, 0, -speed);
  10940. }
  10941. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10942. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10943. this.cameraDirection.addInPlace(this._transformedDirection);
  10944. }
  10945. _super.prototype._checkInputs.call(this);
  10946. };
  10947. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10948. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10949. };
  10950. FreeCamera.prototype._updatePosition = function () {
  10951. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10952. this._collideWithWorld(this.cameraDirection);
  10953. }
  10954. else {
  10955. this.position.addInPlace(this.cameraDirection);
  10956. }
  10957. };
  10958. FreeCamera.prototype.serialize = function () {
  10959. var serializationObject = _super.prototype.serialize.call(this);
  10960. serializationObject.checkCollisions = this.checkCollisions;
  10961. serializationObject.applyGravity = this.applyGravity;
  10962. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10963. return serializationObject;
  10964. };
  10965. return FreeCamera;
  10966. })(BABYLON.TargetCamera);
  10967. BABYLON.FreeCamera = FreeCamera;
  10968. })(BABYLON || (BABYLON = {}));
  10969. var BABYLON;
  10970. (function (BABYLON) {
  10971. var FollowCamera = (function (_super) {
  10972. __extends(FollowCamera, _super);
  10973. function FollowCamera(name, position, scene) {
  10974. _super.call(this, name, position, scene);
  10975. this.radius = 12;
  10976. this.rotationOffset = 0;
  10977. this.heightOffset = 4;
  10978. this.cameraAcceleration = 0.05;
  10979. this.maxCameraSpeed = 20;
  10980. }
  10981. FollowCamera.prototype.getRadians = function (degrees) {
  10982. return degrees * Math.PI / 180;
  10983. };
  10984. FollowCamera.prototype.follow = function (cameraTarget) {
  10985. if (!cameraTarget)
  10986. return;
  10987. var yRotation;
  10988. if (cameraTarget.rotationQuaternion) {
  10989. var rotMatrix = new BABYLON.Matrix();
  10990. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10991. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10992. }
  10993. else {
  10994. yRotation = cameraTarget.rotation.y;
  10995. }
  10996. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10997. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10998. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10999. var dx = targetX - this.position.x;
  11000. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11001. var dz = (targetZ) - this.position.z;
  11002. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11003. var vy = dy * this.cameraAcceleration;
  11004. var vz = dz * this.cameraAcceleration * 2;
  11005. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11006. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11007. }
  11008. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11009. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11010. }
  11011. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11012. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11013. }
  11014. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11015. this.setTarget(cameraTarget.position);
  11016. };
  11017. FollowCamera.prototype._checkInputs = function () {
  11018. _super.prototype._checkInputs.call(this);
  11019. this.follow(this.target);
  11020. };
  11021. FollowCamera.prototype.serialize = function () {
  11022. var serializationObject = _super.prototype.serialize.call(this);
  11023. serializationObject.radius = this.radius;
  11024. serializationObject.heightOffset = this.heightOffset;
  11025. serializationObject.rotationOffset = this.rotationOffset;
  11026. return serializationObject;
  11027. };
  11028. return FollowCamera;
  11029. })(BABYLON.TargetCamera);
  11030. BABYLON.FollowCamera = FollowCamera;
  11031. var ArcFollowCamera = (function (_super) {
  11032. __extends(ArcFollowCamera, _super);
  11033. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11034. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11035. this.alpha = alpha;
  11036. this.beta = beta;
  11037. this.radius = radius;
  11038. this.target = target;
  11039. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11040. this.follow();
  11041. }
  11042. ArcFollowCamera.prototype.follow = function () {
  11043. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11044. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11045. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11046. this.position = this.target.position.add(this._cartesianCoordinates);
  11047. this.setTarget(this.target.position);
  11048. };
  11049. ArcFollowCamera.prototype._checkInputs = function () {
  11050. _super.prototype._checkInputs.call(this);
  11051. this.follow();
  11052. };
  11053. ArcFollowCamera.prototype.serialize = function () {
  11054. var serializationObject = _super.prototype.serialize.call(this);
  11055. serializationObject.radius = this.radius;
  11056. return serializationObject;
  11057. };
  11058. return ArcFollowCamera;
  11059. })(BABYLON.TargetCamera);
  11060. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11061. })(BABYLON || (BABYLON = {}));
  11062. var BABYLON;
  11063. (function (BABYLON) {
  11064. // We're mainly based on the logic defined into the FreeCamera code
  11065. var TouchCamera = (function (_super) {
  11066. __extends(TouchCamera, _super);
  11067. function TouchCamera(name, position, scene) {
  11068. _super.call(this, name, position, scene);
  11069. this._offsetX = null;
  11070. this._offsetY = null;
  11071. this._pointerCount = 0;
  11072. this._pointerPressed = [];
  11073. this.angularSensibility = 200000.0;
  11074. this.moveSensibility = 500.0;
  11075. }
  11076. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11077. var _this = this;
  11078. var previousPosition;
  11079. if (this._attachedCanvas) {
  11080. return;
  11081. }
  11082. this._attachedCanvas = canvas;
  11083. if (this._onPointerDown === undefined) {
  11084. this._onPointerDown = function (evt) {
  11085. if (!noPreventDefault) {
  11086. evt.preventDefault();
  11087. }
  11088. _this._pointerPressed.push(evt.pointerId);
  11089. if (_this._pointerPressed.length !== 1) {
  11090. return;
  11091. }
  11092. previousPosition = {
  11093. x: evt.clientX,
  11094. y: evt.clientY
  11095. };
  11096. };
  11097. this._onPointerUp = function (evt) {
  11098. if (!noPreventDefault) {
  11099. evt.preventDefault();
  11100. }
  11101. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11102. if (index === -1) {
  11103. return;
  11104. }
  11105. _this._pointerPressed.splice(index, 1);
  11106. if (index != 0) {
  11107. return;
  11108. }
  11109. previousPosition = null;
  11110. _this._offsetX = null;
  11111. _this._offsetY = null;
  11112. };
  11113. this._onPointerMove = function (evt) {
  11114. if (!noPreventDefault) {
  11115. evt.preventDefault();
  11116. }
  11117. if (!previousPosition) {
  11118. return;
  11119. }
  11120. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11121. if (index != 0) {
  11122. return;
  11123. }
  11124. _this._offsetX = evt.clientX - previousPosition.x;
  11125. _this._offsetY = -(evt.clientY - previousPosition.y);
  11126. };
  11127. this._onLostFocus = function () {
  11128. _this._offsetX = null;
  11129. _this._offsetY = null;
  11130. };
  11131. }
  11132. canvas.addEventListener("pointerdown", this._onPointerDown);
  11133. canvas.addEventListener("pointerup", this._onPointerUp);
  11134. canvas.addEventListener("pointerout", this._onPointerUp);
  11135. canvas.addEventListener("pointermove", this._onPointerMove);
  11136. BABYLON.Tools.RegisterTopRootEvents([
  11137. { name: "blur", handler: this._onLostFocus }
  11138. ]);
  11139. };
  11140. TouchCamera.prototype.detachControl = function (canvas) {
  11141. if (this._attachedCanvas !== canvas) {
  11142. return;
  11143. }
  11144. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11145. canvas.removeEventListener("pointerup", this._onPointerUp);
  11146. canvas.removeEventListener("pointerout", this._onPointerUp);
  11147. canvas.removeEventListener("pointermove", this._onPointerMove);
  11148. BABYLON.Tools.UnregisterTopRootEvents([
  11149. { name: "blur", handler: this._onLostFocus }
  11150. ]);
  11151. this._attachedCanvas = null;
  11152. };
  11153. TouchCamera.prototype._checkInputs = function () {
  11154. if (this._offsetX) {
  11155. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11156. if (this._pointerPressed.length > 1) {
  11157. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11158. }
  11159. else {
  11160. var speed = this._computeLocalCameraSpeed();
  11161. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11162. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11163. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11164. }
  11165. }
  11166. _super.prototype._checkInputs.call(this);
  11167. };
  11168. return TouchCamera;
  11169. })(BABYLON.FreeCamera);
  11170. BABYLON.TouchCamera = TouchCamera;
  11171. })(BABYLON || (BABYLON = {}));
  11172. var BABYLON;
  11173. (function (BABYLON) {
  11174. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11175. var ArcRotateCamera = (function (_super) {
  11176. __extends(ArcRotateCamera, _super);
  11177. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11178. var _this = this;
  11179. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11180. this.alpha = alpha;
  11181. this.beta = beta;
  11182. this.radius = radius;
  11183. this.target = target;
  11184. this.inertialAlphaOffset = 0;
  11185. this.inertialBetaOffset = 0;
  11186. this.inertialRadiusOffset = 0;
  11187. this.lowerAlphaLimit = null;
  11188. this.upperAlphaLimit = null;
  11189. this.lowerBetaLimit = 0.01;
  11190. this.upperBetaLimit = Math.PI;
  11191. this.lowerRadiusLimit = null;
  11192. this.upperRadiusLimit = null;
  11193. this.angularSensibilityX = 1000.0;
  11194. this.angularSensibilityY = 1000.0;
  11195. this.wheelPrecision = 3.0;
  11196. this.pinchPrecision = 2.0;
  11197. this.panningSensibility = 50.0;
  11198. this.inertialPanningX = 0;
  11199. this.inertialPanningY = 0;
  11200. this.keysUp = [38];
  11201. this.keysDown = [40];
  11202. this.keysLeft = [37];
  11203. this.keysRight = [39];
  11204. this.zoomOnFactor = 1;
  11205. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11206. this.pinchInwards = true;
  11207. this.allowUpsideDown = true;
  11208. this._keys = [];
  11209. this._viewMatrix = new BABYLON.Matrix();
  11210. this._isRightClick = false;
  11211. this._isCtrlPushed = false;
  11212. this.checkCollisions = false;
  11213. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11214. this._collider = new BABYLON.Collider();
  11215. this._previousPosition = BABYLON.Vector3.Zero();
  11216. this._collisionVelocity = BABYLON.Vector3.Zero();
  11217. this._newPosition = BABYLON.Vector3.Zero();
  11218. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11219. if (collidedMesh === void 0) { collidedMesh = null; }
  11220. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11221. newPosition.multiplyInPlace(_this._collider.radius);
  11222. }
  11223. if (!collidedMesh) {
  11224. _this._previousPosition.copyFrom(_this.position);
  11225. }
  11226. else {
  11227. _this.setPosition(newPosition);
  11228. if (_this.onCollide) {
  11229. _this.onCollide(collidedMesh);
  11230. }
  11231. }
  11232. // Recompute because of constraints
  11233. var cosa = Math.cos(_this.alpha);
  11234. var sina = Math.sin(_this.alpha);
  11235. var cosb = Math.cos(_this.beta);
  11236. var sinb = Math.sin(_this.beta);
  11237. var target = _this._getTargetPosition();
  11238. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11239. _this.position.copyFrom(_this._newPosition);
  11240. var up = _this.upVector;
  11241. if (_this.allowUpsideDown && _this.beta < 0) {
  11242. up = up.clone();
  11243. up = up.negate();
  11244. }
  11245. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11246. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11247. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11248. _this._collisionTriggered = false;
  11249. };
  11250. if (!this.target) {
  11251. this.target = BABYLON.Vector3.Zero();
  11252. }
  11253. this.getViewMatrix();
  11254. }
  11255. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11256. //deprecated angularSensibility support
  11257. get: function () {
  11258. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11259. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11260. },
  11261. //deprecated angularSensibility support
  11262. set: function (value) {
  11263. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11264. this.angularSensibilityX = value;
  11265. this.angularSensibilityY = value;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. ArcRotateCamera.prototype._getTargetPosition = function () {
  11271. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11272. };
  11273. // Cache
  11274. ArcRotateCamera.prototype._initCache = function () {
  11275. _super.prototype._initCache.call(this);
  11276. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11277. this._cache.alpha = undefined;
  11278. this._cache.beta = undefined;
  11279. this._cache.radius = undefined;
  11280. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11281. };
  11282. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11283. if (!ignoreParentClass) {
  11284. _super.prototype._updateCache.call(this);
  11285. }
  11286. this._cache.target.copyFrom(this._getTargetPosition());
  11287. this._cache.alpha = this.alpha;
  11288. this._cache.beta = this.beta;
  11289. this._cache.radius = this.radius;
  11290. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11291. };
  11292. // Synchronized
  11293. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11294. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11295. return false;
  11296. return this._cache.target.equals(this._getTargetPosition())
  11297. && this._cache.alpha === this.alpha
  11298. && this._cache.beta === this.beta
  11299. && this._cache.radius === this.radius
  11300. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11301. };
  11302. // Methods
  11303. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11304. var _this = this;
  11305. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11306. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11307. var previousPinchDistance = 0;
  11308. var pointers = new BABYLON.SmartCollection();
  11309. if (this._attachedElement) {
  11310. return;
  11311. }
  11312. this._attachedElement = element;
  11313. var engine = this.getEngine();
  11314. if (this._onPointerDown === undefined) {
  11315. this._onPointerDown = function (evt) {
  11316. // Manage panning with right click
  11317. _this._isRightClick = evt.button === 2;
  11318. // manage pointers
  11319. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11320. cacheSoloPointer = pointers.item(evt.pointerId);
  11321. if (!noPreventDefault) {
  11322. evt.preventDefault();
  11323. }
  11324. };
  11325. this._onPointerUp = function (evt) {
  11326. cacheSoloPointer = null;
  11327. previousPinchDistance = 0;
  11328. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11329. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11330. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11331. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11332. pointers.empty();
  11333. if (!noPreventDefault) {
  11334. evt.preventDefault();
  11335. }
  11336. };
  11337. this._onContextMenu = function (evt) {
  11338. evt.preventDefault();
  11339. };
  11340. this._onPointerMove = function (evt) {
  11341. if (!noPreventDefault) {
  11342. evt.preventDefault();
  11343. }
  11344. switch (pointers.count) {
  11345. case 1:
  11346. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11347. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11348. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11349. }
  11350. else {
  11351. var offsetX = evt.clientX - cacheSoloPointer.x;
  11352. var offsetY = evt.clientY - cacheSoloPointer.y;
  11353. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11354. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11355. }
  11356. cacheSoloPointer.x = evt.clientX;
  11357. cacheSoloPointer.y = evt.clientY;
  11358. break;
  11359. case 2:
  11360. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11361. pointers.item(evt.pointerId).x = evt.clientX;
  11362. pointers.item(evt.pointerId).y = evt.clientY;
  11363. var direction = _this.pinchInwards ? 1 : -1;
  11364. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11365. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11366. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11367. if (previousPinchDistance === 0) {
  11368. previousPinchDistance = pinchSquaredDistance;
  11369. return;
  11370. }
  11371. if (pinchSquaredDistance !== previousPinchDistance) {
  11372. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11373. previousPinchDistance = pinchSquaredDistance;
  11374. }
  11375. break;
  11376. default:
  11377. if (pointers.item(evt.pointerId)) {
  11378. pointers.item(evt.pointerId).x = evt.clientX;
  11379. pointers.item(evt.pointerId).y = evt.clientY;
  11380. }
  11381. }
  11382. };
  11383. this._onMouseMove = function (evt) {
  11384. if (!engine.isPointerLock) {
  11385. return;
  11386. }
  11387. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11388. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11389. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11390. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11391. if (!noPreventDefault) {
  11392. evt.preventDefault();
  11393. }
  11394. };
  11395. this._wheel = function (event) {
  11396. var delta = 0;
  11397. if (event.wheelDelta) {
  11398. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11399. }
  11400. else if (event.detail) {
  11401. delta = -event.detail / _this.wheelPrecision;
  11402. }
  11403. if (delta)
  11404. _this.inertialRadiusOffset += delta;
  11405. if (event.preventDefault) {
  11406. if (!noPreventDefault) {
  11407. event.preventDefault();
  11408. }
  11409. }
  11410. };
  11411. this._onKeyDown = function (evt) {
  11412. _this._isCtrlPushed = evt.ctrlKey;
  11413. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11414. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11415. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11416. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11417. var index = _this._keys.indexOf(evt.keyCode);
  11418. if (index === -1) {
  11419. _this._keys.push(evt.keyCode);
  11420. }
  11421. if (evt.preventDefault) {
  11422. if (!noPreventDefault) {
  11423. evt.preventDefault();
  11424. }
  11425. }
  11426. }
  11427. };
  11428. this._onKeyUp = function (evt) {
  11429. _this._isCtrlPushed = evt.ctrlKey;
  11430. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11431. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11432. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11433. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11434. var index = _this._keys.indexOf(evt.keyCode);
  11435. if (index >= 0) {
  11436. _this._keys.splice(index, 1);
  11437. }
  11438. if (evt.preventDefault) {
  11439. if (!noPreventDefault) {
  11440. evt.preventDefault();
  11441. }
  11442. }
  11443. }
  11444. };
  11445. this._onLostFocus = function () {
  11446. _this._keys = [];
  11447. pointers.empty();
  11448. previousPinchDistance = 0;
  11449. cacheSoloPointer = null;
  11450. };
  11451. this._onGestureStart = function (e) {
  11452. if (window.MSGesture === undefined) {
  11453. return;
  11454. }
  11455. if (!_this._MSGestureHandler) {
  11456. _this._MSGestureHandler = new MSGesture();
  11457. _this._MSGestureHandler.target = element;
  11458. }
  11459. _this._MSGestureHandler.addPointer(e.pointerId);
  11460. };
  11461. this._onGesture = function (e) {
  11462. _this.radius *= e.scale;
  11463. if (e.preventDefault) {
  11464. if (!noPreventDefault) {
  11465. e.stopPropagation();
  11466. e.preventDefault();
  11467. }
  11468. }
  11469. };
  11470. this._reset = function () {
  11471. _this._keys = [];
  11472. _this.inertialAlphaOffset = 0;
  11473. _this.inertialBetaOffset = 0;
  11474. _this.inertialRadiusOffset = 0;
  11475. pointers.empty();
  11476. previousPinchDistance = 0;
  11477. cacheSoloPointer = null;
  11478. };
  11479. }
  11480. if (!useCtrlForPanning) {
  11481. element.addEventListener("contextmenu", this._onContextMenu, false);
  11482. }
  11483. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11484. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11485. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11486. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11487. element.addEventListener("mousemove", this._onMouseMove, false);
  11488. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11489. element.addEventListener("MSGestureChange", this._onGesture, false);
  11490. element.addEventListener('mousewheel', this._wheel, false);
  11491. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11492. BABYLON.Tools.RegisterTopRootEvents([
  11493. { name: "keydown", handler: this._onKeyDown },
  11494. { name: "keyup", handler: this._onKeyUp },
  11495. { name: "blur", handler: this._onLostFocus }
  11496. ]);
  11497. };
  11498. ArcRotateCamera.prototype.detachControl = function (element) {
  11499. if (this._attachedElement !== element) {
  11500. return;
  11501. }
  11502. element.removeEventListener("contextmenu", this._onContextMenu);
  11503. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11504. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11505. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11506. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11507. element.removeEventListener("mousemove", this._onMouseMove);
  11508. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11509. element.removeEventListener("MSGestureChange", this._onGesture);
  11510. element.removeEventListener('mousewheel', this._wheel);
  11511. element.removeEventListener('DOMMouseScroll', this._wheel);
  11512. BABYLON.Tools.UnregisterTopRootEvents([
  11513. { name: "keydown", handler: this._onKeyDown },
  11514. { name: "keyup", handler: this._onKeyUp },
  11515. { name: "blur", handler: this._onLostFocus }
  11516. ]);
  11517. this._MSGestureHandler = null;
  11518. this._attachedElement = null;
  11519. if (this._reset) {
  11520. this._reset();
  11521. }
  11522. };
  11523. ArcRotateCamera.prototype._checkInputs = function () {
  11524. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11525. if (this._collisionTriggered) {
  11526. return;
  11527. }
  11528. // Keyboard
  11529. for (var index = 0; index < this._keys.length; index++) {
  11530. var keyCode = this._keys[index];
  11531. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11532. this.inertialAlphaOffset -= 0.01;
  11533. }
  11534. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11535. this.inertialBetaOffset -= 0.01;
  11536. }
  11537. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11538. this.inertialAlphaOffset += 0.01;
  11539. }
  11540. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11541. this.inertialBetaOffset += 0.01;
  11542. }
  11543. }
  11544. // Inertia
  11545. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11546. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11547. this.beta += this.inertialBetaOffset;
  11548. this.radius -= this.inertialRadiusOffset;
  11549. this.inertialAlphaOffset *= this.inertia;
  11550. this.inertialBetaOffset *= this.inertia;
  11551. this.inertialRadiusOffset *= this.inertia;
  11552. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11553. this.inertialAlphaOffset = 0;
  11554. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11555. this.inertialBetaOffset = 0;
  11556. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11557. this.inertialRadiusOffset = 0;
  11558. }
  11559. // Panning inertia
  11560. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11561. if (!this._localDirection) {
  11562. this._localDirection = BABYLON.Vector3.Zero();
  11563. this._transformedDirection = BABYLON.Vector3.Zero();
  11564. }
  11565. this.inertialPanningX *= this.inertia;
  11566. this.inertialPanningY *= this.inertia;
  11567. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11568. this.inertialPanningX = 0;
  11569. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11570. this.inertialPanningY = 0;
  11571. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11572. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11573. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11574. this.target.addInPlace(this._transformedDirection);
  11575. }
  11576. // Limits
  11577. this._checkLimits();
  11578. _super.prototype._checkInputs.call(this);
  11579. };
  11580. ArcRotateCamera.prototype._checkLimits = function () {
  11581. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11582. if (this.allowUpsideDown && this.beta > Math.PI) {
  11583. this.beta = this.beta - (2 * Math.PI);
  11584. }
  11585. }
  11586. else {
  11587. if (this.beta < this.lowerBetaLimit) {
  11588. this.beta = this.lowerBetaLimit;
  11589. }
  11590. }
  11591. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11592. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11593. this.beta = this.beta + (2 * Math.PI);
  11594. }
  11595. }
  11596. else {
  11597. if (this.beta > this.upperBetaLimit) {
  11598. this.beta = this.upperBetaLimit;
  11599. }
  11600. }
  11601. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11602. this.alpha = this.lowerAlphaLimit;
  11603. }
  11604. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11605. this.alpha = this.upperAlphaLimit;
  11606. }
  11607. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11608. this.radius = this.lowerRadiusLimit;
  11609. }
  11610. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11611. this.radius = this.upperRadiusLimit;
  11612. }
  11613. };
  11614. ArcRotateCamera.prototype.setPosition = function (position) {
  11615. if (this.position.equals(position)) {
  11616. return;
  11617. }
  11618. var radiusv3 = position.subtract(this._getTargetPosition());
  11619. this.radius = radiusv3.length();
  11620. // Alpha
  11621. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11622. if (radiusv3.z < 0) {
  11623. this.alpha = 2 * Math.PI - this.alpha;
  11624. }
  11625. // Beta
  11626. this.beta = Math.acos(radiusv3.y / this.radius);
  11627. this._checkLimits();
  11628. };
  11629. ArcRotateCamera.prototype.setTarget = function (target) {
  11630. this.target = target;
  11631. };
  11632. ArcRotateCamera.prototype._getViewMatrix = function () {
  11633. // Compute
  11634. var cosa = Math.cos(this.alpha);
  11635. var sina = Math.sin(this.alpha);
  11636. var cosb = Math.cos(this.beta);
  11637. var sinb = Math.sin(this.beta);
  11638. var target = this._getTargetPosition();
  11639. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11640. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11641. this._collider.radius = this.collisionRadius;
  11642. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11643. this._collisionTriggered = true;
  11644. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11645. }
  11646. else {
  11647. this.position.copyFrom(this._newPosition);
  11648. var up = this.upVector;
  11649. if (this.allowUpsideDown && this.beta < 0) {
  11650. up = up.clone();
  11651. up = up.negate();
  11652. }
  11653. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11654. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11655. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11656. }
  11657. return this._viewMatrix;
  11658. };
  11659. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11660. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11661. meshes = meshes || this.getScene().meshes;
  11662. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11663. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11664. this.radius = distance * this.zoomOnFactor;
  11665. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11666. };
  11667. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11668. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11669. var meshesOrMinMaxVector;
  11670. var distance;
  11671. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11672. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11673. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11674. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11675. }
  11676. else {
  11677. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11678. distance = meshesOrMinMaxVectorAndDistance.distance;
  11679. }
  11680. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11681. if (!doNotUpdateMaxZ) {
  11682. this.maxZ = distance * 2;
  11683. }
  11684. };
  11685. /**
  11686. * @override
  11687. * Override Camera.createRigCamera
  11688. */
  11689. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11690. switch (this.cameraRigMode) {
  11691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11695. case BABYLON.Camera.RIG_MODE_VR:
  11696. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11697. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11698. }
  11699. return null;
  11700. };
  11701. /**
  11702. * @override
  11703. * Override Camera._updateRigCameras
  11704. */
  11705. ArcRotateCamera.prototype._updateRigCameras = function () {
  11706. switch (this.cameraRigMode) {
  11707. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11708. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11709. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11711. case BABYLON.Camera.RIG_MODE_VR:
  11712. var camLeft = this._rigCameras[0];
  11713. var camRight = this._rigCameras[1];
  11714. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11715. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11716. camLeft.beta = camRight.beta = this.beta;
  11717. camLeft.radius = camRight.radius = this.radius;
  11718. break;
  11719. }
  11720. _super.prototype._updateRigCameras.call(this);
  11721. };
  11722. ArcRotateCamera.prototype.serialize = function () {
  11723. var serializationObject = _super.prototype.serialize.call(this);
  11724. if (this.target instanceof BABYLON.Vector3) {
  11725. serializationObject.target = this.target.asArray();
  11726. }
  11727. if (this.target && this.target.id) {
  11728. serializationObject.lockedTargetId = this.target.id;
  11729. }
  11730. serializationObject.checkCollisions = this.checkCollisions;
  11731. serializationObject.alpha = this.alpha;
  11732. serializationObject.beta = this.beta;
  11733. serializationObject.radius = this.radius;
  11734. return serializationObject;
  11735. };
  11736. return ArcRotateCamera;
  11737. })(BABYLON.TargetCamera);
  11738. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11739. })(BABYLON || (BABYLON = {}));
  11740. var BABYLON;
  11741. (function (BABYLON) {
  11742. var RenderingManager = (function () {
  11743. function RenderingManager(scene) {
  11744. this._renderingGroups = new Array();
  11745. this._scene = scene;
  11746. }
  11747. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11748. if (this._scene._activeParticleSystems.length === 0) {
  11749. return;
  11750. }
  11751. // Particles
  11752. var activeCamera = this._scene.activeCamera;
  11753. var beforeParticlesDate = BABYLON.Tools.Now;
  11754. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11755. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11756. if (particleSystem.renderingGroupId !== index) {
  11757. continue;
  11758. }
  11759. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11760. continue;
  11761. }
  11762. this._clearDepthBuffer();
  11763. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11764. this._scene._activeParticles += particleSystem.render();
  11765. }
  11766. }
  11767. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11768. };
  11769. RenderingManager.prototype._renderSprites = function (index) {
  11770. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11771. return;
  11772. }
  11773. // Sprites
  11774. var activeCamera = this._scene.activeCamera;
  11775. var beforeSpritessDate = BABYLON.Tools.Now;
  11776. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11777. var spriteManager = this._scene.spriteManagers[id];
  11778. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11779. this._clearDepthBuffer();
  11780. spriteManager.render();
  11781. }
  11782. }
  11783. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11784. };
  11785. RenderingManager.prototype._clearDepthBuffer = function () {
  11786. if (this._depthBufferAlreadyCleaned) {
  11787. return;
  11788. }
  11789. this._scene.getEngine().clear(0, false, true);
  11790. this._depthBufferAlreadyCleaned = true;
  11791. };
  11792. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11793. if (this._currentRenderSprites) {
  11794. this._renderSprites(this._currentIndex);
  11795. }
  11796. if (this._currentRenderParticles) {
  11797. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11798. }
  11799. };
  11800. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11801. this._currentActiveMeshes = activeMeshes;
  11802. this._currentRenderParticles = renderParticles;
  11803. this._currentRenderSprites = renderSprites;
  11804. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11805. this._depthBufferAlreadyCleaned = index == 0;
  11806. var renderingGroup = this._renderingGroups[index];
  11807. var needToStepBack = false;
  11808. this._currentIndex = index;
  11809. if (renderingGroup) {
  11810. this._clearDepthBuffer();
  11811. if (!renderingGroup.onBeforeTransparentRendering) {
  11812. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11813. }
  11814. if (!renderingGroup.render(customRenderFunction)) {
  11815. this._renderingGroups.splice(index, 1);
  11816. needToStepBack = true;
  11817. this._renderSpritesAndParticles();
  11818. }
  11819. }
  11820. else {
  11821. this._renderSpritesAndParticles();
  11822. }
  11823. if (needToStepBack) {
  11824. index--;
  11825. }
  11826. }
  11827. };
  11828. RenderingManager.prototype.reset = function () {
  11829. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11830. if (renderingGroup) {
  11831. renderingGroup.prepare();
  11832. }
  11833. });
  11834. };
  11835. RenderingManager.prototype.dispatch = function (subMesh) {
  11836. var mesh = subMesh.getMesh();
  11837. var renderingGroupId = mesh.renderingGroupId || 0;
  11838. if (!this._renderingGroups[renderingGroupId]) {
  11839. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11840. }
  11841. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11842. };
  11843. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11844. return RenderingManager;
  11845. })();
  11846. BABYLON.RenderingManager = RenderingManager;
  11847. })(BABYLON || (BABYLON = {}));
  11848. var BABYLON;
  11849. (function (BABYLON) {
  11850. var RenderingGroup = (function () {
  11851. function RenderingGroup(index, scene) {
  11852. this.index = index;
  11853. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11854. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11855. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11856. this._scene = scene;
  11857. }
  11858. RenderingGroup.prototype.render = function (customRenderFunction) {
  11859. if (customRenderFunction) {
  11860. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11861. return true;
  11862. }
  11863. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11864. if (this.onBeforeTransparentRendering) {
  11865. this.onBeforeTransparentRendering();
  11866. }
  11867. return false;
  11868. }
  11869. var engine = this._scene.getEngine();
  11870. // Opaque
  11871. var subIndex;
  11872. var submesh;
  11873. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11874. submesh = this._opaqueSubMeshes.data[subIndex];
  11875. submesh.render(false);
  11876. }
  11877. // Alpha test
  11878. engine.setAlphaTesting(true);
  11879. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11880. submesh = this._alphaTestSubMeshes.data[subIndex];
  11881. submesh.render(false);
  11882. }
  11883. engine.setAlphaTesting(false);
  11884. if (this.onBeforeTransparentRendering) {
  11885. this.onBeforeTransparentRendering();
  11886. }
  11887. // Transparent
  11888. if (this._transparentSubMeshes.length) {
  11889. // Sorting
  11890. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11891. submesh = this._transparentSubMeshes.data[subIndex];
  11892. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11893. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11894. }
  11895. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11896. sortedArray.sort(function (a, b) {
  11897. // Alpha index first
  11898. if (a._alphaIndex > b._alphaIndex) {
  11899. return 1;
  11900. }
  11901. if (a._alphaIndex < b._alphaIndex) {
  11902. return -1;
  11903. }
  11904. // Then distance to camera
  11905. if (a._distanceToCamera < b._distanceToCamera) {
  11906. return 1;
  11907. }
  11908. if (a._distanceToCamera > b._distanceToCamera) {
  11909. return -1;
  11910. }
  11911. return 0;
  11912. });
  11913. // Rendering
  11914. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11915. submesh = sortedArray[subIndex];
  11916. submesh.render(true);
  11917. }
  11918. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11919. }
  11920. return true;
  11921. };
  11922. RenderingGroup.prototype.prepare = function () {
  11923. this._opaqueSubMeshes.reset();
  11924. this._transparentSubMeshes.reset();
  11925. this._alphaTestSubMeshes.reset();
  11926. };
  11927. RenderingGroup.prototype.dispatch = function (subMesh) {
  11928. var material = subMesh.getMaterial();
  11929. var mesh = subMesh.getMesh();
  11930. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11931. this._transparentSubMeshes.push(subMesh);
  11932. }
  11933. else if (material.needAlphaTesting()) {
  11934. this._alphaTestSubMeshes.push(subMesh);
  11935. }
  11936. else {
  11937. this._opaqueSubMeshes.push(subMesh); // Opaque
  11938. }
  11939. };
  11940. return RenderingGroup;
  11941. })();
  11942. BABYLON.RenderingGroup = RenderingGroup;
  11943. })(BABYLON || (BABYLON = {}));
  11944. var BABYLON;
  11945. (function (BABYLON) {
  11946. /**
  11947. * Represents a scene to be rendered by the engine.
  11948. * @see http://doc.babylonjs.com/page.php?p=21911
  11949. */
  11950. var Scene = (function () {
  11951. /**
  11952. * @constructor
  11953. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11954. */
  11955. function Scene(engine) {
  11956. // Members
  11957. this.autoClear = true;
  11958. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11959. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11960. this.forceWireframe = false;
  11961. this.forcePointsCloud = false;
  11962. this.forceShowBoundingBoxes = false;
  11963. this.animationsEnabled = true;
  11964. this.constantlyUpdateMeshUnderPointer = false;
  11965. 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
  11966. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  11967. this._startingPointerTime = 0;
  11968. // Fog
  11969. /**
  11970. * is fog enabled on this scene.
  11971. * @type {boolean}
  11972. */
  11973. this.fogEnabled = true;
  11974. this.fogMode = Scene.FOGMODE_NONE;
  11975. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11976. this.fogDensity = 0.1;
  11977. this.fogStart = 0;
  11978. this.fogEnd = 1000.0;
  11979. // Lights
  11980. /**
  11981. * is shadow enabled on this scene.
  11982. * @type {boolean}
  11983. */
  11984. this.shadowsEnabled = true;
  11985. /**
  11986. * is light enabled on this scene.
  11987. * @type {boolean}
  11988. */
  11989. this.lightsEnabled = true;
  11990. /**
  11991. * All of the lights added to this scene.
  11992. * @see BABYLON.Light
  11993. * @type {BABYLON.Light[]}
  11994. */
  11995. this.lights = new Array();
  11996. // Cameras
  11997. /**
  11998. * All of the cameras added to this scene.
  11999. * @see BABYLON.Camera
  12000. * @type {BABYLON.Camera[]}
  12001. */
  12002. this.cameras = new Array();
  12003. this.activeCameras = new Array();
  12004. // Meshes
  12005. /**
  12006. * All of the (abstract) meshes added to this scene.
  12007. * @see BABYLON.AbstractMesh
  12008. * @type {BABYLON.AbstractMesh[]}
  12009. */
  12010. this.meshes = new Array();
  12011. // Geometries
  12012. this._geometries = new Array();
  12013. this.materials = new Array();
  12014. this.multiMaterials = new Array();
  12015. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12016. // Textures
  12017. this.texturesEnabled = true;
  12018. this.textures = new Array();
  12019. // Particles
  12020. this.particlesEnabled = true;
  12021. this.particleSystems = new Array();
  12022. // Sprites
  12023. this.spritesEnabled = true;
  12024. this.spriteManagers = new Array();
  12025. // Layers
  12026. this.layers = new Array();
  12027. // Skeletons
  12028. this.skeletonsEnabled = true;
  12029. this.skeletons = new Array();
  12030. // Lens flares
  12031. this.lensFlaresEnabled = true;
  12032. this.lensFlareSystems = new Array();
  12033. // Collisions
  12034. this.collisionsEnabled = true;
  12035. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12036. // Postprocesses
  12037. this.postProcessesEnabled = true;
  12038. // Customs render targets
  12039. this.renderTargetsEnabled = true;
  12040. this.dumpNextRenderTargets = false;
  12041. this.customRenderTargets = new Array();
  12042. // Imported meshes
  12043. this.importedMeshesFiles = new Array();
  12044. // Probes
  12045. this.probesEnabled = true;
  12046. this.reflectionProbes = new Array();
  12047. this._actionManagers = new Array();
  12048. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12049. // Procedural textures
  12050. this.proceduralTexturesEnabled = true;
  12051. this._proceduralTextures = new Array();
  12052. this.soundTracks = new Array();
  12053. this._audioEnabled = true;
  12054. this._headphone = false;
  12055. this._totalVertices = 0;
  12056. this._activeIndices = 0;
  12057. this._activeParticles = 0;
  12058. this._lastFrameDuration = 0;
  12059. this._evaluateActiveMeshesDuration = 0;
  12060. this._renderTargetsDuration = 0;
  12061. this._particlesDuration = 0;
  12062. this._renderDuration = 0;
  12063. this._spritesDuration = 0;
  12064. this._animationRatio = 0;
  12065. this._renderId = 0;
  12066. this._executeWhenReadyTimeoutId = -1;
  12067. this._toBeDisposed = new BABYLON.SmartArray(256);
  12068. this._onReadyCallbacks = new Array();
  12069. this._pendingData = []; //ANY
  12070. this._onBeforeRenderCallbacks = new Array();
  12071. this._onAfterRenderCallbacks = new Array();
  12072. this._activeMeshes = new BABYLON.SmartArray(256);
  12073. this._processedMaterials = new BABYLON.SmartArray(256);
  12074. this._renderTargets = new BABYLON.SmartArray(256);
  12075. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12076. this._activeSkeletons = new BABYLON.SmartArray(32);
  12077. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12078. this._activeBones = 0;
  12079. this._activeAnimatables = new Array();
  12080. this._transformMatrix = BABYLON.Matrix.Zero();
  12081. this._edgesRenderers = new BABYLON.SmartArray(16);
  12082. this._uniqueIdCounter = 0;
  12083. this._engine = engine;
  12084. engine.scenes.push(this);
  12085. this._renderingManager = new BABYLON.RenderingManager(this);
  12086. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12087. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12088. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12089. if (BABYLON.OutlineRenderer) {
  12090. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12091. }
  12092. this.attachControl();
  12093. this._debugLayer = new BABYLON.DebugLayer(this);
  12094. if (BABYLON.SoundTrack) {
  12095. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12096. }
  12097. //simplification queue
  12098. if (BABYLON.SimplificationQueue) {
  12099. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12100. }
  12101. //collision coordinator initialization. For now legacy per default.
  12102. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12103. }
  12104. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12105. get: function () {
  12106. return Scene._FOGMODE_NONE;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12112. get: function () {
  12113. return Scene._FOGMODE_EXP;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12119. get: function () {
  12120. return Scene._FOGMODE_EXP2;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12126. get: function () {
  12127. return Scene._FOGMODE_LINEAR;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Scene.prototype, "debugLayer", {
  12133. // Properties
  12134. get: function () {
  12135. return this._debugLayer;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12141. get: function () {
  12142. return this._workerCollisions;
  12143. },
  12144. set: function (enabled) {
  12145. enabled = (enabled && !!Worker);
  12146. this._workerCollisions = enabled;
  12147. if (this.collisionCoordinator) {
  12148. this.collisionCoordinator.destroy();
  12149. }
  12150. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12151. this.collisionCoordinator.init(this);
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12157. get: function () {
  12158. return this._selectionOctree;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12164. /**
  12165. * The mesh that is currently under the pointer.
  12166. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12167. */
  12168. get: function () {
  12169. return this._meshUnderPointer;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Scene.prototype, "pointerX", {
  12175. /**
  12176. * Current on-screen X position of the pointer
  12177. * @return {number} X position of the pointer
  12178. */
  12179. get: function () {
  12180. return this._pointerX;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Scene.prototype, "pointerY", {
  12186. /**
  12187. * Current on-screen Y position of the pointer
  12188. * @return {number} Y position of the pointer
  12189. */
  12190. get: function () {
  12191. return this._pointerY;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Scene.prototype.getCachedMaterial = function () {
  12197. return this._cachedMaterial;
  12198. };
  12199. Scene.prototype.getBoundingBoxRenderer = function () {
  12200. return this._boundingBoxRenderer;
  12201. };
  12202. Scene.prototype.getOutlineRenderer = function () {
  12203. return this._outlineRenderer;
  12204. };
  12205. Scene.prototype.getEngine = function () {
  12206. return this._engine;
  12207. };
  12208. Scene.prototype.getTotalVertices = function () {
  12209. return this._totalVertices;
  12210. };
  12211. Scene.prototype.getActiveIndices = function () {
  12212. return this._activeIndices;
  12213. };
  12214. Scene.prototype.getActiveParticles = function () {
  12215. return this._activeParticles;
  12216. };
  12217. Scene.prototype.getActiveBones = function () {
  12218. return this._activeBones;
  12219. };
  12220. // Stats
  12221. Scene.prototype.getLastFrameDuration = function () {
  12222. return this._lastFrameDuration;
  12223. };
  12224. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12225. return this._evaluateActiveMeshesDuration;
  12226. };
  12227. Scene.prototype.getActiveMeshes = function () {
  12228. return this._activeMeshes;
  12229. };
  12230. Scene.prototype.getRenderTargetsDuration = function () {
  12231. return this._renderTargetsDuration;
  12232. };
  12233. Scene.prototype.getRenderDuration = function () {
  12234. return this._renderDuration;
  12235. };
  12236. Scene.prototype.getParticlesDuration = function () {
  12237. return this._particlesDuration;
  12238. };
  12239. Scene.prototype.getSpritesDuration = function () {
  12240. return this._spritesDuration;
  12241. };
  12242. Scene.prototype.getAnimationRatio = function () {
  12243. return this._animationRatio;
  12244. };
  12245. Scene.prototype.getRenderId = function () {
  12246. return this._renderId;
  12247. };
  12248. Scene.prototype.incrementRenderId = function () {
  12249. this._renderId++;
  12250. };
  12251. Scene.prototype._updatePointerPosition = function (evt) {
  12252. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12253. this._pointerX = evt.clientX - canvasRect.left;
  12254. this._pointerY = evt.clientY - canvasRect.top;
  12255. if (this.cameraToUseForPointers) {
  12256. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12257. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12258. }
  12259. };
  12260. // Pointers handling
  12261. Scene.prototype.attachControl = function () {
  12262. var _this = this;
  12263. var spritePredicate = function (sprite) {
  12264. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12265. };
  12266. this._onPointerMove = function (evt) {
  12267. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12268. return;
  12269. }
  12270. var canvas = _this._engine.getRenderingCanvas();
  12271. _this._updatePointerPosition(evt);
  12272. // Meshes
  12273. 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);
  12274. if (pickResult.hit && pickResult.pickedMesh) {
  12275. _this._meshUnderPointer = pickResult.pickedMesh;
  12276. _this.setPointerOverMesh(pickResult.pickedMesh);
  12277. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12278. canvas.style.cursor = "pointer";
  12279. }
  12280. else {
  12281. canvas.style.cursor = "";
  12282. }
  12283. }
  12284. else {
  12285. // Sprites
  12286. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12287. if (pickResult.hit && pickResult.pickedSprite) {
  12288. canvas.style.cursor = "pointer";
  12289. }
  12290. else {
  12291. // Restore pointer
  12292. _this.setPointerOverMesh(null);
  12293. canvas.style.cursor = "";
  12294. _this._meshUnderPointer = null;
  12295. }
  12296. }
  12297. if (_this.onPointerMove) {
  12298. _this.onPointerMove(evt, pickResult);
  12299. }
  12300. };
  12301. this._onPointerDown = function (evt) {
  12302. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12303. return;
  12304. }
  12305. _this._updatePointerPosition(evt);
  12306. _this._startingPointerPosition.x = _this._pointerX;
  12307. _this._startingPointerPosition.y = _this._pointerY;
  12308. _this._startingPointerTime = new Date().getTime();
  12309. var predicate = null;
  12310. // Meshes
  12311. if (!_this.onPointerDown) {
  12312. predicate = function (mesh) {
  12313. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12314. };
  12315. }
  12316. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12317. if (pickResult.hit && pickResult.pickedMesh) {
  12318. if (pickResult.pickedMesh.actionManager) {
  12319. switch (evt.button) {
  12320. case 0:
  12321. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12322. break;
  12323. case 1:
  12324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12325. break;
  12326. case 2:
  12327. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12328. break;
  12329. }
  12330. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12331. }
  12332. }
  12333. if (_this.onPointerDown) {
  12334. _this.onPointerDown(evt, pickResult);
  12335. }
  12336. // Sprites
  12337. if (_this.spriteManagers.length > 0) {
  12338. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12339. if (pickResult.hit && pickResult.pickedSprite) {
  12340. if (pickResult.pickedSprite.actionManager) {
  12341. switch (evt.button) {
  12342. case 0:
  12343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12344. break;
  12345. case 1:
  12346. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12347. break;
  12348. case 2:
  12349. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12350. break;
  12351. }
  12352. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12353. }
  12354. }
  12355. }
  12356. };
  12357. this._onPointerUp = function (evt) {
  12358. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12359. return;
  12360. }
  12361. var predicate = null;
  12362. _this._updatePointerPosition(evt);
  12363. if (!_this.onPointerUp) {
  12364. predicate = function (mesh) {
  12365. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12366. };
  12367. }
  12368. // Meshes
  12369. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12370. if (pickResult.hit && pickResult.pickedMesh) {
  12371. if (pickResult.pickedMesh.actionManager) {
  12372. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12373. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12374. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12375. if ((new Date().getTime() - _this._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) {
  12376. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12377. ;
  12378. }
  12379. }
  12380. }
  12381. }
  12382. if (_this.onPointerUp) {
  12383. _this.onPointerUp(evt, pickResult);
  12384. }
  12385. // Sprites
  12386. if (_this.spriteManagers.length > 0) {
  12387. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12388. if (pickResult.hit && pickResult.pickedSprite) {
  12389. if (pickResult.pickedSprite.actionManager) {
  12390. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12391. }
  12392. }
  12393. }
  12394. };
  12395. this._onKeyDown = function (evt) {
  12396. if (_this.actionManager) {
  12397. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12398. }
  12399. };
  12400. this._onKeyUp = function (evt) {
  12401. if (_this.actionManager) {
  12402. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12403. }
  12404. };
  12405. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12406. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12407. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12408. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12409. // Wheel
  12410. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12411. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12412. BABYLON.Tools.RegisterTopRootEvents([
  12413. { name: "keydown", handler: this._onKeyDown },
  12414. { name: "keyup", handler: this._onKeyUp }
  12415. ]);
  12416. };
  12417. Scene.prototype.detachControl = function () {
  12418. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12419. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12420. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12421. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12422. // Wheel
  12423. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12424. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12425. BABYLON.Tools.UnregisterTopRootEvents([
  12426. { name: "keydown", handler: this._onKeyDown },
  12427. { name: "keyup", handler: this._onKeyUp }
  12428. ]);
  12429. };
  12430. // Ready
  12431. Scene.prototype.isReady = function () {
  12432. if (this._pendingData.length > 0) {
  12433. return false;
  12434. }
  12435. var index;
  12436. for (index = 0; index < this._geometries.length; index++) {
  12437. var geometry = this._geometries[index];
  12438. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12439. return false;
  12440. }
  12441. }
  12442. for (index = 0; index < this.meshes.length; index++) {
  12443. var mesh = this.meshes[index];
  12444. if (!mesh.isReady()) {
  12445. return false;
  12446. }
  12447. var mat = mesh.material;
  12448. if (mat) {
  12449. if (!mat.isReady(mesh)) {
  12450. return false;
  12451. }
  12452. }
  12453. }
  12454. return true;
  12455. };
  12456. Scene.prototype.resetCachedMaterial = function () {
  12457. this._cachedMaterial = null;
  12458. };
  12459. Scene.prototype.registerBeforeRender = function (func) {
  12460. this._onBeforeRenderCallbacks.push(func);
  12461. };
  12462. Scene.prototype.unregisterBeforeRender = function (func) {
  12463. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12464. if (index > -1) {
  12465. this._onBeforeRenderCallbacks.splice(index, 1);
  12466. }
  12467. };
  12468. Scene.prototype.registerAfterRender = function (func) {
  12469. this._onAfterRenderCallbacks.push(func);
  12470. };
  12471. Scene.prototype.unregisterAfterRender = function (func) {
  12472. var index = this._onAfterRenderCallbacks.indexOf(func);
  12473. if (index > -1) {
  12474. this._onAfterRenderCallbacks.splice(index, 1);
  12475. }
  12476. };
  12477. Scene.prototype._addPendingData = function (data) {
  12478. this._pendingData.push(data);
  12479. };
  12480. Scene.prototype._removePendingData = function (data) {
  12481. var index = this._pendingData.indexOf(data);
  12482. if (index !== -1) {
  12483. this._pendingData.splice(index, 1);
  12484. }
  12485. };
  12486. Scene.prototype.getWaitingItemsCount = function () {
  12487. return this._pendingData.length;
  12488. };
  12489. /**
  12490. * Registers a function to be executed when the scene is ready.
  12491. * @param {Function} func - the function to be executed.
  12492. */
  12493. Scene.prototype.executeWhenReady = function (func) {
  12494. var _this = this;
  12495. this._onReadyCallbacks.push(func);
  12496. if (this._executeWhenReadyTimeoutId !== -1) {
  12497. return;
  12498. }
  12499. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12500. _this._checkIsReady();
  12501. }, 150);
  12502. };
  12503. Scene.prototype._checkIsReady = function () {
  12504. var _this = this;
  12505. if (this.isReady()) {
  12506. this._onReadyCallbacks.forEach(function (func) {
  12507. func();
  12508. });
  12509. this._onReadyCallbacks = [];
  12510. this._executeWhenReadyTimeoutId = -1;
  12511. return;
  12512. }
  12513. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12514. _this._checkIsReady();
  12515. }, 150);
  12516. };
  12517. // Animations
  12518. /**
  12519. * Will start the animation sequence of a given target
  12520. * @param target - the target
  12521. * @param {number} from - from which frame should animation start
  12522. * @param {number} to - till which frame should animation run.
  12523. * @param {boolean} [loop] - should the animation loop
  12524. * @param {number} [speedRatio] - the speed in which to run the animation
  12525. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12526. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12527. * @return {BABYLON.Animatable} the animatable object created for this animation
  12528. * @see BABYLON.Animatable
  12529. * @see http://doc.babylonjs.com/page.php?p=22081
  12530. */
  12531. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12532. if (speedRatio === void 0) { speedRatio = 1.0; }
  12533. this.stopAnimation(target);
  12534. if (!animatable) {
  12535. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12536. }
  12537. // Local animations
  12538. if (target.animations) {
  12539. animatable.appendAnimations(target, target.animations);
  12540. }
  12541. // Children animations
  12542. if (target.getAnimatables) {
  12543. var animatables = target.getAnimatables();
  12544. for (var index = 0; index < animatables.length; index++) {
  12545. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12546. }
  12547. }
  12548. return animatable;
  12549. };
  12550. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12551. if (speedRatio === undefined) {
  12552. speedRatio = 1.0;
  12553. }
  12554. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12555. return animatable;
  12556. };
  12557. Scene.prototype.getAnimatableByTarget = function (target) {
  12558. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12559. if (this._activeAnimatables[index].target === target) {
  12560. return this._activeAnimatables[index];
  12561. }
  12562. }
  12563. return null;
  12564. };
  12565. /**
  12566. * Will stop the animation of the given target
  12567. * @param target - the target
  12568. * @see beginAnimation
  12569. */
  12570. Scene.prototype.stopAnimation = function (target) {
  12571. var animatable = this.getAnimatableByTarget(target);
  12572. if (animatable) {
  12573. animatable.stop();
  12574. }
  12575. };
  12576. Scene.prototype._animate = function () {
  12577. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12578. return;
  12579. }
  12580. if (!this._animationStartDate) {
  12581. if (this._pendingData.length > 0) {
  12582. return;
  12583. }
  12584. this._animationStartDate = BABYLON.Tools.Now;
  12585. }
  12586. // Getting time
  12587. var now = BABYLON.Tools.Now;
  12588. var delay = now - this._animationStartDate;
  12589. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12590. this._activeAnimatables[index]._animate(delay);
  12591. }
  12592. };
  12593. // Matrix
  12594. Scene.prototype.getViewMatrix = function () {
  12595. return this._viewMatrix;
  12596. };
  12597. Scene.prototype.getProjectionMatrix = function () {
  12598. return this._projectionMatrix;
  12599. };
  12600. Scene.prototype.getTransformMatrix = function () {
  12601. return this._transformMatrix;
  12602. };
  12603. Scene.prototype.setTransformMatrix = function (view, projection) {
  12604. this._viewMatrix = view;
  12605. this._projectionMatrix = projection;
  12606. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12607. };
  12608. // Methods
  12609. Scene.prototype.addMesh = function (newMesh) {
  12610. newMesh.uniqueId = this._uniqueIdCounter++;
  12611. var position = this.meshes.push(newMesh);
  12612. //notify the collision coordinator
  12613. this.collisionCoordinator.onMeshAdded(newMesh);
  12614. if (this.onNewMeshAdded) {
  12615. this.onNewMeshAdded(newMesh, position, this);
  12616. }
  12617. };
  12618. Scene.prototype.removeMesh = function (toRemove) {
  12619. var index = this.meshes.indexOf(toRemove);
  12620. if (index !== -1) {
  12621. // Remove from the scene if mesh found
  12622. this.meshes.splice(index, 1);
  12623. }
  12624. //notify the collision coordinator
  12625. this.collisionCoordinator.onMeshRemoved(toRemove);
  12626. if (this.onMeshRemoved) {
  12627. this.onMeshRemoved(toRemove);
  12628. }
  12629. return index;
  12630. };
  12631. Scene.prototype.removeSkeleton = function (toRemove) {
  12632. var index = this.skeletons.indexOf(toRemove);
  12633. if (index !== -1) {
  12634. // Remove from the scene if mesh found
  12635. this.skeletons.splice(index, 1);
  12636. }
  12637. return index;
  12638. };
  12639. Scene.prototype.removeLight = function (toRemove) {
  12640. var index = this.lights.indexOf(toRemove);
  12641. if (index !== -1) {
  12642. // Remove from the scene if mesh found
  12643. this.lights.splice(index, 1);
  12644. }
  12645. if (this.onLightRemoved) {
  12646. this.onLightRemoved(toRemove);
  12647. }
  12648. return index;
  12649. };
  12650. Scene.prototype.removeCamera = function (toRemove) {
  12651. var index = this.cameras.indexOf(toRemove);
  12652. if (index !== -1) {
  12653. // Remove from the scene if mesh found
  12654. this.cameras.splice(index, 1);
  12655. }
  12656. // Remove from activeCameras
  12657. var index2 = this.activeCameras.indexOf(toRemove);
  12658. if (index2 !== -1) {
  12659. // Remove from the scene if mesh found
  12660. this.activeCameras.splice(index2, 1);
  12661. }
  12662. // Reset the activeCamera
  12663. if (this.activeCamera === toRemove) {
  12664. if (this.cameras.length > 0) {
  12665. this.activeCamera = this.cameras[0];
  12666. }
  12667. else {
  12668. this.activeCamera = null;
  12669. }
  12670. }
  12671. if (this.onCameraRemoved) {
  12672. this.onCameraRemoved(toRemove);
  12673. }
  12674. return index;
  12675. };
  12676. Scene.prototype.addLight = function (newLight) {
  12677. newLight.uniqueId = this._uniqueIdCounter++;
  12678. var position = this.lights.push(newLight);
  12679. if (this.onNewLightAdded) {
  12680. this.onNewLightAdded(newLight, position, this);
  12681. }
  12682. };
  12683. Scene.prototype.addCamera = function (newCamera) {
  12684. newCamera.uniqueId = this._uniqueIdCounter++;
  12685. var position = this.cameras.push(newCamera);
  12686. if (this.onNewCameraAdded) {
  12687. this.onNewCameraAdded(newCamera, position, this);
  12688. }
  12689. };
  12690. /**
  12691. * sets the active camera of the scene using its ID
  12692. * @param {string} id - the camera's ID
  12693. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12694. * @see activeCamera
  12695. */
  12696. Scene.prototype.setActiveCameraByID = function (id) {
  12697. var camera = this.getCameraByID(id);
  12698. if (camera) {
  12699. this.activeCamera = camera;
  12700. return camera;
  12701. }
  12702. return null;
  12703. };
  12704. /**
  12705. * sets the active camera of the scene using its name
  12706. * @param {string} name - the camera's name
  12707. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12708. * @see activeCamera
  12709. */
  12710. Scene.prototype.setActiveCameraByName = function (name) {
  12711. var camera = this.getCameraByName(name);
  12712. if (camera) {
  12713. this.activeCamera = camera;
  12714. return camera;
  12715. }
  12716. return null;
  12717. };
  12718. /**
  12719. * get a material using its id
  12720. * @param {string} the material's ID
  12721. * @return {BABYLON.Material|null} the material or null if none found.
  12722. */
  12723. Scene.prototype.getMaterialByID = function (id) {
  12724. for (var index = 0; index < this.materials.length; index++) {
  12725. if (this.materials[index].id === id) {
  12726. return this.materials[index];
  12727. }
  12728. }
  12729. return null;
  12730. };
  12731. /**
  12732. * get a material using its name
  12733. * @param {string} the material's name
  12734. * @return {BABYLON.Material|null} the material or null if none found.
  12735. */
  12736. Scene.prototype.getMaterialByName = function (name) {
  12737. for (var index = 0; index < this.materials.length; index++) {
  12738. if (this.materials[index].name === name) {
  12739. return this.materials[index];
  12740. }
  12741. }
  12742. return null;
  12743. };
  12744. Scene.prototype.getLensFlareSystemByName = function (name) {
  12745. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12746. if (this.lensFlareSystems[index].name === name) {
  12747. return this.lensFlareSystems[index];
  12748. }
  12749. }
  12750. return null;
  12751. };
  12752. Scene.prototype.getCameraByID = function (id) {
  12753. for (var index = 0; index < this.cameras.length; index++) {
  12754. if (this.cameras[index].id === id) {
  12755. return this.cameras[index];
  12756. }
  12757. }
  12758. return null;
  12759. };
  12760. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12761. for (var index = 0; index < this.cameras.length; index++) {
  12762. if (this.cameras[index].uniqueId === uniqueId) {
  12763. return this.cameras[index];
  12764. }
  12765. }
  12766. return null;
  12767. };
  12768. /**
  12769. * get a camera using its name
  12770. * @param {string} the camera's name
  12771. * @return {BABYLON.Camera|null} the camera or null if none found.
  12772. */
  12773. Scene.prototype.getCameraByName = function (name) {
  12774. for (var index = 0; index < this.cameras.length; index++) {
  12775. if (this.cameras[index].name === name) {
  12776. return this.cameras[index];
  12777. }
  12778. }
  12779. return null;
  12780. };
  12781. /**
  12782. * get a bone using its id
  12783. * @param {string} the bone's id
  12784. * @return {BABYLON.Bone|null} the bone or null if not found
  12785. */
  12786. Scene.prototype.getBoneByID = function (id) {
  12787. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12788. var skeleton = this.skeletons[skeletonIndex];
  12789. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12790. if (skeleton.bones[boneIndex].id === id) {
  12791. return skeleton.bones[boneIndex];
  12792. }
  12793. }
  12794. }
  12795. return null;
  12796. };
  12797. /**
  12798. * get a bone using its id
  12799. * @param {string} the bone's name
  12800. * @return {BABYLON.Bone|null} the bone or null if not found
  12801. */
  12802. Scene.prototype.getBoneByName = function (name) {
  12803. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12804. var skeleton = this.skeletons[skeletonIndex];
  12805. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12806. if (skeleton.bones[boneIndex].name === name) {
  12807. return skeleton.bones[boneIndex];
  12808. }
  12809. }
  12810. }
  12811. return null;
  12812. };
  12813. /**
  12814. * get a light node using its name
  12815. * @param {string} the light's name
  12816. * @return {BABYLON.Light|null} the light or null if none found.
  12817. */
  12818. Scene.prototype.getLightByName = function (name) {
  12819. for (var index = 0; index < this.lights.length; index++) {
  12820. if (this.lights[index].name === name) {
  12821. return this.lights[index];
  12822. }
  12823. }
  12824. return null;
  12825. };
  12826. /**
  12827. * get a light node using its ID
  12828. * @param {string} the light's id
  12829. * @return {BABYLON.Light|null} the light or null if none found.
  12830. */
  12831. Scene.prototype.getLightByID = function (id) {
  12832. for (var index = 0; index < this.lights.length; index++) {
  12833. if (this.lights[index].id === id) {
  12834. return this.lights[index];
  12835. }
  12836. }
  12837. return null;
  12838. };
  12839. /**
  12840. * get a light node using its scene-generated unique ID
  12841. * @param {number} the light's unique id
  12842. * @return {BABYLON.Light|null} the light or null if none found.
  12843. */
  12844. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12845. for (var index = 0; index < this.lights.length; index++) {
  12846. if (this.lights[index].uniqueId === uniqueId) {
  12847. return this.lights[index];
  12848. }
  12849. }
  12850. return null;
  12851. };
  12852. /**
  12853. * get a particle system by id
  12854. * @param id {number} the particle system id
  12855. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12856. */
  12857. Scene.prototype.getParticleSystemByID = function (id) {
  12858. for (var index = 0; index < this.particleSystems.length; index++) {
  12859. if (this.particleSystems[index].id === id) {
  12860. return this.particleSystems[index];
  12861. }
  12862. }
  12863. return null;
  12864. };
  12865. /**
  12866. * get a geometry using its ID
  12867. * @param {string} the geometry's id
  12868. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12869. */
  12870. Scene.prototype.getGeometryByID = function (id) {
  12871. for (var index = 0; index < this._geometries.length; index++) {
  12872. if (this._geometries[index].id === id) {
  12873. return this._geometries[index];
  12874. }
  12875. }
  12876. return null;
  12877. };
  12878. /**
  12879. * add a new geometry to this scene.
  12880. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12881. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12882. * @return {boolean} was the geometry added or not
  12883. */
  12884. Scene.prototype.pushGeometry = function (geometry, force) {
  12885. if (!force && this.getGeometryByID(geometry.id)) {
  12886. return false;
  12887. }
  12888. this._geometries.push(geometry);
  12889. //notify the collision coordinator
  12890. this.collisionCoordinator.onGeometryAdded(geometry);
  12891. if (this.onGeometryAdded) {
  12892. this.onGeometryAdded(geometry);
  12893. }
  12894. return true;
  12895. };
  12896. /**
  12897. * Removes an existing geometry
  12898. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12899. * @return {boolean} was the geometry removed or not
  12900. */
  12901. Scene.prototype.removeGeometry = function (geometry) {
  12902. var index = this._geometries.indexOf(geometry);
  12903. if (index > -1) {
  12904. this._geometries.splice(index, 1);
  12905. //notify the collision coordinator
  12906. this.collisionCoordinator.onGeometryDeleted(geometry);
  12907. if (this.onGeometryRemoved) {
  12908. this.onGeometryRemoved(geometry);
  12909. }
  12910. return true;
  12911. }
  12912. return false;
  12913. };
  12914. Scene.prototype.getGeometries = function () {
  12915. return this._geometries;
  12916. };
  12917. /**
  12918. * Get the first added mesh found of a given ID
  12919. * @param {string} id - the id to search for
  12920. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12921. */
  12922. Scene.prototype.getMeshByID = function (id) {
  12923. for (var index = 0; index < this.meshes.length; index++) {
  12924. if (this.meshes[index].id === id) {
  12925. return this.meshes[index];
  12926. }
  12927. }
  12928. return null;
  12929. };
  12930. /**
  12931. * Get a mesh with its auto-generated unique id
  12932. * @param {number} uniqueId - the unique id to search for
  12933. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12934. */
  12935. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12936. for (var index = 0; index < this.meshes.length; index++) {
  12937. if (this.meshes[index].uniqueId === uniqueId) {
  12938. return this.meshes[index];
  12939. }
  12940. }
  12941. return null;
  12942. };
  12943. /**
  12944. * Get a the last added mesh found of a given ID
  12945. * @param {string} id - the id to search for
  12946. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12947. */
  12948. Scene.prototype.getLastMeshByID = function (id) {
  12949. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12950. if (this.meshes[index].id === id) {
  12951. return this.meshes[index];
  12952. }
  12953. }
  12954. return null;
  12955. };
  12956. /**
  12957. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12958. * @param {string} id - the id to search for
  12959. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12960. */
  12961. Scene.prototype.getLastEntryByID = function (id) {
  12962. var index;
  12963. for (index = this.meshes.length - 1; index >= 0; index--) {
  12964. if (this.meshes[index].id === id) {
  12965. return this.meshes[index];
  12966. }
  12967. }
  12968. for (index = this.cameras.length - 1; index >= 0; index--) {
  12969. if (this.cameras[index].id === id) {
  12970. return this.cameras[index];
  12971. }
  12972. }
  12973. for (index = this.lights.length - 1; index >= 0; index--) {
  12974. if (this.lights[index].id === id) {
  12975. return this.lights[index];
  12976. }
  12977. }
  12978. return null;
  12979. };
  12980. Scene.prototype.getNodeByID = function (id) {
  12981. var mesh = this.getMeshByID(id);
  12982. if (mesh) {
  12983. return mesh;
  12984. }
  12985. var light = this.getLightByID(id);
  12986. if (light) {
  12987. return light;
  12988. }
  12989. var camera = this.getCameraByID(id);
  12990. if (camera) {
  12991. return camera;
  12992. }
  12993. var bone = this.getBoneByID(id);
  12994. return bone;
  12995. };
  12996. Scene.prototype.getNodeByName = function (name) {
  12997. var mesh = this.getMeshByName(name);
  12998. if (mesh) {
  12999. return mesh;
  13000. }
  13001. var light = this.getLightByName(name);
  13002. if (light) {
  13003. return light;
  13004. }
  13005. var camera = this.getCameraByName(name);
  13006. if (camera) {
  13007. return camera;
  13008. }
  13009. var bone = this.getBoneByName(name);
  13010. return bone;
  13011. };
  13012. Scene.prototype.getMeshByName = function (name) {
  13013. for (var index = 0; index < this.meshes.length; index++) {
  13014. if (this.meshes[index].name === name) {
  13015. return this.meshes[index];
  13016. }
  13017. }
  13018. return null;
  13019. };
  13020. Scene.prototype.getSoundByName = function (name) {
  13021. var index;
  13022. if (BABYLON.AudioEngine) {
  13023. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13024. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13025. return this.mainSoundTrack.soundCollection[index];
  13026. }
  13027. }
  13028. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13029. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13030. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13031. return this.soundTracks[sdIndex].soundCollection[index];
  13032. }
  13033. }
  13034. }
  13035. }
  13036. return null;
  13037. };
  13038. Scene.prototype.getLastSkeletonByID = function (id) {
  13039. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13040. if (this.skeletons[index].id === id) {
  13041. return this.skeletons[index];
  13042. }
  13043. }
  13044. return null;
  13045. };
  13046. Scene.prototype.getSkeletonById = function (id) {
  13047. for (var index = 0; index < this.skeletons.length; index++) {
  13048. if (this.skeletons[index].id === id) {
  13049. return this.skeletons[index];
  13050. }
  13051. }
  13052. return null;
  13053. };
  13054. Scene.prototype.getSkeletonByName = function (name) {
  13055. for (var index = 0; index < this.skeletons.length; index++) {
  13056. if (this.skeletons[index].name === name) {
  13057. return this.skeletons[index];
  13058. }
  13059. }
  13060. return null;
  13061. };
  13062. Scene.prototype.isActiveMesh = function (mesh) {
  13063. return (this._activeMeshes.indexOf(mesh) !== -1);
  13064. };
  13065. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13066. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13067. var material = subMesh.getMaterial();
  13068. if (mesh.showSubMeshesBoundingBox) {
  13069. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13070. }
  13071. if (material) {
  13072. // Render targets
  13073. if (material.getRenderTargetTextures) {
  13074. if (this._processedMaterials.indexOf(material) === -1) {
  13075. this._processedMaterials.push(material);
  13076. this._renderTargets.concat(material.getRenderTargetTextures());
  13077. }
  13078. }
  13079. // Dispatch
  13080. this._activeIndices += subMesh.indexCount;
  13081. this._renderingManager.dispatch(subMesh);
  13082. }
  13083. }
  13084. };
  13085. Scene.prototype._evaluateActiveMeshes = function () {
  13086. this.activeCamera._activeMeshes.reset();
  13087. this._activeMeshes.reset();
  13088. this._renderingManager.reset();
  13089. this._processedMaterials.reset();
  13090. this._activeParticleSystems.reset();
  13091. this._activeSkeletons.reset();
  13092. this._softwareSkinnedMeshes.reset();
  13093. this._boundingBoxRenderer.reset();
  13094. this._edgesRenderers.reset();
  13095. if (!this._frustumPlanes) {
  13096. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13097. }
  13098. else {
  13099. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13100. }
  13101. // Meshes
  13102. var meshes;
  13103. var len;
  13104. if (this._selectionOctree) {
  13105. var selection = this._selectionOctree.select(this._frustumPlanes);
  13106. meshes = selection.data;
  13107. len = selection.length;
  13108. }
  13109. else {
  13110. len = this.meshes.length;
  13111. meshes = this.meshes;
  13112. }
  13113. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13114. var mesh = meshes[meshIndex];
  13115. if (mesh.isBlocked) {
  13116. continue;
  13117. }
  13118. this._totalVertices += mesh.getTotalVertices();
  13119. if (!mesh.isReady() || !mesh.isEnabled()) {
  13120. continue;
  13121. }
  13122. mesh.computeWorldMatrix();
  13123. // Intersections
  13124. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13125. this._meshesForIntersections.pushNoDuplicate(mesh);
  13126. }
  13127. // Switch to current LOD
  13128. var meshLOD = mesh.getLOD(this.activeCamera);
  13129. if (!meshLOD) {
  13130. continue;
  13131. }
  13132. mesh._preActivate();
  13133. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13134. this._activeMeshes.push(mesh);
  13135. this.activeCamera._activeMeshes.push(mesh);
  13136. mesh._activate(this._renderId);
  13137. this._activeMesh(meshLOD);
  13138. }
  13139. }
  13140. // Particle systems
  13141. var beforeParticlesDate = BABYLON.Tools.Now;
  13142. if (this.particlesEnabled) {
  13143. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13144. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13145. var particleSystem = this.particleSystems[particleIndex];
  13146. if (!particleSystem.isStarted()) {
  13147. continue;
  13148. }
  13149. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13150. this._activeParticleSystems.push(particleSystem);
  13151. particleSystem.animate();
  13152. }
  13153. }
  13154. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13155. }
  13156. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13157. };
  13158. Scene.prototype._activeMesh = function (mesh) {
  13159. if (mesh.skeleton && this.skeletonsEnabled) {
  13160. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13161. if (!mesh.computeBonesUsingShaders) {
  13162. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13163. }
  13164. }
  13165. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13166. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13167. }
  13168. if (mesh._edgesRenderer) {
  13169. this._edgesRenderers.push(mesh._edgesRenderer);
  13170. }
  13171. if (mesh && mesh.subMeshes) {
  13172. // Submeshes Octrees
  13173. var len;
  13174. var subMeshes;
  13175. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13176. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13177. len = intersections.length;
  13178. subMeshes = intersections.data;
  13179. }
  13180. else {
  13181. subMeshes = mesh.subMeshes;
  13182. len = subMeshes.length;
  13183. }
  13184. for (var subIndex = 0; subIndex < len; subIndex++) {
  13185. var subMesh = subMeshes[subIndex];
  13186. this._evaluateSubMesh(subMesh, mesh);
  13187. }
  13188. }
  13189. };
  13190. Scene.prototype.updateTransformMatrix = function (force) {
  13191. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13192. };
  13193. Scene.prototype._renderForCamera = function (camera) {
  13194. var engine = this._engine;
  13195. this.activeCamera = camera;
  13196. if (!this.activeCamera)
  13197. throw new Error("Active camera not set");
  13198. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13199. // Viewport
  13200. engine.setViewport(this.activeCamera.viewport);
  13201. // Camera
  13202. this.resetCachedMaterial();
  13203. this._renderId++;
  13204. this.updateTransformMatrix();
  13205. if (this.beforeCameraRender) {
  13206. this.beforeCameraRender(this.activeCamera);
  13207. }
  13208. // Meshes
  13209. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13210. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13211. this._evaluateActiveMeshes();
  13212. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13213. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13214. // Skeletons
  13215. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13216. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13217. skeleton.prepare();
  13218. }
  13219. // Software skinning
  13220. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13221. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13222. mesh.applySkeleton(mesh.skeleton);
  13223. }
  13224. // Render targets
  13225. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13226. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13227. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13228. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13229. var renderTarget = this._renderTargets.data[renderIndex];
  13230. if (renderTarget._shouldRender()) {
  13231. this._renderId++;
  13232. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13233. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13234. }
  13235. }
  13236. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13237. this._renderId++;
  13238. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13239. }
  13240. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13241. // Prepare Frame
  13242. this.postProcessManager._prepareFrame();
  13243. var beforeRenderDate = BABYLON.Tools.Now;
  13244. // Backgrounds
  13245. var layerIndex;
  13246. var layer;
  13247. if (this.layers.length) {
  13248. engine.setDepthBuffer(false);
  13249. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13250. layer = this.layers[layerIndex];
  13251. if (layer.isBackground) {
  13252. layer.render();
  13253. }
  13254. }
  13255. engine.setDepthBuffer(true);
  13256. }
  13257. // Render
  13258. BABYLON.Tools.StartPerformanceCounter("Main render");
  13259. this._renderingManager.render(null, null, true, true);
  13260. BABYLON.Tools.EndPerformanceCounter("Main render");
  13261. // Bounding boxes
  13262. this._boundingBoxRenderer.render();
  13263. // Edges
  13264. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13265. this._edgesRenderers.data[edgesRendererIndex].render();
  13266. }
  13267. // Lens flares
  13268. if (this.lensFlaresEnabled) {
  13269. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13270. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13271. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13272. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13273. lensFlareSystem.render();
  13274. }
  13275. }
  13276. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13277. }
  13278. // Foregrounds
  13279. if (this.layers.length) {
  13280. engine.setDepthBuffer(false);
  13281. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13282. layer = this.layers[layerIndex];
  13283. if (!layer.isBackground) {
  13284. layer.render();
  13285. }
  13286. }
  13287. engine.setDepthBuffer(true);
  13288. }
  13289. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13290. // Finalize frame
  13291. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13292. // Update camera
  13293. this.activeCamera._updateFromScene();
  13294. // Reset some special arrays
  13295. this._renderTargets.reset();
  13296. if (this.afterCameraRender) {
  13297. this.afterCameraRender(this.activeCamera);
  13298. }
  13299. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13300. };
  13301. Scene.prototype._processSubCameras = function (camera) {
  13302. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13303. this._renderForCamera(camera);
  13304. return;
  13305. }
  13306. // rig cameras
  13307. for (var index = 0; index < camera._rigCameras.length; index++) {
  13308. this._renderForCamera(camera._rigCameras[index]);
  13309. }
  13310. this.activeCamera = camera;
  13311. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13312. // Update camera
  13313. this.activeCamera._updateFromScene();
  13314. };
  13315. Scene.prototype._checkIntersections = function () {
  13316. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13317. var sourceMesh = this._meshesForIntersections.data[index];
  13318. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13319. var action = sourceMesh.actionManager.actions[actionIndex];
  13320. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13321. var parameters = action.getTriggerParameter();
  13322. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13323. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13324. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13325. if (areIntersecting && currentIntersectionInProgress === -1) {
  13326. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13327. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13328. sourceMesh._intersectionsInProgress.push(otherMesh);
  13329. }
  13330. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13331. sourceMesh._intersectionsInProgress.push(otherMesh);
  13332. }
  13333. }
  13334. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13335. //They intersected, and now they don't.
  13336. //is this trigger an exit trigger? execute an event.
  13337. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13338. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13339. }
  13340. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13341. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13342. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13343. }
  13344. }
  13345. }
  13346. }
  13347. }
  13348. };
  13349. Scene.prototype.render = function () {
  13350. var startDate = BABYLON.Tools.Now;
  13351. this._particlesDuration = 0;
  13352. this._spritesDuration = 0;
  13353. this._activeParticles = 0;
  13354. this._renderDuration = 0;
  13355. this._renderTargetsDuration = 0;
  13356. this._evaluateActiveMeshesDuration = 0;
  13357. this._totalVertices = 0;
  13358. this._activeIndices = 0;
  13359. this._activeBones = 0;
  13360. this.getEngine().resetDrawCalls();
  13361. this._meshesForIntersections.reset();
  13362. this.resetCachedMaterial();
  13363. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13364. // Actions
  13365. if (this.actionManager) {
  13366. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13367. }
  13368. //Simplification Queue
  13369. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13370. this.simplificationQueue.executeNext();
  13371. }
  13372. // Animations
  13373. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13374. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13375. this._animate();
  13376. // Physics
  13377. if (this._physicsEngine) {
  13378. BABYLON.Tools.StartPerformanceCounter("Physics");
  13379. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13380. BABYLON.Tools.EndPerformanceCounter("Physics");
  13381. }
  13382. // Before render
  13383. if (this.beforeRender) {
  13384. this.beforeRender();
  13385. }
  13386. var callbackIndex;
  13387. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13388. this._onBeforeRenderCallbacks[callbackIndex]();
  13389. }
  13390. // Customs render targets
  13391. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13392. var engine = this.getEngine();
  13393. var currentActiveCamera = this.activeCamera;
  13394. if (this.renderTargetsEnabled) {
  13395. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13396. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13397. var renderTarget = this.customRenderTargets[customIndex];
  13398. if (renderTarget._shouldRender()) {
  13399. this._renderId++;
  13400. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13401. if (!this.activeCamera)
  13402. throw new Error("Active camera not set");
  13403. // Viewport
  13404. engine.setViewport(this.activeCamera.viewport);
  13405. // Camera
  13406. this.updateTransformMatrix();
  13407. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13408. }
  13409. }
  13410. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13411. this._renderId++;
  13412. }
  13413. if (this.customRenderTargets.length > 0) {
  13414. engine.restoreDefaultFramebuffer();
  13415. }
  13416. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13417. this.activeCamera = currentActiveCamera;
  13418. // Procedural textures
  13419. if (this.proceduralTexturesEnabled) {
  13420. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13421. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13422. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13423. if (proceduralTexture._shouldRender()) {
  13424. proceduralTexture.render();
  13425. }
  13426. }
  13427. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13428. }
  13429. // Clear
  13430. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13431. // Shadows
  13432. if (this.shadowsEnabled) {
  13433. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13434. var light = this.lights[lightIndex];
  13435. var shadowGenerator = light.getShadowGenerator();
  13436. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13437. this._renderTargets.push(shadowGenerator.getShadowMap());
  13438. }
  13439. }
  13440. }
  13441. // Depth renderer
  13442. if (this._depthRenderer) {
  13443. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13444. }
  13445. // RenderPipeline
  13446. this.postProcessRenderPipelineManager.update();
  13447. // Multi-cameras?
  13448. if (this.activeCameras.length > 0) {
  13449. var currentRenderId = this._renderId;
  13450. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13451. this._renderId = currentRenderId;
  13452. this._processSubCameras(this.activeCameras[cameraIndex]);
  13453. }
  13454. }
  13455. else {
  13456. if (!this.activeCamera) {
  13457. throw new Error("No camera defined");
  13458. }
  13459. this._processSubCameras(this.activeCamera);
  13460. }
  13461. // Intersection checks
  13462. this._checkIntersections();
  13463. // Update the audio listener attached to the camera
  13464. if (BABYLON.AudioEngine) {
  13465. this._updateAudioParameters();
  13466. }
  13467. // After render
  13468. if (this.afterRender) {
  13469. this.afterRender();
  13470. }
  13471. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13472. this._onAfterRenderCallbacks[callbackIndex]();
  13473. }
  13474. // Cleaning
  13475. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13476. this._toBeDisposed.data[index].dispose();
  13477. this._toBeDisposed[index] = null;
  13478. }
  13479. this._toBeDisposed.reset();
  13480. if (this.dumpNextRenderTargets) {
  13481. this.dumpNextRenderTargets = false;
  13482. }
  13483. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13484. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13485. };
  13486. Scene.prototype._updateAudioParameters = function () {
  13487. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13488. return;
  13489. }
  13490. var listeningCamera;
  13491. var audioEngine = BABYLON.Engine.audioEngine;
  13492. if (this.activeCameras.length > 0) {
  13493. listeningCamera = this.activeCameras[0];
  13494. }
  13495. else {
  13496. listeningCamera = this.activeCamera;
  13497. }
  13498. if (listeningCamera && audioEngine.canUseWebAudio) {
  13499. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13500. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13501. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13502. cameraDirection.normalize();
  13503. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13504. var i;
  13505. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13506. var sound = this.mainSoundTrack.soundCollection[i];
  13507. if (sound.useCustomAttenuation) {
  13508. sound.updateDistanceFromListener();
  13509. }
  13510. }
  13511. for (i = 0; i < this.soundTracks.length; i++) {
  13512. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13513. sound = this.soundTracks[i].soundCollection[j];
  13514. if (sound.useCustomAttenuation) {
  13515. sound.updateDistanceFromListener();
  13516. }
  13517. }
  13518. }
  13519. }
  13520. };
  13521. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13522. // Audio
  13523. get: function () {
  13524. return this._audioEnabled;
  13525. },
  13526. set: function (value) {
  13527. this._audioEnabled = value;
  13528. if (BABYLON.AudioEngine) {
  13529. if (this._audioEnabled) {
  13530. this._enableAudio();
  13531. }
  13532. else {
  13533. this._disableAudio();
  13534. }
  13535. }
  13536. },
  13537. enumerable: true,
  13538. configurable: true
  13539. });
  13540. Scene.prototype._disableAudio = function () {
  13541. var i;
  13542. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13543. this.mainSoundTrack.soundCollection[i].pause();
  13544. }
  13545. for (i = 0; i < this.soundTracks.length; i++) {
  13546. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13547. this.soundTracks[i].soundCollection[j].pause();
  13548. }
  13549. }
  13550. };
  13551. Scene.prototype._enableAudio = function () {
  13552. var i;
  13553. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13554. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13555. this.mainSoundTrack.soundCollection[i].play();
  13556. }
  13557. }
  13558. for (i = 0; i < this.soundTracks.length; i++) {
  13559. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13560. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13561. this.soundTracks[i].soundCollection[j].play();
  13562. }
  13563. }
  13564. }
  13565. };
  13566. Object.defineProperty(Scene.prototype, "headphone", {
  13567. get: function () {
  13568. return this._headphone;
  13569. },
  13570. set: function (value) {
  13571. this._headphone = value;
  13572. if (BABYLON.AudioEngine) {
  13573. if (this._headphone) {
  13574. this._switchAudioModeForHeadphones();
  13575. }
  13576. else {
  13577. this._switchAudioModeForNormalSpeakers();
  13578. }
  13579. }
  13580. },
  13581. enumerable: true,
  13582. configurable: true
  13583. });
  13584. Scene.prototype._switchAudioModeForHeadphones = function () {
  13585. this.mainSoundTrack.switchPanningModelToHRTF();
  13586. for (var i = 0; i < this.soundTracks.length; i++) {
  13587. this.soundTracks[i].switchPanningModelToHRTF();
  13588. }
  13589. };
  13590. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13591. this.mainSoundTrack.switchPanningModelToEqualPower();
  13592. for (var i = 0; i < this.soundTracks.length; i++) {
  13593. this.soundTracks[i].switchPanningModelToEqualPower();
  13594. }
  13595. };
  13596. Scene.prototype.enableDepthRenderer = function () {
  13597. if (this._depthRenderer) {
  13598. return this._depthRenderer;
  13599. }
  13600. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13601. return this._depthRenderer;
  13602. };
  13603. Scene.prototype.disableDepthRenderer = function () {
  13604. if (!this._depthRenderer) {
  13605. return;
  13606. }
  13607. this._depthRenderer.dispose();
  13608. this._depthRenderer = null;
  13609. };
  13610. Scene.prototype.freezeMaterials = function () {
  13611. for (var i = 0; i < this.materials.length; i++) {
  13612. this.materials[i].freeze();
  13613. }
  13614. };
  13615. Scene.prototype.unfreezeMaterials = function () {
  13616. for (var i = 0; i < this.materials.length; i++) {
  13617. this.materials[i].unfreeze();
  13618. }
  13619. };
  13620. Scene.prototype.dispose = function () {
  13621. this.beforeRender = null;
  13622. this.afterRender = null;
  13623. this.skeletons = [];
  13624. this._boundingBoxRenderer.dispose();
  13625. if (this._depthRenderer) {
  13626. this._depthRenderer.dispose();
  13627. }
  13628. // Debug layer
  13629. this.debugLayer.hide();
  13630. // Events
  13631. if (this.onDispose) {
  13632. this.onDispose();
  13633. }
  13634. this._onBeforeRenderCallbacks = [];
  13635. this._onAfterRenderCallbacks = [];
  13636. this.detachControl();
  13637. // Release sounds & sounds tracks
  13638. if (BABYLON.AudioEngine) {
  13639. this.disposeSounds();
  13640. }
  13641. // Detach cameras
  13642. var canvas = this._engine.getRenderingCanvas();
  13643. var index;
  13644. for (index = 0; index < this.cameras.length; index++) {
  13645. this.cameras[index].detachControl(canvas);
  13646. }
  13647. // Release lights
  13648. while (this.lights.length) {
  13649. this.lights[0].dispose();
  13650. }
  13651. // Release meshes
  13652. while (this.meshes.length) {
  13653. this.meshes[0].dispose(true);
  13654. }
  13655. // Release cameras
  13656. while (this.cameras.length) {
  13657. this.cameras[0].dispose();
  13658. }
  13659. // Release materials
  13660. while (this.materials.length) {
  13661. this.materials[0].dispose();
  13662. }
  13663. // Release particles
  13664. while (this.particleSystems.length) {
  13665. this.particleSystems[0].dispose();
  13666. }
  13667. // Release sprites
  13668. while (this.spriteManagers.length) {
  13669. this.spriteManagers[0].dispose();
  13670. }
  13671. // Release layers
  13672. while (this.layers.length) {
  13673. this.layers[0].dispose();
  13674. }
  13675. // Release textures
  13676. while (this.textures.length) {
  13677. this.textures[0].dispose();
  13678. }
  13679. // Post-processes
  13680. this.postProcessManager.dispose();
  13681. // Physics
  13682. if (this._physicsEngine) {
  13683. this.disablePhysicsEngine();
  13684. }
  13685. // Remove from engine
  13686. index = this._engine.scenes.indexOf(this);
  13687. if (index > -1) {
  13688. this._engine.scenes.splice(index, 1);
  13689. }
  13690. this._engine.wipeCaches();
  13691. };
  13692. // Release sounds & sounds tracks
  13693. Scene.prototype.disposeSounds = function () {
  13694. this.mainSoundTrack.dispose();
  13695. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13696. this.soundTracks[scIndex].dispose();
  13697. }
  13698. };
  13699. // Octrees
  13700. Scene.prototype.getWorldExtends = function () {
  13701. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13702. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13703. for (var index = 0; index < this.meshes.length; index++) {
  13704. var mesh = this.meshes[index];
  13705. mesh.computeWorldMatrix(true);
  13706. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13707. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13708. BABYLON.Tools.CheckExtends(minBox, min, max);
  13709. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13710. }
  13711. return {
  13712. min: min,
  13713. max: max
  13714. };
  13715. };
  13716. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13717. if (maxCapacity === void 0) { maxCapacity = 64; }
  13718. if (maxDepth === void 0) { maxDepth = 2; }
  13719. if (!this._selectionOctree) {
  13720. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13721. }
  13722. var worldExtends = this.getWorldExtends();
  13723. // Update octree
  13724. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13725. return this._selectionOctree;
  13726. };
  13727. // Picking
  13728. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13729. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13730. var engine = this._engine;
  13731. if (!camera) {
  13732. if (!this.activeCamera)
  13733. throw new Error("Active camera not set");
  13734. camera = this.activeCamera;
  13735. }
  13736. var cameraViewport = camera.viewport;
  13737. var viewport = cameraViewport.toGlobal(engine);
  13738. // Moving coordinates to local viewport world
  13739. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13740. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13741. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13742. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13743. };
  13744. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13745. var engine = this._engine;
  13746. if (!camera) {
  13747. if (!this.activeCamera)
  13748. throw new Error("Active camera not set");
  13749. camera = this.activeCamera;
  13750. }
  13751. var cameraViewport = camera.viewport;
  13752. var viewport = cameraViewport.toGlobal(engine);
  13753. var identity = BABYLON.Matrix.Identity();
  13754. // Moving coordinates to local viewport world
  13755. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13756. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13757. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13758. };
  13759. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13760. var pickingInfo = null;
  13761. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13762. var mesh = this.meshes[meshIndex];
  13763. if (predicate) {
  13764. if (!predicate(mesh)) {
  13765. continue;
  13766. }
  13767. }
  13768. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13769. continue;
  13770. }
  13771. var world = mesh.getWorldMatrix();
  13772. var ray = rayFunction(world);
  13773. var result = mesh.intersects(ray, fastCheck);
  13774. if (!result || !result.hit)
  13775. continue;
  13776. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13777. continue;
  13778. pickingInfo = result;
  13779. if (fastCheck) {
  13780. break;
  13781. }
  13782. }
  13783. return pickingInfo || new BABYLON.PickingInfo();
  13784. };
  13785. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13786. var pickingInfo = null;
  13787. camera = camera || this.activeCamera;
  13788. if (this.spriteManagers.length > 0) {
  13789. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13790. var spriteManager = this.spriteManagers[spriteIndex];
  13791. if (!spriteManager.isPickable) {
  13792. continue;
  13793. }
  13794. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13795. if (!result || !result.hit)
  13796. continue;
  13797. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13798. continue;
  13799. pickingInfo = result;
  13800. if (fastCheck) {
  13801. break;
  13802. }
  13803. }
  13804. }
  13805. return pickingInfo || new BABYLON.PickingInfo();
  13806. };
  13807. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13808. var _this = this;
  13809. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13810. /// <param name="x">X position on screen</param>
  13811. /// <param name="y">Y position on screen</param>
  13812. /// <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>
  13813. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13814. /// <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>
  13815. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13816. };
  13817. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13818. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13819. /// <param name="x">X position on screen</param>
  13820. /// <param name="y">Y position on screen</param>
  13821. /// <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>
  13822. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13823. /// <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>
  13824. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13825. };
  13826. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13827. var _this = this;
  13828. return this._internalPick(function (world) {
  13829. if (!_this._pickWithRayInverseMatrix) {
  13830. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13831. }
  13832. world.invertToRef(_this._pickWithRayInverseMatrix);
  13833. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13834. }, predicate, fastCheck);
  13835. };
  13836. Scene.prototype.setPointerOverMesh = function (mesh) {
  13837. if (this._pointerOverMesh === mesh) {
  13838. return;
  13839. }
  13840. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13841. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13842. }
  13843. this._pointerOverMesh = mesh;
  13844. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13845. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13846. }
  13847. };
  13848. Scene.prototype.getPointerOverMesh = function () {
  13849. return this._pointerOverMesh;
  13850. };
  13851. // Physics
  13852. Scene.prototype.getPhysicsEngine = function () {
  13853. return this._physicsEngine;
  13854. };
  13855. /**
  13856. * Enables physics to the current scene
  13857. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13858. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13859. * @return {boolean} was the physics engine initialized
  13860. */
  13861. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13862. if (this._physicsEngine) {
  13863. return true;
  13864. }
  13865. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13866. if (!this._physicsEngine.isSupported()) {
  13867. this._physicsEngine = null;
  13868. return false;
  13869. }
  13870. this._physicsEngine._initialize(gravity);
  13871. return true;
  13872. };
  13873. Scene.prototype.disablePhysicsEngine = function () {
  13874. if (!this._physicsEngine) {
  13875. return;
  13876. }
  13877. this._physicsEngine.dispose();
  13878. this._physicsEngine = undefined;
  13879. };
  13880. Scene.prototype.isPhysicsEnabled = function () {
  13881. return this._physicsEngine !== undefined;
  13882. };
  13883. /**
  13884. * Sets the gravity of the physics engine (and NOT of the scene)
  13885. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13886. */
  13887. Scene.prototype.setGravity = function (gravity) {
  13888. if (!this._physicsEngine) {
  13889. return;
  13890. }
  13891. this._physicsEngine._setGravity(gravity);
  13892. };
  13893. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13894. if (parts.parts) {
  13895. options = parts;
  13896. parts = parts.parts;
  13897. }
  13898. if (!this._physicsEngine) {
  13899. return null;
  13900. }
  13901. for (var index = 0; index < parts.length; index++) {
  13902. var mesh = parts[index].mesh;
  13903. mesh._physicImpostor = parts[index].impostor;
  13904. mesh._physicsMass = options.mass / parts.length;
  13905. mesh._physicsFriction = options.friction;
  13906. mesh._physicRestitution = options.restitution;
  13907. }
  13908. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13909. };
  13910. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13911. for (var index = 0; index < compound.parts.length; index++) {
  13912. var mesh = compound.parts[index].mesh;
  13913. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13914. this._physicsEngine._unregisterMesh(mesh);
  13915. }
  13916. };
  13917. // Misc.
  13918. Scene.prototype.createDefaultCameraOrLight = function () {
  13919. // Light
  13920. if (this.lights.length === 0) {
  13921. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13922. }
  13923. // Camera
  13924. if (!this.activeCamera) {
  13925. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13926. // Compute position
  13927. var worldExtends = this.getWorldExtends();
  13928. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13929. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13930. camera.setTarget(worldCenter);
  13931. this.activeCamera = camera;
  13932. }
  13933. };
  13934. // Tags
  13935. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13936. if (tagsQuery === undefined) {
  13937. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13938. return list;
  13939. }
  13940. var listByTags = [];
  13941. forEach = forEach || (function (item) { return; });
  13942. for (var i in list) {
  13943. var item = list[i];
  13944. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13945. listByTags.push(item);
  13946. forEach(item);
  13947. }
  13948. }
  13949. return listByTags;
  13950. };
  13951. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13952. return this._getByTags(this.meshes, tagsQuery, forEach);
  13953. };
  13954. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13955. return this._getByTags(this.cameras, tagsQuery, forEach);
  13956. };
  13957. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13958. return this._getByTags(this.lights, tagsQuery, forEach);
  13959. };
  13960. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13961. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13962. };
  13963. // Statics
  13964. Scene._FOGMODE_NONE = 0;
  13965. Scene._FOGMODE_EXP = 1;
  13966. Scene._FOGMODE_EXP2 = 2;
  13967. Scene._FOGMODE_LINEAR = 3;
  13968. Scene.MinDeltaTime = 1.0;
  13969. Scene.MaxDeltaTime = 1000.0;
  13970. return Scene;
  13971. })();
  13972. BABYLON.Scene = Scene;
  13973. })(BABYLON || (BABYLON = {}));
  13974. var BABYLON;
  13975. (function (BABYLON) {
  13976. var VertexBuffer = (function () {
  13977. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13978. if (engine instanceof BABYLON.Mesh) {
  13979. this._engine = engine.getScene().getEngine();
  13980. }
  13981. else {
  13982. this._engine = engine;
  13983. }
  13984. this._updatable = updatable;
  13985. this._data = data;
  13986. if (!postponeInternalCreation) {
  13987. this.create();
  13988. }
  13989. this._kind = kind;
  13990. if (stride) {
  13991. this._strideSize = stride;
  13992. return;
  13993. }
  13994. // Deduce stride from kind
  13995. switch (kind) {
  13996. case VertexBuffer.PositionKind:
  13997. this._strideSize = 3;
  13998. break;
  13999. case VertexBuffer.NormalKind:
  14000. this._strideSize = 3;
  14001. break;
  14002. case VertexBuffer.UVKind:
  14003. case VertexBuffer.UV2Kind:
  14004. case VertexBuffer.UV3Kind:
  14005. case VertexBuffer.UV4Kind:
  14006. case VertexBuffer.UV5Kind:
  14007. case VertexBuffer.UV6Kind:
  14008. this._strideSize = 2;
  14009. break;
  14010. case VertexBuffer.ColorKind:
  14011. this._strideSize = 4;
  14012. break;
  14013. case VertexBuffer.MatricesIndicesKind:
  14014. case VertexBuffer.MatricesIndicesExtraKind:
  14015. this._strideSize = 4;
  14016. break;
  14017. case VertexBuffer.MatricesWeightsKind:
  14018. case VertexBuffer.MatricesWeightsExtraKind:
  14019. this._strideSize = 4;
  14020. break;
  14021. }
  14022. }
  14023. // Properties
  14024. VertexBuffer.prototype.isUpdatable = function () {
  14025. return this._updatable;
  14026. };
  14027. VertexBuffer.prototype.getData = function () {
  14028. return this._data;
  14029. };
  14030. VertexBuffer.prototype.getBuffer = function () {
  14031. return this._buffer;
  14032. };
  14033. VertexBuffer.prototype.getStrideSize = function () {
  14034. return this._strideSize;
  14035. };
  14036. // Methods
  14037. VertexBuffer.prototype.create = function (data) {
  14038. if (!data && this._buffer) {
  14039. return; // nothing to do
  14040. }
  14041. data = data || this._data;
  14042. if (!this._buffer) {
  14043. if (this._updatable) {
  14044. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14045. }
  14046. else {
  14047. this._buffer = this._engine.createVertexBuffer(data);
  14048. }
  14049. }
  14050. if (this._updatable) {
  14051. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14052. this._data = data;
  14053. }
  14054. };
  14055. VertexBuffer.prototype.update = function (data) {
  14056. this.create(data);
  14057. };
  14058. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14059. if (!this._buffer) {
  14060. return;
  14061. }
  14062. if (this._updatable) {
  14063. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14064. this._data = null;
  14065. }
  14066. };
  14067. VertexBuffer.prototype.dispose = function () {
  14068. if (!this._buffer) {
  14069. return;
  14070. }
  14071. if (this._engine._releaseBuffer(this._buffer)) {
  14072. this._buffer = null;
  14073. }
  14074. };
  14075. Object.defineProperty(VertexBuffer, "PositionKind", {
  14076. get: function () {
  14077. return VertexBuffer._PositionKind;
  14078. },
  14079. enumerable: true,
  14080. configurable: true
  14081. });
  14082. Object.defineProperty(VertexBuffer, "NormalKind", {
  14083. get: function () {
  14084. return VertexBuffer._NormalKind;
  14085. },
  14086. enumerable: true,
  14087. configurable: true
  14088. });
  14089. Object.defineProperty(VertexBuffer, "UVKind", {
  14090. get: function () {
  14091. return VertexBuffer._UVKind;
  14092. },
  14093. enumerable: true,
  14094. configurable: true
  14095. });
  14096. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14097. get: function () {
  14098. return VertexBuffer._UV2Kind;
  14099. },
  14100. enumerable: true,
  14101. configurable: true
  14102. });
  14103. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14104. get: function () {
  14105. return VertexBuffer._UV3Kind;
  14106. },
  14107. enumerable: true,
  14108. configurable: true
  14109. });
  14110. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14111. get: function () {
  14112. return VertexBuffer._UV4Kind;
  14113. },
  14114. enumerable: true,
  14115. configurable: true
  14116. });
  14117. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14118. get: function () {
  14119. return VertexBuffer._UV5Kind;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14125. get: function () {
  14126. return VertexBuffer._UV6Kind;
  14127. },
  14128. enumerable: true,
  14129. configurable: true
  14130. });
  14131. Object.defineProperty(VertexBuffer, "ColorKind", {
  14132. get: function () {
  14133. return VertexBuffer._ColorKind;
  14134. },
  14135. enumerable: true,
  14136. configurable: true
  14137. });
  14138. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14139. get: function () {
  14140. return VertexBuffer._MatricesIndicesKind;
  14141. },
  14142. enumerable: true,
  14143. configurable: true
  14144. });
  14145. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14146. get: function () {
  14147. return VertexBuffer._MatricesWeightsKind;
  14148. },
  14149. enumerable: true,
  14150. configurable: true
  14151. });
  14152. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14153. get: function () {
  14154. return VertexBuffer._MatricesIndicesExtraKind;
  14155. },
  14156. enumerable: true,
  14157. configurable: true
  14158. });
  14159. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14160. get: function () {
  14161. return VertexBuffer._MatricesWeightsExtraKind;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. // Enums
  14167. VertexBuffer._PositionKind = "position";
  14168. VertexBuffer._NormalKind = "normal";
  14169. VertexBuffer._UVKind = "uv";
  14170. VertexBuffer._UV2Kind = "uv2";
  14171. VertexBuffer._UV3Kind = "uv3";
  14172. VertexBuffer._UV4Kind = "uv4";
  14173. VertexBuffer._UV5Kind = "uv5";
  14174. VertexBuffer._UV6Kind = "uv6";
  14175. VertexBuffer._ColorKind = "color";
  14176. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14177. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14178. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14179. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14180. return VertexBuffer;
  14181. })();
  14182. BABYLON.VertexBuffer = VertexBuffer;
  14183. })(BABYLON || (BABYLON = {}));
  14184. var BABYLON;
  14185. (function (BABYLON) {
  14186. /**
  14187. * Creates an instance based on a source mesh.
  14188. */
  14189. var InstancedMesh = (function (_super) {
  14190. __extends(InstancedMesh, _super);
  14191. function InstancedMesh(name, source) {
  14192. _super.call(this, name, source.getScene());
  14193. source.instances.push(this);
  14194. this._sourceMesh = source;
  14195. this.position.copyFrom(source.position);
  14196. this.rotation.copyFrom(source.rotation);
  14197. this.scaling.copyFrom(source.scaling);
  14198. if (source.rotationQuaternion) {
  14199. this.rotationQuaternion = source.rotationQuaternion.clone();
  14200. }
  14201. this.infiniteDistance = source.infiniteDistance;
  14202. this.setPivotMatrix(source.getPivotMatrix());
  14203. this.refreshBoundingInfo();
  14204. this._syncSubMeshes();
  14205. }
  14206. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14207. // Methods
  14208. get: function () {
  14209. return this._sourceMesh.receiveShadows;
  14210. },
  14211. enumerable: true,
  14212. configurable: true
  14213. });
  14214. Object.defineProperty(InstancedMesh.prototype, "material", {
  14215. get: function () {
  14216. return this._sourceMesh.material;
  14217. },
  14218. enumerable: true,
  14219. configurable: true
  14220. });
  14221. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14222. get: function () {
  14223. return this._sourceMesh.visibility;
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14229. get: function () {
  14230. return this._sourceMesh.skeleton;
  14231. },
  14232. enumerable: true,
  14233. configurable: true
  14234. });
  14235. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14236. get: function () {
  14237. return this._sourceMesh.renderingGroupId;
  14238. },
  14239. enumerable: true,
  14240. configurable: true
  14241. });
  14242. InstancedMesh.prototype.getTotalVertices = function () {
  14243. return this._sourceMesh.getTotalVertices();
  14244. };
  14245. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14246. get: function () {
  14247. return this._sourceMesh;
  14248. },
  14249. enumerable: true,
  14250. configurable: true
  14251. });
  14252. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14253. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14254. };
  14255. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14256. return this._sourceMesh.isVerticesDataPresent(kind);
  14257. };
  14258. InstancedMesh.prototype.getIndices = function () {
  14259. return this._sourceMesh.getIndices();
  14260. };
  14261. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14262. get: function () {
  14263. return this._sourceMesh._positions;
  14264. },
  14265. enumerable: true,
  14266. configurable: true
  14267. });
  14268. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14269. var meshBB = this._sourceMesh.getBoundingInfo();
  14270. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14271. this._updateBoundingInfo();
  14272. };
  14273. InstancedMesh.prototype._preActivate = function () {
  14274. if (this._currentLOD) {
  14275. this._currentLOD._preActivate();
  14276. }
  14277. };
  14278. InstancedMesh.prototype._activate = function (renderId) {
  14279. if (this._currentLOD) {
  14280. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14281. }
  14282. };
  14283. InstancedMesh.prototype.getLOD = function (camera) {
  14284. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14285. if (this._currentLOD === this.sourceMesh) {
  14286. return this;
  14287. }
  14288. return this._currentLOD;
  14289. };
  14290. InstancedMesh.prototype._syncSubMeshes = function () {
  14291. this.releaseSubMeshes();
  14292. if (this._sourceMesh.subMeshes) {
  14293. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14294. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14295. }
  14296. }
  14297. };
  14298. InstancedMesh.prototype._generatePointsArray = function () {
  14299. return this._sourceMesh._generatePointsArray();
  14300. };
  14301. // Clone
  14302. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14303. var result = this._sourceMesh.createInstance(name);
  14304. // Deep copy
  14305. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14306. // Bounding info
  14307. this.refreshBoundingInfo();
  14308. // Parent
  14309. if (newParent) {
  14310. result.parent = newParent;
  14311. }
  14312. if (!doNotCloneChildren) {
  14313. // Children
  14314. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14315. var mesh = this.getScene().meshes[index];
  14316. if (mesh.parent === this) {
  14317. mesh.clone(mesh.name, result);
  14318. }
  14319. }
  14320. }
  14321. result.computeWorldMatrix(true);
  14322. return result;
  14323. };
  14324. // Dispoe
  14325. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14326. // Remove from mesh
  14327. var index = this._sourceMesh.instances.indexOf(this);
  14328. this._sourceMesh.instances.splice(index, 1);
  14329. _super.prototype.dispose.call(this, doNotRecurse);
  14330. };
  14331. return InstancedMesh;
  14332. })(BABYLON.AbstractMesh);
  14333. BABYLON.InstancedMesh = InstancedMesh;
  14334. })(BABYLON || (BABYLON = {}));
  14335. var BABYLON;
  14336. (function (BABYLON) {
  14337. var _InstancesBatch = (function () {
  14338. function _InstancesBatch() {
  14339. this.mustReturn = false;
  14340. this.visibleInstances = new Array();
  14341. this.renderSelf = new Array();
  14342. }
  14343. return _InstancesBatch;
  14344. })();
  14345. BABYLON._InstancesBatch = _InstancesBatch;
  14346. var Mesh = (function (_super) {
  14347. __extends(Mesh, _super);
  14348. /**
  14349. * @constructor
  14350. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14351. * @param {Scene} scene - The scene to add this mesh to.
  14352. * @param {Node} parent - The parent of this mesh, if it has one
  14353. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14354. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14355. * When false, achieved by calling a clone(), also passing False.
  14356. * This will make creation of children, recursive.
  14357. */
  14358. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14359. if (parent === void 0) { parent = null; }
  14360. _super.call(this, name, scene);
  14361. // Members
  14362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14363. this.instances = new Array();
  14364. this._LODLevels = new Array();
  14365. this._onBeforeRenderCallbacks = new Array();
  14366. this._onAfterRenderCallbacks = new Array();
  14367. this._visibleInstances = {};
  14368. this._renderIdForInstances = new Array();
  14369. this._batchCache = new _InstancesBatch();
  14370. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14371. this._sideOrientation = Mesh._DEFAULTSIDE;
  14372. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14373. if (source) {
  14374. // Geometry
  14375. if (source._geometry) {
  14376. source._geometry.applyToMesh(this);
  14377. }
  14378. // Deep copy
  14379. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14380. this.id = name + "." + source.id;
  14381. // Material
  14382. this.material = source.material;
  14383. var index;
  14384. if (!doNotCloneChildren) {
  14385. // Children
  14386. for (index = 0; index < scene.meshes.length; index++) {
  14387. var mesh = scene.meshes[index];
  14388. if (mesh.parent === source) {
  14389. // doNotCloneChildren is always going to be False
  14390. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14391. }
  14392. }
  14393. }
  14394. // Particles
  14395. for (index = 0; index < scene.particleSystems.length; index++) {
  14396. var system = scene.particleSystems[index];
  14397. if (system.emitter === source) {
  14398. system.clone(system.name, this);
  14399. }
  14400. }
  14401. this.computeWorldMatrix(true);
  14402. }
  14403. // Parent
  14404. if (parent !== null) {
  14405. this.parent = parent;
  14406. }
  14407. }
  14408. Object.defineProperty(Mesh, "FRONTSIDE", {
  14409. get: function () {
  14410. return Mesh._FRONTSIDE;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Mesh, "BACKSIDE", {
  14416. get: function () {
  14417. return Mesh._BACKSIDE;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14423. get: function () {
  14424. return Mesh._DOUBLESIDE;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14430. get: function () {
  14431. return Mesh._DEFAULTSIDE;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Object.defineProperty(Mesh, "NO_CAP", {
  14437. get: function () {
  14438. return Mesh._NO_CAP;
  14439. },
  14440. enumerable: true,
  14441. configurable: true
  14442. });
  14443. Object.defineProperty(Mesh, "CAP_START", {
  14444. get: function () {
  14445. return Mesh._CAP_START;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Object.defineProperty(Mesh, "CAP_END", {
  14451. get: function () {
  14452. return Mesh._CAP_END;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(Mesh, "CAP_ALL", {
  14458. get: function () {
  14459. return Mesh._CAP_ALL;
  14460. },
  14461. enumerable: true,
  14462. configurable: true
  14463. });
  14464. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14465. // Methods
  14466. get: function () {
  14467. return this._LODLevels.length > 0;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Mesh.prototype._sortLODLevels = function () {
  14473. this._LODLevels.sort(function (a, b) {
  14474. if (a.distance < b.distance) {
  14475. return 1;
  14476. }
  14477. if (a.distance > b.distance) {
  14478. return -1;
  14479. }
  14480. return 0;
  14481. });
  14482. };
  14483. /**
  14484. * Add a mesh as LOD level triggered at the given distance.
  14485. * @param {number} distance - the distance from the center of the object to show this level
  14486. * @param {Mesh} mesh - the mesh to be added as LOD level
  14487. * @return {Mesh} this mesh (for chaining)
  14488. */
  14489. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14490. if (mesh && mesh._masterMesh) {
  14491. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14492. return this;
  14493. }
  14494. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14495. this._LODLevels.push(level);
  14496. if (mesh) {
  14497. mesh._masterMesh = this;
  14498. }
  14499. this._sortLODLevels();
  14500. return this;
  14501. };
  14502. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14503. for (var index = 0; index < this._LODLevels.length; index++) {
  14504. var level = this._LODLevels[index];
  14505. if (level.distance === distance) {
  14506. return level.mesh;
  14507. }
  14508. }
  14509. return null;
  14510. };
  14511. /**
  14512. * Remove a mesh from the LOD array
  14513. * @param {Mesh} mesh - the mesh to be removed.
  14514. * @return {Mesh} this mesh (for chaining)
  14515. */
  14516. Mesh.prototype.removeLODLevel = function (mesh) {
  14517. for (var index = 0; index < this._LODLevels.length; index++) {
  14518. if (this._LODLevels[index].mesh === mesh) {
  14519. this._LODLevels.splice(index, 1);
  14520. if (mesh) {
  14521. mesh._masterMesh = null;
  14522. }
  14523. }
  14524. }
  14525. this._sortLODLevels();
  14526. return this;
  14527. };
  14528. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14529. if (!this._LODLevels || this._LODLevels.length === 0) {
  14530. return this;
  14531. }
  14532. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14533. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14534. if (this.onLODLevelSelection) {
  14535. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14536. }
  14537. return this;
  14538. }
  14539. for (var index = 0; index < this._LODLevels.length; index++) {
  14540. var level = this._LODLevels[index];
  14541. if (level.distance < distanceToCamera) {
  14542. if (level.mesh) {
  14543. level.mesh._preActivate();
  14544. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14545. }
  14546. if (this.onLODLevelSelection) {
  14547. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14548. }
  14549. return level.mesh;
  14550. }
  14551. }
  14552. if (this.onLODLevelSelection) {
  14553. this.onLODLevelSelection(distanceToCamera, this, this);
  14554. }
  14555. return this;
  14556. };
  14557. Object.defineProperty(Mesh.prototype, "geometry", {
  14558. get: function () {
  14559. return this._geometry;
  14560. },
  14561. enumerable: true,
  14562. configurable: true
  14563. });
  14564. Mesh.prototype.getTotalVertices = function () {
  14565. if (!this._geometry) {
  14566. return 0;
  14567. }
  14568. return this._geometry.getTotalVertices();
  14569. };
  14570. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14571. if (!this._geometry) {
  14572. return null;
  14573. }
  14574. return this._geometry.getVerticesData(kind, copyWhenShared);
  14575. };
  14576. Mesh.prototype.getVertexBuffer = function (kind) {
  14577. if (!this._geometry) {
  14578. return undefined;
  14579. }
  14580. return this._geometry.getVertexBuffer(kind);
  14581. };
  14582. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14583. if (!this._geometry) {
  14584. if (this._delayInfo) {
  14585. return this._delayInfo.indexOf(kind) !== -1;
  14586. }
  14587. return false;
  14588. }
  14589. return this._geometry.isVerticesDataPresent(kind);
  14590. };
  14591. Mesh.prototype.getVerticesDataKinds = function () {
  14592. if (!this._geometry) {
  14593. var result = [];
  14594. if (this._delayInfo) {
  14595. for (var kind in this._delayInfo) {
  14596. result.push(kind);
  14597. }
  14598. }
  14599. return result;
  14600. }
  14601. return this._geometry.getVerticesDataKinds();
  14602. };
  14603. Mesh.prototype.getTotalIndices = function () {
  14604. if (!this._geometry) {
  14605. return 0;
  14606. }
  14607. return this._geometry.getTotalIndices();
  14608. };
  14609. Mesh.prototype.getIndices = function (copyWhenShared) {
  14610. if (!this._geometry) {
  14611. return [];
  14612. }
  14613. return this._geometry.getIndices(copyWhenShared);
  14614. };
  14615. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14616. get: function () {
  14617. return this._masterMesh !== null && this._masterMesh !== undefined;
  14618. },
  14619. enumerable: true,
  14620. configurable: true
  14621. });
  14622. Mesh.prototype.isReady = function () {
  14623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14624. return false;
  14625. }
  14626. return _super.prototype.isReady.call(this);
  14627. };
  14628. Mesh.prototype.isDisposed = function () {
  14629. return this._isDisposed;
  14630. };
  14631. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14632. get: function () {
  14633. return this._sideOrientation;
  14634. },
  14635. set: function (sideO) {
  14636. this._sideOrientation = sideO;
  14637. },
  14638. enumerable: true,
  14639. configurable: true
  14640. });
  14641. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14642. get: function () {
  14643. return this._areNormalsFrozen;
  14644. },
  14645. enumerable: true,
  14646. configurable: true
  14647. });
  14648. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14649. Mesh.prototype.freezeNormals = function () {
  14650. this._areNormalsFrozen = true;
  14651. };
  14652. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14653. Mesh.prototype.unfreezeNormals = function () {
  14654. this._areNormalsFrozen = false;
  14655. };
  14656. // Methods
  14657. Mesh.prototype._preActivate = function () {
  14658. var sceneRenderId = this.getScene().getRenderId();
  14659. if (this._preActivateId === sceneRenderId) {
  14660. return;
  14661. }
  14662. this._preActivateId = sceneRenderId;
  14663. this._visibleInstances = null;
  14664. };
  14665. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14666. if (!this._visibleInstances) {
  14667. this._visibleInstances = {};
  14668. this._visibleInstances.defaultRenderId = renderId;
  14669. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14670. }
  14671. if (!this._visibleInstances[renderId]) {
  14672. this._visibleInstances[renderId] = new Array();
  14673. }
  14674. this._visibleInstances[renderId].push(instance);
  14675. };
  14676. Mesh.prototype.refreshBoundingInfo = function () {
  14677. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14678. if (data) {
  14679. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14680. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14681. }
  14682. if (this.subMeshes) {
  14683. for (var index = 0; index < this.subMeshes.length; index++) {
  14684. this.subMeshes[index].refreshBoundingInfo();
  14685. }
  14686. }
  14687. this._updateBoundingInfo();
  14688. };
  14689. Mesh.prototype._createGlobalSubMesh = function () {
  14690. var totalVertices = this.getTotalVertices();
  14691. if (!totalVertices || !this.getIndices()) {
  14692. return null;
  14693. }
  14694. this.releaseSubMeshes();
  14695. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14696. };
  14697. Mesh.prototype.subdivide = function (count) {
  14698. if (count < 1) {
  14699. return;
  14700. }
  14701. var totalIndices = this.getTotalIndices();
  14702. var subdivisionSize = (totalIndices / count) | 0;
  14703. var offset = 0;
  14704. // Ensure that subdivisionSize is a multiple of 3
  14705. while (subdivisionSize % 3 !== 0) {
  14706. subdivisionSize++;
  14707. }
  14708. this.releaseSubMeshes();
  14709. for (var index = 0; index < count; index++) {
  14710. if (offset >= totalIndices) {
  14711. break;
  14712. }
  14713. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14714. offset += subdivisionSize;
  14715. }
  14716. this.synchronizeInstances();
  14717. };
  14718. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14719. if (!this._geometry) {
  14720. var vertexData = new BABYLON.VertexData();
  14721. vertexData.set(data, kind);
  14722. var scene = this.getScene();
  14723. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14724. }
  14725. else {
  14726. this._geometry.setVerticesData(kind, data, updatable, stride);
  14727. }
  14728. };
  14729. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14730. if (!this._geometry) {
  14731. return;
  14732. }
  14733. if (!makeItUnique) {
  14734. this._geometry.updateVerticesData(kind, data, updateExtends);
  14735. }
  14736. else {
  14737. this.makeGeometryUnique();
  14738. this.updateVerticesData(kind, data, updateExtends, false);
  14739. }
  14740. };
  14741. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14742. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14743. if (!this._geometry) {
  14744. return;
  14745. }
  14746. if (!makeItUnique) {
  14747. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14748. }
  14749. else {
  14750. this.makeGeometryUnique();
  14751. this.updateVerticesDataDirectly(kind, data, offset, false);
  14752. }
  14753. };
  14754. // Mesh positions update function :
  14755. // updates the mesh positions according to the positionFunction returned values.
  14756. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14757. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14758. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14759. if (computeNormals === void 0) { computeNormals = true; }
  14760. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14761. positionFunction(positions);
  14762. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14763. if (computeNormals) {
  14764. var indices = this.getIndices();
  14765. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14766. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14767. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14768. }
  14769. };
  14770. Mesh.prototype.makeGeometryUnique = function () {
  14771. if (!this._geometry) {
  14772. return;
  14773. }
  14774. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14775. geometry.applyToMesh(this);
  14776. };
  14777. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14778. if (!this._geometry) {
  14779. var vertexData = new BABYLON.VertexData();
  14780. vertexData.indices = indices;
  14781. var scene = this.getScene();
  14782. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14783. }
  14784. else {
  14785. this._geometry.setIndices(indices, totalVertices);
  14786. }
  14787. };
  14788. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14789. var engine = this.getScene().getEngine();
  14790. // Wireframe
  14791. var indexToBind;
  14792. if (this._unIndexed) {
  14793. indexToBind = null;
  14794. }
  14795. else {
  14796. switch (fillMode) {
  14797. case BABYLON.Material.PointFillMode:
  14798. indexToBind = null;
  14799. break;
  14800. case BABYLON.Material.WireFrameFillMode:
  14801. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14802. break;
  14803. default:
  14804. case BABYLON.Material.TriangleFillMode:
  14805. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14806. break;
  14807. }
  14808. }
  14809. // VBOs
  14810. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14811. };
  14812. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14813. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14814. return;
  14815. }
  14816. var engine = this.getScene().getEngine();
  14817. // Draw order
  14818. switch (fillMode) {
  14819. case BABYLON.Material.PointFillMode:
  14820. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14821. break;
  14822. case BABYLON.Material.WireFrameFillMode:
  14823. if (this._unIndexed) {
  14824. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14825. }
  14826. else {
  14827. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14828. }
  14829. break;
  14830. default:
  14831. if (this._unIndexed) {
  14832. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14833. }
  14834. else {
  14835. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14836. }
  14837. }
  14838. };
  14839. Mesh.prototype.registerBeforeRender = function (func) {
  14840. this._onBeforeRenderCallbacks.push(func);
  14841. };
  14842. Mesh.prototype.unregisterBeforeRender = function (func) {
  14843. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14844. if (index > -1) {
  14845. this._onBeforeRenderCallbacks.splice(index, 1);
  14846. }
  14847. };
  14848. Mesh.prototype.registerAfterRender = function (func) {
  14849. this._onAfterRenderCallbacks.push(func);
  14850. };
  14851. Mesh.prototype.unregisterAfterRender = function (func) {
  14852. var index = this._onAfterRenderCallbacks.indexOf(func);
  14853. if (index > -1) {
  14854. this._onAfterRenderCallbacks.splice(index, 1);
  14855. }
  14856. };
  14857. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14858. var scene = this.getScene();
  14859. this._batchCache.mustReturn = false;
  14860. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14861. this._batchCache.visibleInstances[subMeshId] = null;
  14862. if (this._visibleInstances) {
  14863. var currentRenderId = scene.getRenderId();
  14864. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14865. var selfRenderId = this._renderId;
  14866. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14867. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14868. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14869. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14870. }
  14871. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14872. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14873. this._batchCache.mustReturn = true;
  14874. return this._batchCache;
  14875. }
  14876. if (currentRenderId !== selfRenderId) {
  14877. this._batchCache.renderSelf[subMeshId] = false;
  14878. }
  14879. }
  14880. this._renderIdForInstances[subMeshId] = currentRenderId;
  14881. }
  14882. return this._batchCache;
  14883. };
  14884. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14885. var visibleInstances = batch.visibleInstances[subMesh._id];
  14886. var matricesCount = visibleInstances.length + 1;
  14887. var bufferSize = matricesCount * 16 * 4;
  14888. while (this._instancesBufferSize < bufferSize) {
  14889. this._instancesBufferSize *= 2;
  14890. }
  14891. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14892. if (this._worldMatricesInstancesBuffer) {
  14893. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14894. }
  14895. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14896. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14897. }
  14898. var offset = 0;
  14899. var instancesCount = 0;
  14900. var world = this.getWorldMatrix();
  14901. if (batch.renderSelf[subMesh._id]) {
  14902. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14903. offset += 16;
  14904. instancesCount++;
  14905. }
  14906. if (visibleInstances) {
  14907. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14908. var instance = visibleInstances[instanceIndex];
  14909. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14910. offset += 16;
  14911. instancesCount++;
  14912. }
  14913. }
  14914. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14915. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14916. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14917. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14918. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14919. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14920. this._draw(subMesh, fillMode, instancesCount);
  14921. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14922. };
  14923. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14924. var scene = this.getScene();
  14925. var engine = scene.getEngine();
  14926. if (hardwareInstancedRendering) {
  14927. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14928. }
  14929. else {
  14930. if (batch.renderSelf[subMesh._id]) {
  14931. // Draw
  14932. if (onBeforeDraw) {
  14933. onBeforeDraw(false, this.getWorldMatrix());
  14934. }
  14935. this._draw(subMesh, fillMode);
  14936. }
  14937. if (batch.visibleInstances[subMesh._id]) {
  14938. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14939. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14940. // World
  14941. var world = instance.getWorldMatrix();
  14942. if (onBeforeDraw) {
  14943. onBeforeDraw(true, world);
  14944. }
  14945. // Draw
  14946. this._draw(subMesh, fillMode);
  14947. }
  14948. }
  14949. }
  14950. };
  14951. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14952. var scene = this.getScene();
  14953. // Managing instances
  14954. var batch = this._getInstancesRenderList(subMesh._id);
  14955. if (batch.mustReturn) {
  14956. return;
  14957. }
  14958. // Checking geometry state
  14959. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14960. return;
  14961. }
  14962. var callbackIndex;
  14963. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14964. this._onBeforeRenderCallbacks[callbackIndex](this);
  14965. }
  14966. var engine = scene.getEngine();
  14967. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14968. // Material
  14969. var effectiveMaterial = subMesh.getMaterial();
  14970. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14971. return;
  14972. }
  14973. // Outline - step 1
  14974. var savedDepthWrite = engine.getDepthWrite();
  14975. if (this.renderOutline) {
  14976. engine.setDepthWrite(false);
  14977. scene.getOutlineRenderer().render(subMesh, batch);
  14978. engine.setDepthWrite(savedDepthWrite);
  14979. }
  14980. effectiveMaterial._preBind();
  14981. var effect = effectiveMaterial.getEffect();
  14982. // Bind
  14983. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14984. this._bind(subMesh, effect, fillMode);
  14985. var world = this.getWorldMatrix();
  14986. effectiveMaterial.bind(world, this);
  14987. // Alpha mode
  14988. if (enableAlphaMode) {
  14989. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14990. }
  14991. // Draw
  14992. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14993. if (isInstance) {
  14994. effectiveMaterial.bindOnlyWorldMatrix(world);
  14995. }
  14996. });
  14997. // Unbind
  14998. effectiveMaterial.unbind();
  14999. // Outline - step 2
  15000. if (this.renderOutline && savedDepthWrite) {
  15001. engine.setDepthWrite(true);
  15002. engine.setColorWrite(false);
  15003. scene.getOutlineRenderer().render(subMesh, batch);
  15004. engine.setColorWrite(true);
  15005. }
  15006. // Overlay
  15007. if (this.renderOverlay) {
  15008. var currentMode = engine.getAlphaMode();
  15009. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15010. scene.getOutlineRenderer().render(subMesh, batch, true);
  15011. engine.setAlphaMode(currentMode);
  15012. }
  15013. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15014. this._onAfterRenderCallbacks[callbackIndex](this);
  15015. }
  15016. };
  15017. Mesh.prototype.getEmittedParticleSystems = function () {
  15018. var results = new Array();
  15019. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15020. var particleSystem = this.getScene().particleSystems[index];
  15021. if (particleSystem.emitter === this) {
  15022. results.push(particleSystem);
  15023. }
  15024. }
  15025. return results;
  15026. };
  15027. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15028. var results = new Array();
  15029. var descendants = this.getDescendants();
  15030. descendants.push(this);
  15031. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15032. var particleSystem = this.getScene().particleSystems[index];
  15033. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15034. results.push(particleSystem);
  15035. }
  15036. }
  15037. return results;
  15038. };
  15039. Mesh.prototype.getChildren = function () {
  15040. var results = [];
  15041. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15042. var mesh = this.getScene().meshes[index];
  15043. if (mesh.parent === this) {
  15044. results.push(mesh);
  15045. }
  15046. }
  15047. return results;
  15048. };
  15049. Mesh.prototype._checkDelayState = function () {
  15050. var _this = this;
  15051. var that = this;
  15052. var scene = this.getScene();
  15053. if (this._geometry) {
  15054. this._geometry.load(scene);
  15055. }
  15056. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15057. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15058. scene._addPendingData(that);
  15059. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15060. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15061. if (data instanceof ArrayBuffer) {
  15062. _this._delayLoadingFunction(data, _this);
  15063. }
  15064. else {
  15065. _this._delayLoadingFunction(JSON.parse(data), _this);
  15066. }
  15067. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15068. scene._removePendingData(_this);
  15069. }, function () { }, scene.database, getBinaryData);
  15070. }
  15071. };
  15072. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15073. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15074. return false;
  15075. }
  15076. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15077. return false;
  15078. }
  15079. this._checkDelayState();
  15080. return true;
  15081. };
  15082. Mesh.prototype.setMaterialByID = function (id) {
  15083. var materials = this.getScene().materials;
  15084. var index;
  15085. for (index = 0; index < materials.length; index++) {
  15086. if (materials[index].id === id) {
  15087. this.material = materials[index];
  15088. return;
  15089. }
  15090. }
  15091. // Multi
  15092. var multiMaterials = this.getScene().multiMaterials;
  15093. for (index = 0; index < multiMaterials.length; index++) {
  15094. if (multiMaterials[index].id === id) {
  15095. this.material = multiMaterials[index];
  15096. return;
  15097. }
  15098. }
  15099. };
  15100. Mesh.prototype.getAnimatables = function () {
  15101. var results = [];
  15102. if (this.material) {
  15103. results.push(this.material);
  15104. }
  15105. if (this.skeleton) {
  15106. results.push(this.skeleton);
  15107. }
  15108. return results;
  15109. };
  15110. // Geometry
  15111. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15112. // Position
  15113. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15114. return;
  15115. }
  15116. this._resetPointsArrayCache();
  15117. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15118. var temp = [];
  15119. var index;
  15120. for (index = 0; index < data.length; index += 3) {
  15121. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15122. }
  15123. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15124. // Normals
  15125. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15126. return;
  15127. }
  15128. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15129. temp = [];
  15130. for (index = 0; index < data.length; index += 3) {
  15131. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15132. }
  15133. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15134. // flip faces?
  15135. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15136. this.flipFaces();
  15137. }
  15138. };
  15139. // Will apply current transform to mesh and reset world matrix
  15140. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15141. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15142. this.scaling.copyFromFloats(1, 1, 1);
  15143. this.position.copyFromFloats(0, 0, 0);
  15144. this.rotation.copyFromFloats(0, 0, 0);
  15145. //only if quaternion is already set
  15146. if (this.rotationQuaternion) {
  15147. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15148. }
  15149. this._worldMatrix = BABYLON.Matrix.Identity();
  15150. };
  15151. // Cache
  15152. Mesh.prototype._resetPointsArrayCache = function () {
  15153. this._positions = null;
  15154. };
  15155. Mesh.prototype._generatePointsArray = function () {
  15156. if (this._positions)
  15157. return true;
  15158. this._positions = [];
  15159. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15160. if (!data) {
  15161. return false;
  15162. }
  15163. for (var index = 0; index < data.length; index += 3) {
  15164. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15165. }
  15166. return true;
  15167. };
  15168. // Clone
  15169. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15170. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15171. };
  15172. // Dispose
  15173. Mesh.prototype.dispose = function (doNotRecurse) {
  15174. if (this._geometry) {
  15175. this._geometry.releaseForMesh(this, true);
  15176. }
  15177. // Instances
  15178. if (this._worldMatricesInstancesBuffer) {
  15179. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15180. this._worldMatricesInstancesBuffer = null;
  15181. }
  15182. while (this.instances.length) {
  15183. this.instances[0].dispose();
  15184. }
  15185. _super.prototype.dispose.call(this, doNotRecurse);
  15186. };
  15187. // Geometric tools
  15188. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15189. var _this = this;
  15190. var scene = this.getScene();
  15191. var onload = function (img) {
  15192. // Getting height map data
  15193. var canvas = document.createElement("canvas");
  15194. var context = canvas.getContext("2d");
  15195. var heightMapWidth = img.width;
  15196. var heightMapHeight = img.height;
  15197. canvas.width = heightMapWidth;
  15198. canvas.height = heightMapHeight;
  15199. context.drawImage(img, 0, 0);
  15200. // Create VertexData from map data
  15201. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15202. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15203. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15204. //execute success callback, if set
  15205. if (onSuccess) {
  15206. onSuccess(_this);
  15207. }
  15208. };
  15209. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15210. };
  15211. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15212. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15213. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15214. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15215. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15216. return;
  15217. }
  15218. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15219. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15220. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15221. var position = BABYLON.Vector3.Zero();
  15222. var normal = BABYLON.Vector3.Zero();
  15223. var uv = BABYLON.Vector2.Zero();
  15224. for (var index = 0; index < positions.length; index += 3) {
  15225. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15226. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15227. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15228. // Compute height
  15229. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15230. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15231. var pos = (u + v * heightMapWidth) * 4;
  15232. var r = buffer[pos] / 255.0;
  15233. var g = buffer[pos + 1] / 255.0;
  15234. var b = buffer[pos + 2] / 255.0;
  15235. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15236. normal.normalize();
  15237. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15238. position = position.add(normal);
  15239. position.toArray(positions, index);
  15240. }
  15241. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15242. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15243. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15244. };
  15245. Mesh.prototype.convertToFlatShadedMesh = function () {
  15246. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15247. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15248. var kinds = this.getVerticesDataKinds();
  15249. var vbs = [];
  15250. var data = [];
  15251. var newdata = [];
  15252. var updatableNormals = false;
  15253. var kindIndex;
  15254. var kind;
  15255. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15256. kind = kinds[kindIndex];
  15257. var vertexBuffer = this.getVertexBuffer(kind);
  15258. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15259. updatableNormals = vertexBuffer.isUpdatable();
  15260. kinds.splice(kindIndex, 1);
  15261. kindIndex--;
  15262. continue;
  15263. }
  15264. vbs[kind] = vertexBuffer;
  15265. data[kind] = vbs[kind].getData();
  15266. newdata[kind] = [];
  15267. }
  15268. // Save previous submeshes
  15269. var previousSubmeshes = this.subMeshes.slice(0);
  15270. var indices = this.getIndices();
  15271. var totalIndices = this.getTotalIndices();
  15272. // Generating unique vertices per face
  15273. var index;
  15274. for (index = 0; index < totalIndices; index++) {
  15275. var vertexIndex = indices[index];
  15276. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15277. kind = kinds[kindIndex];
  15278. var stride = vbs[kind].getStrideSize();
  15279. for (var offset = 0; offset < stride; offset++) {
  15280. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15281. }
  15282. }
  15283. }
  15284. // Updating faces & normal
  15285. var normals = [];
  15286. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15287. for (index = 0; index < totalIndices; index += 3) {
  15288. indices[index] = index;
  15289. indices[index + 1] = index + 1;
  15290. indices[index + 2] = index + 2;
  15291. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15292. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15293. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15294. var p1p2 = p1.subtract(p2);
  15295. var p3p2 = p3.subtract(p2);
  15296. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15297. // Store same normals for every vertex
  15298. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15299. normals.push(normal.x);
  15300. normals.push(normal.y);
  15301. normals.push(normal.z);
  15302. }
  15303. }
  15304. this.setIndices(indices);
  15305. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15306. // Updating vertex buffers
  15307. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15308. kind = kinds[kindIndex];
  15309. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15310. }
  15311. // Updating submeshes
  15312. this.releaseSubMeshes();
  15313. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15314. var previousOne = previousSubmeshes[submeshIndex];
  15315. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15316. }
  15317. this.synchronizeInstances();
  15318. };
  15319. Mesh.prototype.convertToUnIndexedMesh = function () {
  15320. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15321. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15322. var kinds = this.getVerticesDataKinds();
  15323. var vbs = [];
  15324. var data = [];
  15325. var newdata = [];
  15326. var updatableNormals = false;
  15327. var kindIndex;
  15328. var kind;
  15329. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15330. kind = kinds[kindIndex];
  15331. var vertexBuffer = this.getVertexBuffer(kind);
  15332. vbs[kind] = vertexBuffer;
  15333. data[kind] = vbs[kind].getData();
  15334. newdata[kind] = [];
  15335. }
  15336. // Save previous submeshes
  15337. var previousSubmeshes = this.subMeshes.slice(0);
  15338. var indices = this.getIndices();
  15339. var totalIndices = this.getTotalIndices();
  15340. // Generating unique vertices per face
  15341. var index;
  15342. for (index = 0; index < totalIndices; index++) {
  15343. var vertexIndex = indices[index];
  15344. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15345. kind = kinds[kindIndex];
  15346. var stride = vbs[kind].getStrideSize();
  15347. for (var offset = 0; offset < stride; offset++) {
  15348. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15349. }
  15350. }
  15351. }
  15352. // Updating indices
  15353. for (index = 0; index < totalIndices; index += 3) {
  15354. indices[index] = index;
  15355. indices[index + 1] = index + 1;
  15356. indices[index + 2] = index + 2;
  15357. }
  15358. this.setIndices(indices);
  15359. // Updating vertex buffers
  15360. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15361. kind = kinds[kindIndex];
  15362. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15363. }
  15364. // Updating submeshes
  15365. this.releaseSubMeshes();
  15366. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15367. var previousOne = previousSubmeshes[submeshIndex];
  15368. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15369. }
  15370. this._unIndexed = true;
  15371. this.synchronizeInstances();
  15372. };
  15373. // will inverse faces orientations, and invert normals too if specified
  15374. Mesh.prototype.flipFaces = function (flipNormals) {
  15375. if (flipNormals === void 0) { flipNormals = false; }
  15376. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15377. var i;
  15378. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15379. for (i = 0; i < vertex_data.normals.length; i++) {
  15380. vertex_data.normals[i] *= -1;
  15381. }
  15382. }
  15383. var temp;
  15384. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15385. // reassign indices
  15386. temp = vertex_data.indices[i + 1];
  15387. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15388. vertex_data.indices[i + 2] = temp;
  15389. }
  15390. vertex_data.applyToMesh(this);
  15391. };
  15392. // Instances
  15393. Mesh.prototype.createInstance = function (name) {
  15394. return new BABYLON.InstancedMesh(name, this);
  15395. };
  15396. Mesh.prototype.synchronizeInstances = function () {
  15397. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15398. var instance = this.instances[instanceIndex];
  15399. instance._syncSubMeshes();
  15400. }
  15401. };
  15402. /**
  15403. * Simplify the mesh according to the given array of settings.
  15404. * Function will return immediately and will simplify async.
  15405. * @param settings a collection of simplification settings.
  15406. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15407. * @param type the type of simplification to run.
  15408. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15409. */
  15410. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15411. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15412. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15413. this.getScene().simplificationQueue.addTask({
  15414. settings: settings,
  15415. parallelProcessing: parallelProcessing,
  15416. mesh: this,
  15417. simplificationType: simplificationType,
  15418. successCallback: successCallback
  15419. });
  15420. };
  15421. /**
  15422. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15423. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15424. * This should be used together with the simplification to avoid disappearing triangles.
  15425. * @param successCallback an optional success callback to be called after the optimization finished.
  15426. */
  15427. Mesh.prototype.optimizeIndices = function (successCallback) {
  15428. var _this = this;
  15429. var indices = this.getIndices();
  15430. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15431. var vectorPositions = [];
  15432. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15433. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15434. }
  15435. var dupes = [];
  15436. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15437. var realPos = vectorPositions.length - 1 - iteration;
  15438. var testedPosition = vectorPositions[realPos];
  15439. for (var j = 0; j < realPos; ++j) {
  15440. var againstPosition = vectorPositions[j];
  15441. if (testedPosition.equals(againstPosition)) {
  15442. dupes[realPos] = j;
  15443. break;
  15444. }
  15445. }
  15446. }, function () {
  15447. for (var i = 0; i < indices.length; ++i) {
  15448. indices[i] = dupes[indices[i]] || indices[i];
  15449. }
  15450. //indices are now reordered
  15451. var originalSubMeshes = _this.subMeshes.slice(0);
  15452. _this.setIndices(indices);
  15453. _this.subMeshes = originalSubMeshes;
  15454. if (successCallback) {
  15455. successCallback(_this);
  15456. }
  15457. });
  15458. };
  15459. // Statics
  15460. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15461. var mesh = new Mesh(parsedMesh.name, scene);
  15462. mesh.id = parsedMesh.id;
  15463. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15464. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15465. if (parsedMesh.rotationQuaternion) {
  15466. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15467. }
  15468. else if (parsedMesh.rotation) {
  15469. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15470. }
  15471. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15472. if (parsedMesh.localMatrix) {
  15473. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15474. }
  15475. else if (parsedMesh.pivotMatrix) {
  15476. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15477. }
  15478. mesh.setEnabled(parsedMesh.isEnabled);
  15479. mesh.isVisible = parsedMesh.isVisible;
  15480. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15481. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15482. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15483. if (parsedMesh.applyFog !== undefined) {
  15484. mesh.applyFog = parsedMesh.applyFog;
  15485. }
  15486. if (parsedMesh.pickable !== undefined) {
  15487. mesh.isPickable = parsedMesh.pickable;
  15488. }
  15489. if (parsedMesh.alphaIndex !== undefined) {
  15490. mesh.alphaIndex = parsedMesh.alphaIndex;
  15491. }
  15492. mesh.receiveShadows = parsedMesh.receiveShadows;
  15493. mesh.billboardMode = parsedMesh.billboardMode;
  15494. if (parsedMesh.visibility !== undefined) {
  15495. mesh.visibility = parsedMesh.visibility;
  15496. }
  15497. mesh.checkCollisions = parsedMesh.checkCollisions;
  15498. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15499. // freezeWorldMatrix
  15500. if (parsedMesh.freezeWorldMatrix) {
  15501. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15502. }
  15503. // Parent
  15504. if (parsedMesh.parentId) {
  15505. mesh._waitingParentId = parsedMesh.parentId;
  15506. }
  15507. // Actions
  15508. if (parsedMesh.actions !== undefined) {
  15509. mesh._waitingActions = parsedMesh.actions;
  15510. }
  15511. // Geometry
  15512. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15513. if (parsedMesh.delayLoadingFile) {
  15514. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15515. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15516. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15517. if (parsedMesh._binaryInfo) {
  15518. mesh._binaryInfo = parsedMesh._binaryInfo;
  15519. }
  15520. mesh._delayInfo = [];
  15521. if (parsedMesh.hasUVs) {
  15522. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15523. }
  15524. if (parsedMesh.hasUVs2) {
  15525. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15526. }
  15527. if (parsedMesh.hasUVs3) {
  15528. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15529. }
  15530. if (parsedMesh.hasUVs4) {
  15531. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15532. }
  15533. if (parsedMesh.hasUVs5) {
  15534. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15535. }
  15536. if (parsedMesh.hasUVs6) {
  15537. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15538. }
  15539. if (parsedMesh.hasColors) {
  15540. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15541. }
  15542. if (parsedMesh.hasMatricesIndices) {
  15543. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15544. }
  15545. if (parsedMesh.hasMatricesWeights) {
  15546. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15547. }
  15548. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15549. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15550. mesh._checkDelayState();
  15551. }
  15552. }
  15553. else {
  15554. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15555. }
  15556. // Material
  15557. if (parsedMesh.materialId) {
  15558. mesh.setMaterialByID(parsedMesh.materialId);
  15559. }
  15560. else {
  15561. mesh.material = null;
  15562. }
  15563. // Skeleton
  15564. if (parsedMesh.skeletonId > -1) {
  15565. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15566. if (parsedMesh.numBoneInfluencers) {
  15567. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15568. }
  15569. }
  15570. // Physics
  15571. if (parsedMesh.physicsImpostor) {
  15572. if (!scene.isPhysicsEnabled()) {
  15573. scene.enablePhysics();
  15574. }
  15575. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15576. }
  15577. // Animations
  15578. if (parsedMesh.animations) {
  15579. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15580. var parsedAnimation = parsedMesh.animations[animationIndex];
  15581. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15582. }
  15583. }
  15584. if (parsedMesh.autoAnimate) {
  15585. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15586. }
  15587. // Layer Mask
  15588. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15589. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15590. }
  15591. else {
  15592. mesh.layerMask = 0x0FFFFFFF;
  15593. }
  15594. // Instances
  15595. if (parsedMesh.instances) {
  15596. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15597. var parsedInstance = parsedMesh.instances[index];
  15598. var instance = mesh.createInstance(parsedInstance.name);
  15599. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15600. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15601. if (parsedInstance.rotationQuaternion) {
  15602. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15603. }
  15604. else if (parsedInstance.rotation) {
  15605. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15606. }
  15607. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15608. instance.checkCollisions = mesh.checkCollisions;
  15609. if (parsedMesh.animations) {
  15610. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15611. parsedAnimation = parsedMesh.animations[animationIndex];
  15612. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15613. }
  15614. }
  15615. }
  15616. }
  15617. return mesh;
  15618. };
  15619. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15620. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15621. pathArray: pathArray,
  15622. closeArray: closeArray,
  15623. closePath: closePath,
  15624. offset: offset,
  15625. updatable: updatable,
  15626. sideOrientation: sideOrientation,
  15627. instance: instance
  15628. }, scene);
  15629. };
  15630. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15631. var options = {
  15632. radius: radius,
  15633. tessellation: tessellation,
  15634. sideOrientation: sideOrientation,
  15635. updatable: updatable
  15636. };
  15637. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15638. };
  15639. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15640. var options = {
  15641. size: size,
  15642. sideOrientation: sideOrientation,
  15643. updatable: updatable
  15644. };
  15645. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15646. };
  15647. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15648. var options = {
  15649. segments: segments,
  15650. diameterX: diameter,
  15651. diameterY: diameter,
  15652. diameterZ: diameter,
  15653. sideOrientation: sideOrientation,
  15654. updatable: updatable
  15655. };
  15656. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15657. };
  15658. // Cylinder and cone
  15659. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15660. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15661. if (scene !== undefined) {
  15662. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15663. updatable = scene;
  15664. }
  15665. scene = subdivisions;
  15666. subdivisions = 1;
  15667. }
  15668. var options = {
  15669. height: height,
  15670. diameterTop: diameterTop,
  15671. diameterBottom: diameterBottom,
  15672. tessellation: tessellation,
  15673. subdivisions: subdivisions,
  15674. sideOrientation: sideOrientation,
  15675. updatable: updatable
  15676. };
  15677. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15678. };
  15679. // Torus (Code from SharpDX.org)
  15680. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15681. var options = {
  15682. diameter: diameter,
  15683. thickness: thickness,
  15684. tessellation: tessellation,
  15685. sideOrientation: sideOrientation,
  15686. updatable: updatable
  15687. };
  15688. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15689. };
  15690. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15691. var options = {
  15692. radius: radius,
  15693. tube: tube,
  15694. radialSegments: radialSegments,
  15695. tubularSegments: tubularSegments,
  15696. p: p,
  15697. q: q,
  15698. sideOrientation: sideOrientation,
  15699. updatable: updatable
  15700. };
  15701. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15702. };
  15703. // Lines
  15704. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15705. var options = {
  15706. points: points,
  15707. updatable: updatable,
  15708. instance: instance
  15709. };
  15710. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15711. };
  15712. // Dashed Lines
  15713. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15714. var options = {
  15715. points: points,
  15716. dashSize: dashSize,
  15717. gapSize: gapSize,
  15718. dashNb: dashNb,
  15719. updatable: updatable
  15720. };
  15721. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15722. };
  15723. // Extrusion
  15724. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15725. var options = {
  15726. shape: shape,
  15727. path: path,
  15728. scale: scale,
  15729. rotation: rotation,
  15730. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15731. sideOrientation: sideOrientation,
  15732. instance: instance,
  15733. updatable: updatable
  15734. };
  15735. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15736. };
  15737. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15738. var options = {
  15739. shape: shape,
  15740. path: path,
  15741. scaleFunction: scaleFunction,
  15742. rotationFunction: rotationFunction,
  15743. ribbonCloseArray: ribbonCloseArray,
  15744. ribbonClosePath: ribbonClosePath,
  15745. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15746. sideOrientation: sideOrientation,
  15747. instance: instance,
  15748. updatable: updatable
  15749. };
  15750. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15751. };
  15752. // Lathe
  15753. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15754. var options = {
  15755. shape: shape,
  15756. radius: radius,
  15757. tessellation: tessellation,
  15758. sideOrientation: sideOrientation,
  15759. updatable: updatable
  15760. };
  15761. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15762. };
  15763. // Plane & ground
  15764. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15765. var options = {
  15766. size: size,
  15767. width: size,
  15768. height: size,
  15769. sideOrientation: sideOrientation,
  15770. updatable: updatable
  15771. };
  15772. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15773. };
  15774. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15775. var options = {
  15776. width: width,
  15777. height: height,
  15778. subdivisions: subdivisions,
  15779. updatable: updatable
  15780. };
  15781. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15782. };
  15783. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15784. var options = {
  15785. xmin: xmin,
  15786. zmin: zmin,
  15787. xmax: xmax,
  15788. zmax: zmax,
  15789. subdivisions: subdivisions,
  15790. precision: precision,
  15791. updatable: updatable
  15792. };
  15793. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15794. };
  15795. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15796. var options = {
  15797. width: width,
  15798. height: height,
  15799. subdivisions: subdivisions,
  15800. minHeight: minHeight,
  15801. maxHeight: maxHeight,
  15802. updatable: updatable,
  15803. onReady: onReady
  15804. };
  15805. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15806. };
  15807. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15808. var options = {
  15809. path: path,
  15810. radius: radius,
  15811. tessellation: tessellation,
  15812. radiusFunction: radiusFunction,
  15813. arc: 1,
  15814. cap: cap,
  15815. updatable: updatable,
  15816. sideOrientation: sideOrientation,
  15817. instance: instance
  15818. };
  15819. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15820. };
  15821. Mesh.CreatePolyhedron = function (name, options, scene) {
  15822. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15823. };
  15824. Mesh.CreateIcoSphere = function (name, options, scene) {
  15825. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15826. };
  15827. // Decals
  15828. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15829. var options = {
  15830. position: position,
  15831. normal: normal,
  15832. size: size,
  15833. angle: angle
  15834. };
  15835. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15836. };
  15837. // Skeletons
  15838. /**
  15839. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15840. */
  15841. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15842. var source;
  15843. if (!this._sourcePositions) {
  15844. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15845. this._sourcePositions = new Float32Array(source);
  15846. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15847. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15848. }
  15849. }
  15850. return this._sourcePositions;
  15851. };
  15852. /**
  15853. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15854. */
  15855. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15856. var source;
  15857. if (!this._sourceNormals) {
  15858. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15859. this._sourceNormals = new Float32Array(source);
  15860. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15861. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15862. }
  15863. }
  15864. return this._sourceNormals;
  15865. };
  15866. /**
  15867. * Update the vertex buffers by applying transformation from the bones
  15868. * @param {skeleton} skeleton to apply
  15869. */
  15870. Mesh.prototype.applySkeleton = function (skeleton) {
  15871. if (!this.geometry) {
  15872. return;
  15873. }
  15874. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  15875. return;
  15876. }
  15877. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  15878. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15879. return this;
  15880. }
  15881. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15882. return this;
  15883. }
  15884. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15885. return this;
  15886. }
  15887. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15888. return this;
  15889. }
  15890. if (!this._sourcePositions) {
  15891. this.setPositionsForCPUSkinning();
  15892. }
  15893. if (!this._sourceNormals) {
  15894. this.setNormalsForCPUSkinning();
  15895. }
  15896. // positionsData checks for not being Float32Array will only pass at most once
  15897. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15898. if (!(positionsData instanceof Float32Array)) {
  15899. positionsData = new Float32Array(positionsData);
  15900. }
  15901. // normalsData checks for not being Float32Array will only pass at most once
  15902. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15903. if (!(normalsData instanceof Float32Array)) {
  15904. normalsData = new Float32Array(normalsData);
  15905. }
  15906. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15907. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15908. var needExtras = this.numBoneInfluencers > 4;
  15909. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15910. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15911. var skeletonMatrices = skeleton.getTransformMatrices();
  15912. var tempVector3 = BABYLON.Vector3.Zero();
  15913. var finalMatrix = new BABYLON.Matrix();
  15914. var tempMatrix = new BABYLON.Matrix();
  15915. var matWeightIdx = 0;
  15916. var inf;
  15917. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15918. var weight;
  15919. for (inf = 0; inf < 4; inf++) {
  15920. weight = matricesWeightsData[matWeightIdx + inf];
  15921. if (weight > 0) {
  15922. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15923. finalMatrix.addToSelf(tempMatrix);
  15924. }
  15925. else
  15926. break;
  15927. }
  15928. if (needExtras) {
  15929. for (inf = 0; inf < 4; inf++) {
  15930. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15931. if (weight > 0) {
  15932. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15933. finalMatrix.addToSelf(tempMatrix);
  15934. }
  15935. else
  15936. break;
  15937. }
  15938. }
  15939. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15940. tempVector3.toArray(positionsData, index);
  15941. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15942. tempVector3.toArray(normalsData, index);
  15943. finalMatrix.reset();
  15944. }
  15945. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15946. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15947. return this;
  15948. };
  15949. // Tools
  15950. Mesh.MinMax = function (meshes) {
  15951. var minVector = null;
  15952. var maxVector = null;
  15953. for (var i in meshes) {
  15954. var mesh = meshes[i];
  15955. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15956. if (!minVector) {
  15957. minVector = boundingBox.minimumWorld;
  15958. maxVector = boundingBox.maximumWorld;
  15959. continue;
  15960. }
  15961. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15962. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15963. }
  15964. return {
  15965. min: minVector,
  15966. max: maxVector
  15967. };
  15968. };
  15969. Mesh.Center = function (meshesOrMinMaxVector) {
  15970. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15971. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15972. };
  15973. /**
  15974. * Merge the array of meshes into a single mesh for performance reasons.
  15975. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15976. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15977. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15978. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15979. */
  15980. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15981. if (disposeSource === void 0) { disposeSource = true; }
  15982. var index;
  15983. if (!allow32BitsIndices) {
  15984. var totalVertices = 0;
  15985. // Counting vertices
  15986. for (index = 0; index < meshes.length; index++) {
  15987. if (meshes[index]) {
  15988. totalVertices += meshes[index].getTotalVertices();
  15989. if (totalVertices > 65536) {
  15990. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15991. return null;
  15992. }
  15993. }
  15994. }
  15995. }
  15996. // Merge
  15997. var vertexData;
  15998. var otherVertexData;
  15999. var source;
  16000. for (index = 0; index < meshes.length; index++) {
  16001. if (meshes[index]) {
  16002. meshes[index].computeWorldMatrix(true);
  16003. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16004. otherVertexData.transform(meshes[index].getWorldMatrix());
  16005. if (vertexData) {
  16006. vertexData.merge(otherVertexData);
  16007. }
  16008. else {
  16009. vertexData = otherVertexData;
  16010. source = meshes[index];
  16011. }
  16012. }
  16013. }
  16014. if (!meshSubclass) {
  16015. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16016. }
  16017. vertexData.applyToMesh(meshSubclass);
  16018. // Setting properties
  16019. meshSubclass.material = source.material;
  16020. meshSubclass.checkCollisions = source.checkCollisions;
  16021. // Cleaning
  16022. if (disposeSource) {
  16023. for (index = 0; index < meshes.length; index++) {
  16024. if (meshes[index]) {
  16025. meshes[index].dispose();
  16026. }
  16027. }
  16028. }
  16029. return meshSubclass;
  16030. };
  16031. // Consts
  16032. Mesh._FRONTSIDE = 0;
  16033. Mesh._BACKSIDE = 1;
  16034. Mesh._DOUBLESIDE = 2;
  16035. Mesh._DEFAULTSIDE = 0;
  16036. Mesh._NO_CAP = 0;
  16037. Mesh._CAP_START = 1;
  16038. Mesh._CAP_END = 2;
  16039. Mesh._CAP_ALL = 3;
  16040. return Mesh;
  16041. })(BABYLON.AbstractMesh);
  16042. BABYLON.Mesh = Mesh;
  16043. })(BABYLON || (BABYLON = {}));
  16044. var BABYLON;
  16045. (function (BABYLON) {
  16046. var SubMesh = (function () {
  16047. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16048. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16049. this.materialIndex = materialIndex;
  16050. this.verticesStart = verticesStart;
  16051. this.verticesCount = verticesCount;
  16052. this.indexStart = indexStart;
  16053. this.indexCount = indexCount;
  16054. this._renderId = 0;
  16055. this._mesh = mesh;
  16056. this._renderingMesh = renderingMesh || mesh;
  16057. mesh.subMeshes.push(this);
  16058. this._trianglePlanes = [];
  16059. this._id = mesh.subMeshes.length - 1;
  16060. if (createBoundingBox) {
  16061. this.refreshBoundingInfo();
  16062. mesh.computeWorldMatrix(true);
  16063. }
  16064. }
  16065. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16066. get: function () {
  16067. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16068. },
  16069. enumerable: true,
  16070. configurable: true
  16071. });
  16072. SubMesh.prototype.getBoundingInfo = function () {
  16073. if (this.IsGlobal) {
  16074. return this._mesh.getBoundingInfo();
  16075. }
  16076. return this._boundingInfo;
  16077. };
  16078. SubMesh.prototype.getMesh = function () {
  16079. return this._mesh;
  16080. };
  16081. SubMesh.prototype.getRenderingMesh = function () {
  16082. return this._renderingMesh;
  16083. };
  16084. SubMesh.prototype.getMaterial = function () {
  16085. var rootMaterial = this._renderingMesh.material;
  16086. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16087. var multiMaterial = rootMaterial;
  16088. return multiMaterial.getSubMaterial(this.materialIndex);
  16089. }
  16090. if (!rootMaterial) {
  16091. return this._mesh.getScene().defaultMaterial;
  16092. }
  16093. return rootMaterial;
  16094. };
  16095. // Methods
  16096. SubMesh.prototype.refreshBoundingInfo = function () {
  16097. if (this.IsGlobal) {
  16098. return;
  16099. }
  16100. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16101. if (!data) {
  16102. this._boundingInfo = this._mesh._boundingInfo;
  16103. return;
  16104. }
  16105. var indices = this._renderingMesh.getIndices();
  16106. var extend;
  16107. //is this the only submesh?
  16108. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16109. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16110. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16111. }
  16112. else {
  16113. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16114. }
  16115. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16116. };
  16117. SubMesh.prototype._checkCollision = function (collider) {
  16118. return this.getBoundingInfo()._checkCollision(collider);
  16119. };
  16120. SubMesh.prototype.updateBoundingInfo = function (world) {
  16121. if (!this.getBoundingInfo()) {
  16122. this.refreshBoundingInfo();
  16123. }
  16124. this.getBoundingInfo()._update(world);
  16125. };
  16126. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16127. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16128. };
  16129. SubMesh.prototype.render = function (enableAlphaMode) {
  16130. this._renderingMesh.render(this, enableAlphaMode);
  16131. };
  16132. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16133. if (!this._linesIndexBuffer) {
  16134. var linesIndices = [];
  16135. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16136. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16137. }
  16138. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16139. this.linesIndexCount = linesIndices.length;
  16140. }
  16141. return this._linesIndexBuffer;
  16142. };
  16143. SubMesh.prototype.canIntersects = function (ray) {
  16144. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16145. };
  16146. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16147. var intersectInfo = null;
  16148. // Triangles test
  16149. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16150. var p0 = positions[indices[index]];
  16151. var p1 = positions[indices[index + 1]];
  16152. var p2 = positions[indices[index + 2]];
  16153. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16154. if (currentIntersectInfo) {
  16155. if (currentIntersectInfo.distance < 0) {
  16156. continue;
  16157. }
  16158. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16159. intersectInfo = currentIntersectInfo;
  16160. intersectInfo.faceId = index / 3;
  16161. if (fastCheck) {
  16162. break;
  16163. }
  16164. }
  16165. }
  16166. }
  16167. return intersectInfo;
  16168. };
  16169. // Clone
  16170. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16171. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16172. if (!this.IsGlobal) {
  16173. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16174. }
  16175. return result;
  16176. };
  16177. // Dispose
  16178. SubMesh.prototype.dispose = function () {
  16179. if (this._linesIndexBuffer) {
  16180. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16181. this._linesIndexBuffer = null;
  16182. }
  16183. // Remove from mesh
  16184. var index = this._mesh.subMeshes.indexOf(this);
  16185. this._mesh.subMeshes.splice(index, 1);
  16186. };
  16187. // Statics
  16188. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16189. var minVertexIndex = Number.MAX_VALUE;
  16190. var maxVertexIndex = -Number.MAX_VALUE;
  16191. renderingMesh = renderingMesh || mesh;
  16192. var indices = renderingMesh.getIndices();
  16193. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16194. var vertexIndex = indices[index];
  16195. if (vertexIndex < minVertexIndex)
  16196. minVertexIndex = vertexIndex;
  16197. if (vertexIndex > maxVertexIndex)
  16198. maxVertexIndex = vertexIndex;
  16199. }
  16200. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16201. };
  16202. return SubMesh;
  16203. })();
  16204. BABYLON.SubMesh = SubMesh;
  16205. })(BABYLON || (BABYLON = {}));
  16206. var BABYLON;
  16207. (function (BABYLON) {
  16208. var MeshBuilder = (function () {
  16209. function MeshBuilder() {
  16210. }
  16211. MeshBuilder.CreateBox = function (name, options, scene) {
  16212. var box = new BABYLON.Mesh(name, scene);
  16213. var vertexData = BABYLON.VertexData.CreateBox(options);
  16214. vertexData.applyToMesh(box, options.updatable);
  16215. return box;
  16216. };
  16217. MeshBuilder.CreateSphere = function (name, options, scene) {
  16218. var sphere = new BABYLON.Mesh(name, scene);
  16219. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16220. vertexData.applyToMesh(sphere, options.updatable);
  16221. return sphere;
  16222. };
  16223. MeshBuilder.CreateDisc = function (name, options, scene) {
  16224. var disc = new BABYLON.Mesh(name, scene);
  16225. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16226. vertexData.applyToMesh(disc, options.updatable);
  16227. return disc;
  16228. };
  16229. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16230. var sphere = new BABYLON.Mesh(name, scene);
  16231. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16232. vertexData.applyToMesh(sphere, options.updatable);
  16233. return sphere;
  16234. };
  16235. ;
  16236. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16237. var pathArray = options.pathArray;
  16238. var closeArray = options.closeArray;
  16239. var closePath = options.closePath;
  16240. var offset = options.offset;
  16241. var sideOrientation = options.sideOrientation;
  16242. var instance = options.instance;
  16243. var updatable = options.updatable;
  16244. if (instance) {
  16245. // positionFunction : ribbon case
  16246. // only pathArray and sideOrientation parameters are taken into account for positions update
  16247. var positionFunction = function (positions) {
  16248. var minlg = pathArray[0].length;
  16249. var i = 0;
  16250. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16251. for (var si = 1; si <= ns; si++) {
  16252. for (var p = 0; p < pathArray.length; p++) {
  16253. var path = pathArray[p];
  16254. var l = path.length;
  16255. minlg = (minlg < l) ? minlg : l;
  16256. var j = 0;
  16257. while (j < minlg) {
  16258. positions[i] = path[j].x;
  16259. positions[i + 1] = path[j].y;
  16260. positions[i + 2] = path[j].z;
  16261. j++;
  16262. i += 3;
  16263. }
  16264. if (instance._closePath) {
  16265. positions[i] = path[0].x;
  16266. positions[i + 1] = path[0].y;
  16267. positions[i + 2] = path[0].z;
  16268. i += 3;
  16269. }
  16270. }
  16271. }
  16272. };
  16273. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16274. positionFunction(positions);
  16275. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16276. if (!(instance.areNormalsFrozen)) {
  16277. var indices = instance.getIndices();
  16278. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16279. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16280. if (instance._closePath) {
  16281. var indexFirst = 0;
  16282. var indexLast = 0;
  16283. for (var p = 0; p < pathArray.length; p++) {
  16284. indexFirst = instance._idx[p] * 3;
  16285. if (p + 1 < pathArray.length) {
  16286. indexLast = (instance._idx[p + 1] - 1) * 3;
  16287. }
  16288. else {
  16289. indexLast = normals.length - 3;
  16290. }
  16291. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16292. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16293. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16294. normals[indexLast] = normals[indexFirst];
  16295. normals[indexLast + 1] = normals[indexFirst + 1];
  16296. normals[indexLast + 2] = normals[indexFirst + 2];
  16297. }
  16298. }
  16299. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16300. }
  16301. return instance;
  16302. }
  16303. else {
  16304. var ribbon = new BABYLON.Mesh(name, scene);
  16305. ribbon.sideOrientation = sideOrientation;
  16306. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16307. if (closePath) {
  16308. ribbon._idx = vertexData._idx;
  16309. }
  16310. ribbon._closePath = closePath;
  16311. ribbon._closeArray = closeArray;
  16312. vertexData.applyToMesh(ribbon, updatable);
  16313. return ribbon;
  16314. }
  16315. };
  16316. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16317. var cylinder = new BABYLON.Mesh(name, scene);
  16318. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16319. vertexData.applyToMesh(cylinder, options.updatable);
  16320. return cylinder;
  16321. };
  16322. MeshBuilder.CreateTorus = function (name, options, scene) {
  16323. var torus = new BABYLON.Mesh(name, scene);
  16324. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16325. vertexData.applyToMesh(torus, options.updatable);
  16326. return torus;
  16327. };
  16328. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16329. var torusKnot = new BABYLON.Mesh(name, scene);
  16330. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16331. vertexData.applyToMesh(torusKnot, options.updatable);
  16332. return torusKnot;
  16333. };
  16334. MeshBuilder.CreateLines = function (name, options, scene) {
  16335. var instance = options.instance;
  16336. var points = options.points;
  16337. if (instance) {
  16338. var positionFunction = function (positions) {
  16339. var i = 0;
  16340. for (var p = 0; p < points.length; p++) {
  16341. positions[i] = points[p].x;
  16342. positions[i + 1] = points[p].y;
  16343. positions[i + 2] = points[p].z;
  16344. i += 3;
  16345. }
  16346. };
  16347. instance.updateMeshPositions(positionFunction, false);
  16348. return instance;
  16349. }
  16350. // lines creation
  16351. var lines = new BABYLON.LinesMesh(name, scene);
  16352. var vertexData = BABYLON.VertexData.CreateLines(options);
  16353. vertexData.applyToMesh(lines, options.updatable);
  16354. return lines;
  16355. };
  16356. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16357. var points = options.points;
  16358. var instance = options.instance;
  16359. var gapSize = options.gapSize;
  16360. var dashNb = options.dashNb;
  16361. var dashSize = options.dashSize;
  16362. if (instance) {
  16363. var positionFunction = function (positions) {
  16364. var curvect = BABYLON.Vector3.Zero();
  16365. var nbSeg = positions.length / 6;
  16366. var lg = 0;
  16367. var nb = 0;
  16368. var shft = 0;
  16369. var dashshft = 0;
  16370. var curshft = 0;
  16371. var p = 0;
  16372. var i = 0;
  16373. var j = 0;
  16374. for (i = 0; i < points.length - 1; i++) {
  16375. points[i + 1].subtractToRef(points[i], curvect);
  16376. lg += curvect.length();
  16377. }
  16378. shft = lg / nbSeg;
  16379. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16380. for (i = 0; i < points.length - 1; i++) {
  16381. points[i + 1].subtractToRef(points[i], curvect);
  16382. nb = Math.floor(curvect.length() / shft);
  16383. curvect.normalize();
  16384. j = 0;
  16385. while (j < nb && p < positions.length) {
  16386. curshft = shft * j;
  16387. positions[p] = points[i].x + curshft * curvect.x;
  16388. positions[p + 1] = points[i].y + curshft * curvect.y;
  16389. positions[p + 2] = points[i].z + curshft * curvect.z;
  16390. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16391. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16392. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16393. p += 6;
  16394. j++;
  16395. }
  16396. }
  16397. while (p < positions.length) {
  16398. positions[p] = points[i].x;
  16399. positions[p + 1] = points[i].y;
  16400. positions[p + 2] = points[i].z;
  16401. p += 3;
  16402. }
  16403. };
  16404. instance.updateMeshPositions(positionFunction, false);
  16405. return instance;
  16406. }
  16407. // dashed lines creation
  16408. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16409. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16410. vertexData.applyToMesh(dashedLines, options.updatable);
  16411. dashedLines.dashSize = dashSize;
  16412. dashedLines.gapSize = gapSize;
  16413. return dashedLines;
  16414. };
  16415. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16416. var path = options.path;
  16417. var shape = options.shape;
  16418. var scale = options.scale || 1;
  16419. var rotation = options.rotation || 0;
  16420. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16421. var updatable = options.updatable;
  16422. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16423. var instance = options.instance;
  16424. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16425. };
  16426. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16427. var path = options.path;
  16428. var shape = options.shape;
  16429. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16430. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16431. var ribbonCloseArray = options.ribbonCloseArray || false;
  16432. var ribbonClosePath = options.ribbonClosePath || false;
  16433. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16434. var updatable = options.updatable;
  16435. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16436. var instance = options.instance;
  16437. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16438. };
  16439. MeshBuilder.CreateLathe = function (name, options, scene) {
  16440. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16441. var closed = (options.closed === undefined) ? true : options.closed;
  16442. var shape = options.shape;
  16443. var radius = options.radius || 1;
  16444. var tessellation = options.tessellation || 64;
  16445. var updatable = options.updatable;
  16446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16447. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16448. var pi2 = Math.PI * 2;
  16449. var paths = new Array();
  16450. var i = 0;
  16451. var p = 0;
  16452. var step = pi2 / tessellation * arc;
  16453. var rotated;
  16454. var path = new Array();
  16455. ;
  16456. for (i = 0; i <= tessellation; i++) {
  16457. var path = [];
  16458. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16459. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16460. path.push(new BABYLON.Vector3(shape[0].x, shape[0].y, shape[0].x));
  16461. }
  16462. for (p = 0; p < shape.length; p++) {
  16463. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16464. path.push(rotated);
  16465. }
  16466. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16467. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16468. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16469. }
  16470. paths.push(path);
  16471. }
  16472. // lathe ribbon
  16473. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16474. return lathe;
  16475. };
  16476. MeshBuilder.CreatePlane = function (name, options, scene) {
  16477. var plane = new BABYLON.Mesh(name, scene);
  16478. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16479. vertexData.applyToMesh(plane, options.updatable);
  16480. if (options.sourcePlane) {
  16481. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16482. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16483. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16484. plane.rotate(vectorProduct, product);
  16485. }
  16486. return plane;
  16487. };
  16488. MeshBuilder.CreateGround = function (name, options, scene) {
  16489. var ground = new BABYLON.GroundMesh(name, scene);
  16490. ground._setReady(false);
  16491. ground._subdivisions = options.subdivisions || 1;
  16492. ground._width = options.width || 1;
  16493. ground._height = options.height || 1;
  16494. ground._maxX = ground._width / 2;
  16495. ground._maxZ = ground._height / 2;
  16496. ground._minX = -ground._maxX;
  16497. ground._minZ = -ground._maxZ;
  16498. var vertexData = BABYLON.VertexData.CreateGround(options);
  16499. vertexData.applyToMesh(ground, options.updatable);
  16500. ground._setReady(true);
  16501. return ground;
  16502. };
  16503. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16504. var tiledGround = new BABYLON.Mesh(name, scene);
  16505. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16506. vertexData.applyToMesh(tiledGround, options.updatable);
  16507. return tiledGround;
  16508. };
  16509. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16510. var width = options.width || 10;
  16511. var height = options.height || 10;
  16512. var subdivisions = options.subdivisions || 1;
  16513. var minHeight = options.minHeight;
  16514. var maxHeight = options.maxHeight || 10;
  16515. var updatable = options.updatable;
  16516. var onReady = options.onReady;
  16517. var ground = new BABYLON.GroundMesh(name, scene);
  16518. ground._subdivisions = subdivisions;
  16519. ground._width = width;
  16520. ground._height = height;
  16521. ground._maxX = ground._width / 2;
  16522. ground._maxZ = ground._height / 2;
  16523. ground._minX = -ground._maxX;
  16524. ground._minZ = -ground._maxZ;
  16525. ground._setReady(false);
  16526. var onload = function (img) {
  16527. // Getting height map data
  16528. var canvas = document.createElement("canvas");
  16529. var context = canvas.getContext("2d");
  16530. var bufferWidth = img.width;
  16531. var bufferHeight = img.height;
  16532. canvas.width = bufferWidth;
  16533. canvas.height = bufferHeight;
  16534. context.drawImage(img, 0, 0);
  16535. // Create VertexData from map data
  16536. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16537. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16538. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16539. width: width, height: height,
  16540. subdivisions: subdivisions,
  16541. minHeight: minHeight, maxHeight: maxHeight,
  16542. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16543. });
  16544. vertexData.applyToMesh(ground, updatable);
  16545. ground._setReady(true);
  16546. //execute ready callback, if set
  16547. if (onReady) {
  16548. onReady(ground);
  16549. }
  16550. };
  16551. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16552. return ground;
  16553. };
  16554. MeshBuilder.CreateTube = function (name, options, scene) {
  16555. var path = options.path;
  16556. var radius = options.radius || 1;
  16557. var tessellation = options.tessellation || 64;
  16558. var radiusFunction = options.radiusFunction;
  16559. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16560. var updatable = options.updatable;
  16561. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16562. var instance = options.instance;
  16563. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16564. // tube geometry
  16565. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16566. var tangents = path3D.getTangents();
  16567. var normals = path3D.getNormals();
  16568. var distances = path3D.getDistances();
  16569. var pi2 = Math.PI * 2;
  16570. var step = pi2 / tessellation * arc;
  16571. var returnRadius = function () { return radius; };
  16572. var radiusFunctionFinal = radiusFunction || returnRadius;
  16573. var circlePath;
  16574. var rad;
  16575. var normal;
  16576. var rotated;
  16577. var rotationMatrix = BABYLON.Matrix.Zero();
  16578. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16579. for (var i = 0; i < path.length; i++) {
  16580. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16581. circlePath = Array(); // current circle array
  16582. normal = normals[i]; // current normal
  16583. for (var t = 0; t < tessellation; t++) {
  16584. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16585. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16586. circlePath.push(rotated);
  16587. }
  16588. circlePaths[index] = circlePath;
  16589. index++;
  16590. }
  16591. // cap
  16592. var capPath = function (nbPoints, pathIndex) {
  16593. var pointCap = Array();
  16594. for (var i = 0; i < nbPoints; i++) {
  16595. pointCap.push(path[pathIndex]);
  16596. }
  16597. return pointCap;
  16598. };
  16599. switch (cap) {
  16600. case BABYLON.Mesh.NO_CAP:
  16601. break;
  16602. case BABYLON.Mesh.CAP_START:
  16603. circlePaths[0] = capPath(tessellation, 0);
  16604. circlePaths[1] = circlePaths[2].slice(0);
  16605. break;
  16606. case BABYLON.Mesh.CAP_END:
  16607. circlePaths[index] = circlePaths[index - 1].slice(0);
  16608. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16609. break;
  16610. case BABYLON.Mesh.CAP_ALL:
  16611. circlePaths[0] = capPath(tessellation, 0);
  16612. circlePaths[1] = circlePaths[2].slice(0);
  16613. circlePaths[index] = circlePaths[index - 1].slice(0);
  16614. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16615. break;
  16616. default:
  16617. break;
  16618. }
  16619. return circlePaths;
  16620. };
  16621. var path3D;
  16622. var pathArray;
  16623. if (instance) {
  16624. var arc = options.arc || instance.arc;
  16625. path3D = (instance.path3D).update(path);
  16626. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16627. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16628. instance.path3D = path3D;
  16629. instance.pathArray = pathArray;
  16630. instance.arc = arc;
  16631. return instance;
  16632. }
  16633. // tube creation
  16634. path3D = new BABYLON.Path3D(path);
  16635. var newPathArray = new Array();
  16636. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16637. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16638. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16639. tube.pathArray = pathArray;
  16640. tube.path3D = path3D;
  16641. tube.tessellation = tessellation;
  16642. tube.cap = cap;
  16643. tube.arc = options.arc;
  16644. return tube;
  16645. };
  16646. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16647. var polyhedron = new BABYLON.Mesh(name, scene);
  16648. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16649. vertexData.applyToMesh(polyhedron, options.updatable);
  16650. return polyhedron;
  16651. };
  16652. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16653. var indices = sourceMesh.getIndices();
  16654. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16655. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16656. var position = options.position || BABYLON.Vector3.Zero();
  16657. var normal = options.normal || BABYLON.Vector3.Up();
  16658. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16659. var angle = options.angle || 0;
  16660. // Getting correct rotation
  16661. if (!normal) {
  16662. var target = new BABYLON.Vector3(0, 0, 1);
  16663. var camera = sourceMesh.getScene().activeCamera;
  16664. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16665. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16666. }
  16667. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16668. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16669. var pitch = Math.atan2(normal.y, len);
  16670. // Matrix
  16671. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16672. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16673. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16674. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16675. var vertexData = new BABYLON.VertexData();
  16676. vertexData.indices = [];
  16677. vertexData.positions = [];
  16678. vertexData.normals = [];
  16679. vertexData.uvs = [];
  16680. var currentVertexDataIndex = 0;
  16681. var extractDecalVector3 = function (indexId) {
  16682. var vertexId = indices[indexId];
  16683. var result = new BABYLON.PositionNormalVertex();
  16684. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16685. // Send vector to decal local world
  16686. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16687. // Get normal
  16688. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16689. return result;
  16690. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16691. var clip = function (vertices, axis) {
  16692. if (vertices.length === 0) {
  16693. return vertices;
  16694. }
  16695. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16696. var clipVertices = function (v0, v1) {
  16697. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16698. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16699. };
  16700. var result = new Array();
  16701. for (var index = 0; index < vertices.length; index += 3) {
  16702. var v1Out;
  16703. var v2Out;
  16704. var v3Out;
  16705. var total = 0;
  16706. var nV1, nV2, nV3, nV4;
  16707. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16708. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16709. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16710. v1Out = d1 > 0;
  16711. v2Out = d2 > 0;
  16712. v3Out = d3 > 0;
  16713. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16714. switch (total) {
  16715. case 0:
  16716. result.push(vertices[index]);
  16717. result.push(vertices[index + 1]);
  16718. result.push(vertices[index + 2]);
  16719. break;
  16720. case 1:
  16721. if (v1Out) {
  16722. nV1 = vertices[index + 1];
  16723. nV2 = vertices[index + 2];
  16724. nV3 = clipVertices(vertices[index], nV1);
  16725. nV4 = clipVertices(vertices[index], nV2);
  16726. }
  16727. if (v2Out) {
  16728. nV1 = vertices[index];
  16729. nV2 = vertices[index + 2];
  16730. nV3 = clipVertices(vertices[index + 1], nV1);
  16731. nV4 = clipVertices(vertices[index + 1], nV2);
  16732. result.push(nV3);
  16733. result.push(nV2.clone());
  16734. result.push(nV1.clone());
  16735. result.push(nV2.clone());
  16736. result.push(nV3.clone());
  16737. result.push(nV4);
  16738. break;
  16739. }
  16740. if (v3Out) {
  16741. nV1 = vertices[index];
  16742. nV2 = vertices[index + 1];
  16743. nV3 = clipVertices(vertices[index + 2], nV1);
  16744. nV4 = clipVertices(vertices[index + 2], nV2);
  16745. }
  16746. result.push(nV1.clone());
  16747. result.push(nV2.clone());
  16748. result.push(nV3);
  16749. result.push(nV4);
  16750. result.push(nV3.clone());
  16751. result.push(nV2.clone());
  16752. break;
  16753. case 2:
  16754. if (!v1Out) {
  16755. nV1 = vertices[index].clone();
  16756. nV2 = clipVertices(nV1, vertices[index + 1]);
  16757. nV3 = clipVertices(nV1, vertices[index + 2]);
  16758. result.push(nV1);
  16759. result.push(nV2);
  16760. result.push(nV3);
  16761. }
  16762. if (!v2Out) {
  16763. nV1 = vertices[index + 1].clone();
  16764. nV2 = clipVertices(nV1, vertices[index + 2]);
  16765. nV3 = clipVertices(nV1, vertices[index]);
  16766. result.push(nV1);
  16767. result.push(nV2);
  16768. result.push(nV3);
  16769. }
  16770. if (!v3Out) {
  16771. nV1 = vertices[index + 2].clone();
  16772. nV2 = clipVertices(nV1, vertices[index]);
  16773. nV3 = clipVertices(nV1, vertices[index + 1]);
  16774. result.push(nV1);
  16775. result.push(nV2);
  16776. result.push(nV3);
  16777. }
  16778. break;
  16779. case 3:
  16780. break;
  16781. }
  16782. }
  16783. return result;
  16784. };
  16785. for (var index = 0; index < indices.length; index += 3) {
  16786. var faceVertices = new Array();
  16787. faceVertices.push(extractDecalVector3(index));
  16788. faceVertices.push(extractDecalVector3(index + 1));
  16789. faceVertices.push(extractDecalVector3(index + 2));
  16790. // Clip
  16791. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16792. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16793. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16794. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16795. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16796. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16797. if (faceVertices.length === 0) {
  16798. continue;
  16799. }
  16800. // Add UVs and get back to world
  16801. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16802. var vertex = faceVertices[vIndex];
  16803. //TODO check for Int32Array
  16804. vertexData.indices.push(currentVertexDataIndex);
  16805. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16806. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16807. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16808. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16809. currentVertexDataIndex++;
  16810. }
  16811. }
  16812. // Return mesh
  16813. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16814. vertexData.applyToMesh(decal);
  16815. decal.position = position.clone();
  16816. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16817. return decal;
  16818. };
  16819. // Privates
  16820. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16821. // extrusion geometry
  16822. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16823. var tangents = path3D.getTangents();
  16824. var normals = path3D.getNormals();
  16825. var binormals = path3D.getBinormals();
  16826. var distances = path3D.getDistances();
  16827. var angle = 0;
  16828. var returnScale = function () { return scale; };
  16829. var returnRotation = function () { return rotation; };
  16830. var rotate = custom ? rotateFunction : returnRotation;
  16831. var scl = custom ? scaleFunction : returnScale;
  16832. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16833. var rotationMatrix = BABYLON.Matrix.Zero();
  16834. for (var i = 0; i < curve.length; i++) {
  16835. var shapePath = new Array();
  16836. var angleStep = rotate(i, distances[i]);
  16837. var scaleRatio = scl(i, distances[i]);
  16838. for (var p = 0; p < shape.length; p++) {
  16839. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16840. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16841. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16842. shapePath.push(rotated);
  16843. }
  16844. shapePaths[index] = shapePath;
  16845. angle += angleStep;
  16846. index++;
  16847. }
  16848. // cap
  16849. var capPath = function (shapePath) {
  16850. var pointCap = Array();
  16851. var barycenter = BABYLON.Vector3.Zero();
  16852. var i;
  16853. for (i = 0; i < shapePath.length; i++) {
  16854. barycenter.addInPlace(shapePath[i]);
  16855. }
  16856. barycenter.scaleInPlace(1 / shapePath.length);
  16857. for (i = 0; i < shapePath.length; i++) {
  16858. pointCap.push(barycenter);
  16859. }
  16860. return pointCap;
  16861. };
  16862. switch (cap) {
  16863. case BABYLON.Mesh.NO_CAP:
  16864. break;
  16865. case BABYLON.Mesh.CAP_START:
  16866. shapePaths[0] = capPath(shapePaths[2]);
  16867. shapePaths[1] = shapePaths[2].slice(0);
  16868. break;
  16869. case BABYLON.Mesh.CAP_END:
  16870. shapePaths[index] = shapePaths[index - 1];
  16871. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16872. break;
  16873. case BABYLON.Mesh.CAP_ALL:
  16874. shapePaths[0] = capPath(shapePaths[2]);
  16875. shapePaths[1] = shapePaths[2].slice(0);
  16876. shapePaths[index] = shapePaths[index - 1];
  16877. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16878. break;
  16879. default:
  16880. break;
  16881. }
  16882. return shapePaths;
  16883. };
  16884. var path3D;
  16885. var pathArray;
  16886. if (instance) {
  16887. path3D = (instance.path3D).update(curve);
  16888. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16889. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16890. return instance;
  16891. }
  16892. // extruded shape creation
  16893. path3D = new BABYLON.Path3D(curve);
  16894. var newShapePaths = new Array();
  16895. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16896. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16897. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16898. extrudedGeneric.pathArray = pathArray;
  16899. extrudedGeneric.path3D = path3D;
  16900. extrudedGeneric.cap = cap;
  16901. return extrudedGeneric;
  16902. };
  16903. return MeshBuilder;
  16904. })();
  16905. BABYLON.MeshBuilder = MeshBuilder;
  16906. })(BABYLON || (BABYLON = {}));
  16907. var BABYLON;
  16908. (function (BABYLON) {
  16909. var BaseTexture = (function () {
  16910. function BaseTexture(scene) {
  16911. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16912. this.hasAlpha = false;
  16913. this.getAlphaFromRGB = false;
  16914. this.level = 1;
  16915. this.isCube = false;
  16916. this.isRenderTarget = false;
  16917. this.animations = new Array();
  16918. this.coordinatesIndex = 0;
  16919. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16920. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16921. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16922. this.anisotropicFilteringLevel = 4;
  16923. this._scene = scene;
  16924. this._scene.textures.push(this);
  16925. }
  16926. BaseTexture.prototype.getScene = function () {
  16927. return this._scene;
  16928. };
  16929. BaseTexture.prototype.getTextureMatrix = function () {
  16930. return null;
  16931. };
  16932. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16933. return null;
  16934. };
  16935. BaseTexture.prototype.getInternalTexture = function () {
  16936. return this._texture;
  16937. };
  16938. BaseTexture.prototype.isReady = function () {
  16939. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16940. return true;
  16941. }
  16942. if (this._texture) {
  16943. return this._texture.isReady;
  16944. }
  16945. return false;
  16946. };
  16947. BaseTexture.prototype.getSize = function () {
  16948. if (this._texture._width) {
  16949. return { width: this._texture._width, height: this._texture._height };
  16950. }
  16951. if (this._texture._size) {
  16952. return { width: this._texture._size, height: this._texture._size };
  16953. }
  16954. return { width: 0, height: 0 };
  16955. };
  16956. BaseTexture.prototype.getBaseSize = function () {
  16957. if (!this.isReady())
  16958. return { width: 0, height: 0 };
  16959. if (this._texture._size) {
  16960. return { width: this._texture._size, height: this._texture._size };
  16961. }
  16962. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16963. };
  16964. BaseTexture.prototype.scale = function (ratio) {
  16965. };
  16966. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16967. get: function () {
  16968. return false;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16974. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16975. for (var index = 0; index < texturesCache.length; index++) {
  16976. var texturesCacheEntry = texturesCache[index];
  16977. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16978. texturesCache.splice(index, 1);
  16979. return;
  16980. }
  16981. }
  16982. };
  16983. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16984. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16985. for (var index = 0; index < texturesCache.length; index++) {
  16986. var texturesCacheEntry = texturesCache[index];
  16987. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16988. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16989. texturesCacheEntry.references++;
  16990. return texturesCacheEntry;
  16991. }
  16992. }
  16993. }
  16994. return null;
  16995. };
  16996. BaseTexture.prototype.delayLoad = function () {
  16997. };
  16998. BaseTexture.prototype.clone = function () {
  16999. return null;
  17000. };
  17001. BaseTexture.prototype.releaseInternalTexture = function () {
  17002. if (this._texture) {
  17003. this._scene.getEngine().releaseInternalTexture(this._texture);
  17004. delete this._texture;
  17005. }
  17006. };
  17007. BaseTexture.prototype.dispose = function () {
  17008. // Animations
  17009. this.getScene().stopAnimation(this);
  17010. // Remove from scene
  17011. var index = this._scene.textures.indexOf(this);
  17012. if (index >= 0) {
  17013. this._scene.textures.splice(index, 1);
  17014. }
  17015. if (this._texture === undefined) {
  17016. return;
  17017. }
  17018. // Release
  17019. this.releaseInternalTexture();
  17020. // Callback
  17021. if (this.onDispose) {
  17022. this.onDispose();
  17023. }
  17024. };
  17025. BaseTexture.prototype.serialize = function () {
  17026. var serializationObject = {};
  17027. if (!this.name) {
  17028. return null;
  17029. }
  17030. serializationObject.name = this.name;
  17031. serializationObject.hasAlpha = this.hasAlpha;
  17032. serializationObject.level = this.level;
  17033. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17034. serializationObject.coordinatesMode = this.coordinatesMode;
  17035. serializationObject.wrapU = this.wrapU;
  17036. serializationObject.wrapV = this.wrapV;
  17037. // Animations
  17038. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17039. return serializationObject;
  17040. };
  17041. return BaseTexture;
  17042. })();
  17043. BABYLON.BaseTexture = BaseTexture;
  17044. })(BABYLON || (BABYLON = {}));
  17045. var BABYLON;
  17046. (function (BABYLON) {
  17047. var Texture = (function (_super) {
  17048. __extends(Texture, _super);
  17049. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17050. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17051. if (onLoad === void 0) { onLoad = null; }
  17052. if (onError === void 0) { onError = null; }
  17053. if (buffer === void 0) { buffer = null; }
  17054. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17055. _super.call(this, scene);
  17056. this.uOffset = 0;
  17057. this.vOffset = 0;
  17058. this.uScale = 1.0;
  17059. this.vScale = 1.0;
  17060. this.uAng = 0;
  17061. this.vAng = 0;
  17062. this.wAng = 0;
  17063. this.name = url;
  17064. this.url = url;
  17065. this._noMipmap = noMipmap;
  17066. this._invertY = invertY;
  17067. this._samplingMode = samplingMode;
  17068. this._buffer = buffer;
  17069. this._deleteBuffer = deleteBuffer;
  17070. if (!url) {
  17071. return;
  17072. }
  17073. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17074. if (!this._texture) {
  17075. if (!scene.useDelayedTextureLoading) {
  17076. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17077. if (deleteBuffer) {
  17078. delete this._buffer;
  17079. }
  17080. }
  17081. else {
  17082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17083. }
  17084. }
  17085. else {
  17086. BABYLON.Tools.SetImmediate(function () {
  17087. if (onLoad) {
  17088. onLoad();
  17089. }
  17090. });
  17091. }
  17092. }
  17093. Texture.prototype.delayLoad = function () {
  17094. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17095. return;
  17096. }
  17097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17098. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17099. if (!this._texture) {
  17100. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17101. if (this._deleteBuffer) {
  17102. delete this._buffer;
  17103. }
  17104. }
  17105. };
  17106. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17107. if (!this._texture) {
  17108. return;
  17109. }
  17110. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17111. };
  17112. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17113. x *= this.uScale;
  17114. y *= this.vScale;
  17115. x -= 0.5 * this.uScale;
  17116. y -= 0.5 * this.vScale;
  17117. z -= 0.5;
  17118. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17119. t.x += 0.5 * this.uScale + this.uOffset;
  17120. t.y += 0.5 * this.vScale + this.vOffset;
  17121. t.z += 0.5;
  17122. };
  17123. Texture.prototype.getTextureMatrix = function () {
  17124. if (this.uOffset === this._cachedUOffset &&
  17125. this.vOffset === this._cachedVOffset &&
  17126. this.uScale === this._cachedUScale &&
  17127. this.vScale === this._cachedVScale &&
  17128. this.uAng === this._cachedUAng &&
  17129. this.vAng === this._cachedVAng &&
  17130. this.wAng === this._cachedWAng) {
  17131. return this._cachedTextureMatrix;
  17132. }
  17133. this._cachedUOffset = this.uOffset;
  17134. this._cachedVOffset = this.vOffset;
  17135. this._cachedUScale = this.uScale;
  17136. this._cachedVScale = this.vScale;
  17137. this._cachedUAng = this.uAng;
  17138. this._cachedVAng = this.vAng;
  17139. this._cachedWAng = this.wAng;
  17140. if (!this._cachedTextureMatrix) {
  17141. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17142. this._rowGenerationMatrix = new BABYLON.Matrix();
  17143. this._t0 = BABYLON.Vector3.Zero();
  17144. this._t1 = BABYLON.Vector3.Zero();
  17145. this._t2 = BABYLON.Vector3.Zero();
  17146. }
  17147. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17148. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17149. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17150. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17151. this._t1.subtractInPlace(this._t0);
  17152. this._t2.subtractInPlace(this._t0);
  17153. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17154. this._cachedTextureMatrix.m[0] = this._t1.x;
  17155. this._cachedTextureMatrix.m[1] = this._t1.y;
  17156. this._cachedTextureMatrix.m[2] = this._t1.z;
  17157. this._cachedTextureMatrix.m[4] = this._t2.x;
  17158. this._cachedTextureMatrix.m[5] = this._t2.y;
  17159. this._cachedTextureMatrix.m[6] = this._t2.z;
  17160. this._cachedTextureMatrix.m[8] = this._t0.x;
  17161. this._cachedTextureMatrix.m[9] = this._t0.y;
  17162. this._cachedTextureMatrix.m[10] = this._t0.z;
  17163. return this._cachedTextureMatrix;
  17164. };
  17165. Texture.prototype.getReflectionTextureMatrix = function () {
  17166. if (this.uOffset === this._cachedUOffset &&
  17167. this.vOffset === this._cachedVOffset &&
  17168. this.uScale === this._cachedUScale &&
  17169. this.vScale === this._cachedVScale &&
  17170. this.coordinatesMode === this._cachedCoordinatesMode) {
  17171. return this._cachedTextureMatrix;
  17172. }
  17173. if (!this._cachedTextureMatrix) {
  17174. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17175. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17176. }
  17177. this._cachedCoordinatesMode = this.coordinatesMode;
  17178. switch (this.coordinatesMode) {
  17179. case Texture.PLANAR_MODE:
  17180. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17181. this._cachedTextureMatrix[0] = this.uScale;
  17182. this._cachedTextureMatrix[5] = this.vScale;
  17183. this._cachedTextureMatrix[12] = this.uOffset;
  17184. this._cachedTextureMatrix[13] = this.vOffset;
  17185. break;
  17186. case Texture.PROJECTION_MODE:
  17187. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17188. this._projectionModeMatrix.m[0] = 0.5;
  17189. this._projectionModeMatrix.m[5] = -0.5;
  17190. this._projectionModeMatrix.m[10] = 0.0;
  17191. this._projectionModeMatrix.m[12] = 0.5;
  17192. this._projectionModeMatrix.m[13] = 0.5;
  17193. this._projectionModeMatrix.m[14] = 1.0;
  17194. this._projectionModeMatrix.m[15] = 1.0;
  17195. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17196. break;
  17197. default:
  17198. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17199. break;
  17200. }
  17201. return this._cachedTextureMatrix;
  17202. };
  17203. Texture.prototype.clone = function () {
  17204. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17205. // Base texture
  17206. newTexture.hasAlpha = this.hasAlpha;
  17207. newTexture.level = this.level;
  17208. newTexture.wrapU = this.wrapU;
  17209. newTexture.wrapV = this.wrapV;
  17210. newTexture.coordinatesIndex = this.coordinatesIndex;
  17211. newTexture.coordinatesMode = this.coordinatesMode;
  17212. // Texture
  17213. newTexture.uOffset = this.uOffset;
  17214. newTexture.vOffset = this.vOffset;
  17215. newTexture.uScale = this.uScale;
  17216. newTexture.vScale = this.vScale;
  17217. newTexture.uAng = this.uAng;
  17218. newTexture.vAng = this.vAng;
  17219. newTexture.wAng = this.wAng;
  17220. return newTexture;
  17221. };
  17222. Texture.prototype.serialize = function () {
  17223. if (!this.name) {
  17224. return null;
  17225. }
  17226. var serializationObject = _super.prototype.serialize.call(this);
  17227. serializationObject.uOffset = this.uOffset;
  17228. serializationObject.vOffset = this.vOffset;
  17229. serializationObject.uScale = this.uScale;
  17230. serializationObject.vScale = this.vScale;
  17231. serializationObject.uAng = this.uAng;
  17232. serializationObject.vAng = this.vAng;
  17233. serializationObject.wAng = this.wAng;
  17234. return serializationObject;
  17235. };
  17236. // Statics
  17237. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17238. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17239. if (onLoad === void 0) { onLoad = null; }
  17240. if (onError === void 0) { onError = null; }
  17241. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17242. };
  17243. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17244. if (parsedTexture.isCube) {
  17245. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17246. }
  17247. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17248. return null;
  17249. }
  17250. var texture;
  17251. if (parsedTexture.mirrorPlane) {
  17252. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17253. texture._waitingRenderList = parsedTexture.renderList;
  17254. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17255. }
  17256. else if (parsedTexture.isRenderTarget) {
  17257. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17258. texture._waitingRenderList = parsedTexture.renderList;
  17259. }
  17260. else {
  17261. if (parsedTexture.base64String) {
  17262. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17263. }
  17264. else {
  17265. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17266. }
  17267. }
  17268. texture.name = parsedTexture.name;
  17269. texture.hasAlpha = parsedTexture.hasAlpha;
  17270. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17271. texture.level = parsedTexture.level;
  17272. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17273. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17274. texture.uOffset = parsedTexture.uOffset;
  17275. texture.vOffset = parsedTexture.vOffset;
  17276. texture.uScale = parsedTexture.uScale;
  17277. texture.vScale = parsedTexture.vScale;
  17278. texture.uAng = parsedTexture.uAng;
  17279. texture.vAng = parsedTexture.vAng;
  17280. texture.wAng = parsedTexture.wAng;
  17281. texture.wrapU = parsedTexture.wrapU;
  17282. texture.wrapV = parsedTexture.wrapV;
  17283. // Animations
  17284. if (parsedTexture.animations) {
  17285. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17286. var parsedAnimation = parsedTexture.animations[animationIndex];
  17287. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17288. }
  17289. }
  17290. return texture;
  17291. };
  17292. // Constants
  17293. Texture.NEAREST_SAMPLINGMODE = 1;
  17294. Texture.BILINEAR_SAMPLINGMODE = 2;
  17295. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17296. Texture.EXPLICIT_MODE = 0;
  17297. Texture.SPHERICAL_MODE = 1;
  17298. Texture.PLANAR_MODE = 2;
  17299. Texture.CUBIC_MODE = 3;
  17300. Texture.PROJECTION_MODE = 4;
  17301. Texture.SKYBOX_MODE = 5;
  17302. Texture.INVCUBIC_MODE = 6;
  17303. Texture.EQUIRECTANGULAR_MODE = 7;
  17304. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17305. Texture.CLAMP_ADDRESSMODE = 0;
  17306. Texture.WRAP_ADDRESSMODE = 1;
  17307. Texture.MIRROR_ADDRESSMODE = 2;
  17308. return Texture;
  17309. })(BABYLON.BaseTexture);
  17310. BABYLON.Texture = Texture;
  17311. })(BABYLON || (BABYLON = {}));
  17312. var BABYLON;
  17313. (function (BABYLON) {
  17314. var CubeTexture = (function (_super) {
  17315. __extends(CubeTexture, _super);
  17316. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17317. _super.call(this, scene);
  17318. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17319. this.name = rootUrl;
  17320. this.url = rootUrl;
  17321. this._noMipmap = noMipmap;
  17322. this.hasAlpha = false;
  17323. if (!rootUrl) {
  17324. return;
  17325. }
  17326. this._texture = this._getFromCache(rootUrl, noMipmap);
  17327. if (!extensions) {
  17328. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17329. }
  17330. this._extensions = extensions;
  17331. if (!this._texture) {
  17332. if (!scene.useDelayedTextureLoading) {
  17333. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17334. }
  17335. else {
  17336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17337. }
  17338. }
  17339. this.isCube = true;
  17340. this._textureMatrix = BABYLON.Matrix.Identity();
  17341. }
  17342. CubeTexture.prototype.clone = function () {
  17343. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17344. // Base texture
  17345. newTexture.level = this.level;
  17346. newTexture.wrapU = this.wrapU;
  17347. newTexture.wrapV = this.wrapV;
  17348. newTexture.coordinatesIndex = this.coordinatesIndex;
  17349. newTexture.coordinatesMode = this.coordinatesMode;
  17350. return newTexture;
  17351. };
  17352. // Methods
  17353. CubeTexture.prototype.delayLoad = function () {
  17354. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17355. return;
  17356. }
  17357. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17358. this._texture = this._getFromCache(this.url, this._noMipmap);
  17359. if (!this._texture) {
  17360. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17361. }
  17362. };
  17363. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17364. return this._textureMatrix;
  17365. };
  17366. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17367. var texture = null;
  17368. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17369. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17370. texture.name = parsedTexture.name;
  17371. texture.hasAlpha = parsedTexture.hasAlpha;
  17372. texture.level = parsedTexture.level;
  17373. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17374. }
  17375. return texture;
  17376. };
  17377. CubeTexture.prototype.serialize = function () {
  17378. if (!this.name) {
  17379. return null;
  17380. }
  17381. var serializationObject = {};
  17382. serializationObject.name = this.name;
  17383. serializationObject.hasAlpha = this.hasAlpha;
  17384. serializationObject.isCube = true;
  17385. serializationObject.level = this.level;
  17386. serializationObject.coordinatesMode = this.coordinatesMode;
  17387. return serializationObject;
  17388. };
  17389. return CubeTexture;
  17390. })(BABYLON.BaseTexture);
  17391. BABYLON.CubeTexture = CubeTexture;
  17392. })(BABYLON || (BABYLON = {}));
  17393. var BABYLON;
  17394. (function (BABYLON) {
  17395. var RenderTargetTexture = (function (_super) {
  17396. __extends(RenderTargetTexture, _super);
  17397. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17398. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17399. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17400. if (isCube === void 0) { isCube = false; }
  17401. _super.call(this, null, scene, !generateMipMaps);
  17402. this.isCube = isCube;
  17403. this.renderList = new Array();
  17404. this.renderParticles = true;
  17405. this.renderSprites = false;
  17406. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17407. this._currentRefreshId = -1;
  17408. this._refreshRate = 1;
  17409. this.name = name;
  17410. this.isRenderTarget = true;
  17411. this._size = size;
  17412. this._generateMipMaps = generateMipMaps;
  17413. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17414. if (isCube) {
  17415. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17416. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17417. this._textureMatrix = BABYLON.Matrix.Identity();
  17418. }
  17419. else {
  17420. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17421. }
  17422. // Rendering groups
  17423. this._renderingManager = new BABYLON.RenderingManager(scene);
  17424. }
  17425. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17426. get: function () {
  17427. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17433. get: function () {
  17434. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17440. get: function () {
  17441. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17447. this._currentRefreshId = -1;
  17448. };
  17449. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17450. get: function () {
  17451. return this._refreshRate;
  17452. },
  17453. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17454. set: function (value) {
  17455. this._refreshRate = value;
  17456. this.resetRefreshCounter();
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. RenderTargetTexture.prototype._shouldRender = function () {
  17462. if (this._currentRefreshId === -1) {
  17463. this._currentRefreshId = 1;
  17464. return true;
  17465. }
  17466. if (this.refreshRate === this._currentRefreshId) {
  17467. this._currentRefreshId = 1;
  17468. return true;
  17469. }
  17470. this._currentRefreshId++;
  17471. return false;
  17472. };
  17473. RenderTargetTexture.prototype.isReady = function () {
  17474. if (!this.getScene().renderTargetsEnabled) {
  17475. return false;
  17476. }
  17477. return _super.prototype.isReady.call(this);
  17478. };
  17479. RenderTargetTexture.prototype.getRenderSize = function () {
  17480. return this._size;
  17481. };
  17482. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17483. get: function () {
  17484. return true;
  17485. },
  17486. enumerable: true,
  17487. configurable: true
  17488. });
  17489. RenderTargetTexture.prototype.scale = function (ratio) {
  17490. var newSize = this._size * ratio;
  17491. this.resize(newSize, this._generateMipMaps);
  17492. };
  17493. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17494. if (this.isCube) {
  17495. return this._textureMatrix;
  17496. }
  17497. return _super.prototype.getReflectionTextureMatrix.call(this);
  17498. };
  17499. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17500. this.releaseInternalTexture();
  17501. if (this.isCube) {
  17502. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17503. }
  17504. else {
  17505. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17506. }
  17507. };
  17508. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17509. var scene = this.getScene();
  17510. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17511. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17512. }
  17513. if (this._waitingRenderList) {
  17514. this.renderList = [];
  17515. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17516. var id = this._waitingRenderList[index];
  17517. this.renderList.push(scene.getMeshByID(id));
  17518. }
  17519. delete this._waitingRenderList;
  17520. }
  17521. if (this.renderList && this.renderList.length === 0) {
  17522. return;
  17523. }
  17524. // Prepare renderingManager
  17525. this._renderingManager.reset();
  17526. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17527. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17528. var mesh = currentRenderList[meshIndex];
  17529. if (mesh) {
  17530. if (!mesh.isReady()) {
  17531. // Reset _currentRefreshId
  17532. this.resetRefreshCounter();
  17533. continue;
  17534. }
  17535. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17536. mesh._activate(scene.getRenderId());
  17537. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17538. var subMesh = mesh.subMeshes[subIndex];
  17539. scene._activeIndices += subMesh.indexCount;
  17540. this._renderingManager.dispatch(subMesh);
  17541. }
  17542. }
  17543. }
  17544. }
  17545. if (this.isCube) {
  17546. for (var face = 0; face < 6; face++) {
  17547. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17548. scene.incrementRenderId();
  17549. }
  17550. }
  17551. else {
  17552. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17553. }
  17554. if (this.onAfterUnbind) {
  17555. this.onAfterUnbind();
  17556. }
  17557. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17558. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17559. }
  17560. scene.resetCachedMaterial();
  17561. };
  17562. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17563. var scene = this.getScene();
  17564. var engine = scene.getEngine();
  17565. // Bind
  17566. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17567. if (this.isCube) {
  17568. engine.bindFramebuffer(this._texture, faceIndex);
  17569. }
  17570. else {
  17571. engine.bindFramebuffer(this._texture);
  17572. }
  17573. }
  17574. if (this.onBeforeRender) {
  17575. this.onBeforeRender(faceIndex);
  17576. }
  17577. // Clear
  17578. if (this.onClear) {
  17579. this.onClear(engine);
  17580. }
  17581. else {
  17582. engine.clear(scene.clearColor, true, true);
  17583. }
  17584. if (!this._doNotChangeAspectRatio) {
  17585. scene.updateTransformMatrix(true);
  17586. }
  17587. // Render
  17588. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17589. if (useCameraPostProcess) {
  17590. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17591. }
  17592. if (!this._doNotChangeAspectRatio) {
  17593. scene.updateTransformMatrix(true);
  17594. }
  17595. if (this.onAfterRender) {
  17596. this.onAfterRender(faceIndex);
  17597. }
  17598. // Dump ?
  17599. if (dumpForDebug) {
  17600. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17601. }
  17602. // Unbind
  17603. if (!this.isCube || faceIndex === 5) {
  17604. if (this.isCube) {
  17605. if (faceIndex === 5) {
  17606. engine.generateMipMapsForCubemap(this._texture);
  17607. }
  17608. }
  17609. engine.unBindFramebuffer(this._texture, this.isCube);
  17610. }
  17611. };
  17612. RenderTargetTexture.prototype.clone = function () {
  17613. var textureSize = this.getSize();
  17614. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17615. // Base texture
  17616. newTexture.hasAlpha = this.hasAlpha;
  17617. newTexture.level = this.level;
  17618. // RenderTarget Texture
  17619. newTexture.coordinatesMode = this.coordinatesMode;
  17620. newTexture.renderList = this.renderList.slice(0);
  17621. return newTexture;
  17622. };
  17623. RenderTargetTexture.prototype.serialize = function () {
  17624. if (!this.name) {
  17625. return null;
  17626. }
  17627. var serializationObject = _super.prototype.serialize.call(this);
  17628. serializationObject.renderTargetSize = this.getRenderSize();
  17629. serializationObject.renderList = [];
  17630. for (var index = 0; index < this.renderList.length; index++) {
  17631. serializationObject.renderList.push(this.renderList[index].id);
  17632. }
  17633. return serializationObject;
  17634. };
  17635. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17636. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17637. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17638. return RenderTargetTexture;
  17639. })(BABYLON.Texture);
  17640. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17641. })(BABYLON || (BABYLON = {}));
  17642. var BABYLON;
  17643. (function (BABYLON) {
  17644. var ProceduralTexture = (function (_super) {
  17645. __extends(ProceduralTexture, _super);
  17646. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17648. _super.call(this, null, scene, !generateMipMaps);
  17649. this.isEnabled = true;
  17650. this._currentRefreshId = -1;
  17651. this._refreshRate = 1;
  17652. this._vertexDeclaration = [2];
  17653. this._vertexStrideSize = 2 * 4;
  17654. this._uniforms = new Array();
  17655. this._samplers = new Array();
  17656. this._textures = new Array();
  17657. this._floats = new Array();
  17658. this._floatsArrays = {};
  17659. this._colors3 = new Array();
  17660. this._colors4 = new Array();
  17661. this._vectors2 = new Array();
  17662. this._vectors3 = new Array();
  17663. this._matrices = new Array();
  17664. this._fallbackTextureUsed = false;
  17665. scene._proceduralTextures.push(this);
  17666. this.name = name;
  17667. this.isRenderTarget = true;
  17668. this._size = size;
  17669. this._generateMipMaps = generateMipMaps;
  17670. this.setFragment(fragment);
  17671. this._fallbackTexture = fallbackTexture;
  17672. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17673. // VBO
  17674. var vertices = [];
  17675. vertices.push(1, 1);
  17676. vertices.push(-1, 1);
  17677. vertices.push(-1, -1);
  17678. vertices.push(1, -1);
  17679. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17680. // Indices
  17681. var indices = [];
  17682. indices.push(0);
  17683. indices.push(1);
  17684. indices.push(2);
  17685. indices.push(0);
  17686. indices.push(2);
  17687. indices.push(3);
  17688. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17689. }
  17690. ProceduralTexture.prototype.reset = function () {
  17691. if (this._effect === undefined) {
  17692. return;
  17693. }
  17694. var engine = this.getScene().getEngine();
  17695. engine._releaseEffect(this._effect);
  17696. };
  17697. ProceduralTexture.prototype.isReady = function () {
  17698. var _this = this;
  17699. var engine = this.getScene().getEngine();
  17700. var shaders;
  17701. if (!this._fragment) {
  17702. return false;
  17703. }
  17704. if (this._fallbackTextureUsed) {
  17705. return true;
  17706. }
  17707. if (this._fragment.fragmentElement !== undefined) {
  17708. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17709. }
  17710. else {
  17711. shaders = { vertex: "procedural", fragment: this._fragment };
  17712. }
  17713. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17714. _this.releaseInternalTexture();
  17715. if (_this._fallbackTexture) {
  17716. _this._texture = _this._fallbackTexture._texture;
  17717. _this._texture.references++;
  17718. }
  17719. _this._fallbackTextureUsed = true;
  17720. });
  17721. return this._effect.isReady();
  17722. };
  17723. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17724. this._currentRefreshId = -1;
  17725. };
  17726. ProceduralTexture.prototype.setFragment = function (fragment) {
  17727. this._fragment = fragment;
  17728. };
  17729. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17730. get: function () {
  17731. return this._refreshRate;
  17732. },
  17733. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17734. set: function (value) {
  17735. this._refreshRate = value;
  17736. this.resetRefreshCounter();
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. ProceduralTexture.prototype._shouldRender = function () {
  17742. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17743. return false;
  17744. }
  17745. if (this._fallbackTextureUsed) {
  17746. return false;
  17747. }
  17748. if (this._currentRefreshId === -1) {
  17749. this._currentRefreshId = 1;
  17750. return true;
  17751. }
  17752. if (this.refreshRate === this._currentRefreshId) {
  17753. this._currentRefreshId = 1;
  17754. return true;
  17755. }
  17756. this._currentRefreshId++;
  17757. return false;
  17758. };
  17759. ProceduralTexture.prototype.getRenderSize = function () {
  17760. return this._size;
  17761. };
  17762. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17763. if (this._fallbackTextureUsed) {
  17764. return;
  17765. }
  17766. this.releaseInternalTexture();
  17767. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17768. };
  17769. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17770. if (this._uniforms.indexOf(uniformName) === -1) {
  17771. this._uniforms.push(uniformName);
  17772. }
  17773. };
  17774. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17775. if (this._samplers.indexOf(name) === -1) {
  17776. this._samplers.push(name);
  17777. }
  17778. this._textures[name] = texture;
  17779. return this;
  17780. };
  17781. ProceduralTexture.prototype.setFloat = function (name, value) {
  17782. this._checkUniform(name);
  17783. this._floats[name] = value;
  17784. return this;
  17785. };
  17786. ProceduralTexture.prototype.setFloats = function (name, value) {
  17787. this._checkUniform(name);
  17788. this._floatsArrays[name] = value;
  17789. return this;
  17790. };
  17791. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17792. this._checkUniform(name);
  17793. this._colors3[name] = value;
  17794. return this;
  17795. };
  17796. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17797. this._checkUniform(name);
  17798. this._colors4[name] = value;
  17799. return this;
  17800. };
  17801. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17802. this._checkUniform(name);
  17803. this._vectors2[name] = value;
  17804. return this;
  17805. };
  17806. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17807. this._checkUniform(name);
  17808. this._vectors3[name] = value;
  17809. return this;
  17810. };
  17811. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17812. this._checkUniform(name);
  17813. this._matrices[name] = value;
  17814. return this;
  17815. };
  17816. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17817. var scene = this.getScene();
  17818. var engine = scene.getEngine();
  17819. engine.bindFramebuffer(this._texture);
  17820. // Clear
  17821. engine.clear(scene.clearColor, true, true);
  17822. // Render
  17823. engine.enableEffect(this._effect);
  17824. engine.setState(false);
  17825. // Texture
  17826. for (var name in this._textures) {
  17827. this._effect.setTexture(name, this._textures[name]);
  17828. }
  17829. // Float
  17830. for (name in this._floats) {
  17831. this._effect.setFloat(name, this._floats[name]);
  17832. }
  17833. // Floats
  17834. for (name in this._floatsArrays) {
  17835. this._effect.setArray(name, this._floatsArrays[name]);
  17836. }
  17837. // Color3
  17838. for (name in this._colors3) {
  17839. this._effect.setColor3(name, this._colors3[name]);
  17840. }
  17841. // Color4
  17842. for (name in this._colors4) {
  17843. var color = this._colors4[name];
  17844. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17845. }
  17846. // Vector2
  17847. for (name in this._vectors2) {
  17848. this._effect.setVector2(name, this._vectors2[name]);
  17849. }
  17850. // Vector3
  17851. for (name in this._vectors3) {
  17852. this._effect.setVector3(name, this._vectors3[name]);
  17853. }
  17854. // Matrix
  17855. for (name in this._matrices) {
  17856. this._effect.setMatrix(name, this._matrices[name]);
  17857. }
  17858. // VBOs
  17859. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17860. // Draw order
  17861. engine.draw(true, 0, 6);
  17862. // Unbind
  17863. engine.unBindFramebuffer(this._texture);
  17864. };
  17865. ProceduralTexture.prototype.clone = function () {
  17866. var textureSize = this.getSize();
  17867. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17868. // Base texture
  17869. newTexture.hasAlpha = this.hasAlpha;
  17870. newTexture.level = this.level;
  17871. // RenderTarget Texture
  17872. newTexture.coordinatesMode = this.coordinatesMode;
  17873. return newTexture;
  17874. };
  17875. ProceduralTexture.prototype.dispose = function () {
  17876. var index = this.getScene()._proceduralTextures.indexOf(this);
  17877. if (index >= 0) {
  17878. this.getScene()._proceduralTextures.splice(index, 1);
  17879. }
  17880. _super.prototype.dispose.call(this);
  17881. };
  17882. return ProceduralTexture;
  17883. })(BABYLON.Texture);
  17884. BABYLON.ProceduralTexture = ProceduralTexture;
  17885. })(BABYLON || (BABYLON = {}));
  17886. var BABYLON;
  17887. (function (BABYLON) {
  17888. var MirrorTexture = (function (_super) {
  17889. __extends(MirrorTexture, _super);
  17890. function MirrorTexture(name, size, scene, generateMipMaps) {
  17891. var _this = this;
  17892. _super.call(this, name, size, scene, generateMipMaps, true);
  17893. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17894. this._transformMatrix = BABYLON.Matrix.Zero();
  17895. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17896. this.onBeforeRender = function () {
  17897. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17898. _this._savedViewMatrix = scene.getViewMatrix();
  17899. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17900. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17901. scene.clipPlane = _this.mirrorPlane;
  17902. scene.getEngine().cullBackFaces = false;
  17903. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17904. };
  17905. this.onAfterRender = function () {
  17906. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17907. scene.getEngine().cullBackFaces = true;
  17908. scene._mirroredCameraPosition = null;
  17909. delete scene.clipPlane;
  17910. };
  17911. }
  17912. MirrorTexture.prototype.clone = function () {
  17913. var textureSize = this.getSize();
  17914. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17915. // Base texture
  17916. newTexture.hasAlpha = this.hasAlpha;
  17917. newTexture.level = this.level;
  17918. // Mirror Texture
  17919. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17920. newTexture.renderList = this.renderList.slice(0);
  17921. return newTexture;
  17922. };
  17923. MirrorTexture.prototype.serialize = function () {
  17924. if (!this.name) {
  17925. return null;
  17926. }
  17927. var serializationObject = _super.prototype.serialize.call(this);
  17928. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17929. return serializationObject;
  17930. };
  17931. return MirrorTexture;
  17932. })(BABYLON.RenderTargetTexture);
  17933. BABYLON.MirrorTexture = MirrorTexture;
  17934. })(BABYLON || (BABYLON = {}));
  17935. var BABYLON;
  17936. (function (BABYLON) {
  17937. var DynamicTexture = (function (_super) {
  17938. __extends(DynamicTexture, _super);
  17939. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17941. _super.call(this, null, scene, !generateMipMaps);
  17942. this.name = name;
  17943. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17944. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17945. this._generateMipMaps = generateMipMaps;
  17946. if (options.getContext) {
  17947. this._canvas = options;
  17948. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17949. }
  17950. else {
  17951. this._canvas = document.createElement("canvas");
  17952. if (options.width) {
  17953. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17954. }
  17955. else {
  17956. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17957. }
  17958. }
  17959. var textureSize = this.getSize();
  17960. this._canvas.width = textureSize.width;
  17961. this._canvas.height = textureSize.height;
  17962. this._context = this._canvas.getContext("2d");
  17963. }
  17964. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17965. get: function () {
  17966. return true;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. DynamicTexture.prototype.scale = function (ratio) {
  17972. var textureSize = this.getSize();
  17973. textureSize.width *= ratio;
  17974. textureSize.height *= ratio;
  17975. this._canvas.width = textureSize.width;
  17976. this._canvas.height = textureSize.height;
  17977. this.releaseInternalTexture();
  17978. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17979. };
  17980. DynamicTexture.prototype.getContext = function () {
  17981. return this._context;
  17982. };
  17983. DynamicTexture.prototype.clear = function () {
  17984. var size = this.getSize();
  17985. this._context.fillRect(0, 0, size.width, size.height);
  17986. };
  17987. DynamicTexture.prototype.update = function (invertY) {
  17988. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17989. };
  17990. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17991. if (update === void 0) { update = true; }
  17992. var size = this.getSize();
  17993. if (clearColor) {
  17994. this._context.fillStyle = clearColor;
  17995. this._context.fillRect(0, 0, size.width, size.height);
  17996. }
  17997. this._context.font = font;
  17998. if (x === null) {
  17999. var textSize = this._context.measureText(text);
  18000. x = (size.width - textSize.width) / 2;
  18001. }
  18002. this._context.fillStyle = color;
  18003. this._context.fillText(text, x, y);
  18004. if (update) {
  18005. this.update(invertY);
  18006. }
  18007. };
  18008. DynamicTexture.prototype.clone = function () {
  18009. var textureSize = this.getSize();
  18010. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18011. // Base texture
  18012. newTexture.hasAlpha = this.hasAlpha;
  18013. newTexture.level = this.level;
  18014. // Dynamic Texture
  18015. newTexture.wrapU = this.wrapU;
  18016. newTexture.wrapV = this.wrapV;
  18017. return newTexture;
  18018. };
  18019. return DynamicTexture;
  18020. })(BABYLON.Texture);
  18021. BABYLON.DynamicTexture = DynamicTexture;
  18022. })(BABYLON || (BABYLON = {}));
  18023. var BABYLON;
  18024. (function (BABYLON) {
  18025. var VideoTexture = (function (_super) {
  18026. __extends(VideoTexture, _super);
  18027. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18028. var _this = this;
  18029. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18030. if (invertY === void 0) { invertY = false; }
  18031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18032. _super.call(this, null, scene, !generateMipMaps, invertY);
  18033. this._autoLaunch = true;
  18034. this.name = name;
  18035. this.video = document.createElement("video");
  18036. this.video.autoplay = false;
  18037. this.video.loop = true;
  18038. this.video.addEventListener("canplaythrough", function () {
  18039. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18040. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18041. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18042. }
  18043. else {
  18044. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18045. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18046. generateMipMaps = false;
  18047. }
  18048. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18049. _this._texture.isReady = true;
  18050. });
  18051. urls.forEach(function (url) {
  18052. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18053. var source = document.createElement("source");
  18054. source.src = url;
  18055. _this.video.appendChild(source);
  18056. });
  18057. this._lastUpdate = BABYLON.Tools.Now;
  18058. }
  18059. VideoTexture.prototype.update = function () {
  18060. if (this._autoLaunch) {
  18061. this._autoLaunch = false;
  18062. this.video.play();
  18063. }
  18064. var now = BABYLON.Tools.Now;
  18065. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18066. return false;
  18067. }
  18068. this._lastUpdate = now;
  18069. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18070. return true;
  18071. };
  18072. return VideoTexture;
  18073. })(BABYLON.Texture);
  18074. BABYLON.VideoTexture = VideoTexture;
  18075. })(BABYLON || (BABYLON = {}));
  18076. var BABYLON;
  18077. (function (BABYLON) {
  18078. var CustomProceduralTexture = (function (_super) {
  18079. __extends(CustomProceduralTexture, _super);
  18080. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18081. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18082. this._animate = true;
  18083. this._time = 0;
  18084. this._texturePath = texturePath;
  18085. //Try to load json
  18086. this.loadJson(texturePath);
  18087. this.refreshRate = 1;
  18088. }
  18089. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18090. var _this = this;
  18091. var that = this;
  18092. function noConfigFile() {
  18093. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18094. try {
  18095. that.setFragment(that._texturePath);
  18096. }
  18097. catch (ex) {
  18098. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18099. }
  18100. }
  18101. var configFileUrl = jsonUrl + "/config.json";
  18102. var xhr = new XMLHttpRequest();
  18103. xhr.open("GET", configFileUrl, true);
  18104. xhr.addEventListener("load", function () {
  18105. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18106. try {
  18107. _this._config = JSON.parse(xhr.response);
  18108. _this.updateShaderUniforms();
  18109. _this.updateTextures();
  18110. _this.setFragment(_this._texturePath + "/custom");
  18111. _this._animate = _this._config.animate;
  18112. _this.refreshRate = _this._config.refreshrate;
  18113. }
  18114. catch (ex) {
  18115. noConfigFile();
  18116. }
  18117. }
  18118. else {
  18119. noConfigFile();
  18120. }
  18121. }, false);
  18122. xhr.addEventListener("error", function () {
  18123. noConfigFile();
  18124. }, false);
  18125. try {
  18126. xhr.send();
  18127. }
  18128. catch (ex) {
  18129. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18130. }
  18131. };
  18132. CustomProceduralTexture.prototype.isReady = function () {
  18133. if (!_super.prototype.isReady.call(this)) {
  18134. return false;
  18135. }
  18136. for (var name in this._textures) {
  18137. var texture = this._textures[name];
  18138. if (!texture.isReady()) {
  18139. return false;
  18140. }
  18141. }
  18142. return true;
  18143. };
  18144. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18145. if (this._animate) {
  18146. this._time += this.getScene().getAnimationRatio() * 0.03;
  18147. this.updateShaderUniforms();
  18148. }
  18149. _super.prototype.render.call(this, useCameraPostProcess);
  18150. };
  18151. CustomProceduralTexture.prototype.updateTextures = function () {
  18152. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18153. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18154. }
  18155. };
  18156. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18157. if (this._config) {
  18158. for (var j = 0; j < this._config.uniforms.length; j++) {
  18159. var uniform = this._config.uniforms[j];
  18160. switch (uniform.type) {
  18161. case "float":
  18162. this.setFloat(uniform.name, uniform.value);
  18163. break;
  18164. case "color3":
  18165. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18166. break;
  18167. case "color4":
  18168. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18169. break;
  18170. case "vector2":
  18171. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18172. break;
  18173. case "vector3":
  18174. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18175. break;
  18176. }
  18177. }
  18178. }
  18179. this.setFloat("time", this._time);
  18180. };
  18181. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18182. get: function () {
  18183. return this._animate;
  18184. },
  18185. set: function (value) {
  18186. this._animate = value;
  18187. },
  18188. enumerable: true,
  18189. configurable: true
  18190. });
  18191. return CustomProceduralTexture;
  18192. })(BABYLON.ProceduralTexture);
  18193. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18194. })(BABYLON || (BABYLON = {}));
  18195. var BABYLON;
  18196. (function (BABYLON) {
  18197. var EffectFallbacks = (function () {
  18198. function EffectFallbacks() {
  18199. this._defines = {};
  18200. this._currentRank = 32;
  18201. this._maxRank = -1;
  18202. }
  18203. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18204. if (!this._defines[rank]) {
  18205. if (rank < this._currentRank) {
  18206. this._currentRank = rank;
  18207. }
  18208. if (rank > this._maxRank) {
  18209. this._maxRank = rank;
  18210. }
  18211. this._defines[rank] = new Array();
  18212. }
  18213. this._defines[rank].push(define);
  18214. };
  18215. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18216. this._meshRank = rank;
  18217. this._mesh = mesh;
  18218. if (rank > this._maxRank) {
  18219. this._maxRank = rank;
  18220. }
  18221. };
  18222. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18223. get: function () {
  18224. return this._currentRank <= this._maxRank;
  18225. },
  18226. enumerable: true,
  18227. configurable: true
  18228. });
  18229. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18230. var currentFallbacks = this._defines[this._currentRank];
  18231. for (var index = 0; index < currentFallbacks.length; index++) {
  18232. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18233. }
  18234. if (this._mesh && this._currentRank === this._meshRank) {
  18235. this._mesh.computeBonesUsingShaders = false;
  18236. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18237. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18238. }
  18239. this._currentRank++;
  18240. return currentDefines;
  18241. };
  18242. return EffectFallbacks;
  18243. })();
  18244. BABYLON.EffectFallbacks = EffectFallbacks;
  18245. var Effect = (function () {
  18246. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18247. var _this = this;
  18248. this._isReady = false;
  18249. this._compilationError = "";
  18250. this._valueCache = [];
  18251. this._engine = engine;
  18252. this.name = baseName;
  18253. this.defines = defines;
  18254. this._uniformsNames = uniformsNames.concat(samplers);
  18255. this._samplers = samplers;
  18256. this._attributesNames = attributesNames;
  18257. this.onError = onError;
  18258. this.onCompiled = onCompiled;
  18259. var vertexSource;
  18260. var fragmentSource;
  18261. if (baseName.vertexElement) {
  18262. vertexSource = document.getElementById(baseName.vertexElement);
  18263. if (!vertexSource) {
  18264. vertexSource = baseName.vertexElement;
  18265. }
  18266. }
  18267. else {
  18268. vertexSource = baseName.vertex || baseName;
  18269. }
  18270. if (baseName.fragmentElement) {
  18271. fragmentSource = document.getElementById(baseName.fragmentElement);
  18272. if (!fragmentSource) {
  18273. fragmentSource = baseName.fragmentElement;
  18274. }
  18275. }
  18276. else {
  18277. fragmentSource = baseName.fragment || baseName;
  18278. }
  18279. this._loadVertexShader(vertexSource, function (vertexCode) {
  18280. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18281. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18282. });
  18283. });
  18284. }
  18285. // Properties
  18286. Effect.prototype.isReady = function () {
  18287. return this._isReady;
  18288. };
  18289. Effect.prototype.getProgram = function () {
  18290. return this._program;
  18291. };
  18292. Effect.prototype.getAttributesNames = function () {
  18293. return this._attributesNames;
  18294. };
  18295. Effect.prototype.getAttributeLocation = function (index) {
  18296. return this._attributes[index];
  18297. };
  18298. Effect.prototype.getAttributeLocationByName = function (name) {
  18299. var index = this._attributesNames.indexOf(name);
  18300. return this._attributes[index];
  18301. };
  18302. Effect.prototype.getAttributesCount = function () {
  18303. return this._attributes.length;
  18304. };
  18305. Effect.prototype.getUniformIndex = function (uniformName) {
  18306. return this._uniformsNames.indexOf(uniformName);
  18307. };
  18308. Effect.prototype.getUniform = function (uniformName) {
  18309. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18310. };
  18311. Effect.prototype.getSamplers = function () {
  18312. return this._samplers;
  18313. };
  18314. Effect.prototype.getCompilationError = function () {
  18315. return this._compilationError;
  18316. };
  18317. // Methods
  18318. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18319. // DOM element ?
  18320. if (vertex instanceof HTMLElement) {
  18321. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18322. callback(vertexCode);
  18323. return;
  18324. }
  18325. // Is in local store ?
  18326. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18327. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18328. return;
  18329. }
  18330. var vertexShaderUrl;
  18331. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18332. vertexShaderUrl = vertex;
  18333. }
  18334. else {
  18335. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18336. }
  18337. // Vertex shader
  18338. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18339. };
  18340. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18341. // DOM element ?
  18342. if (fragment instanceof HTMLElement) {
  18343. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18344. callback(fragmentCode);
  18345. return;
  18346. }
  18347. // Is in local store ?
  18348. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18349. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18350. return;
  18351. }
  18352. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18353. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18354. return;
  18355. }
  18356. var fragmentShaderUrl;
  18357. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18358. fragmentShaderUrl = fragment;
  18359. }
  18360. else {
  18361. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18362. }
  18363. // Fragment shader
  18364. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18365. };
  18366. Effect.prototype._dumpShadersName = function () {
  18367. if (this.name.vertexElement) {
  18368. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18369. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18370. }
  18371. else if (this.name.vertex) {
  18372. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18373. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18374. }
  18375. else {
  18376. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18377. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18378. }
  18379. };
  18380. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18381. try {
  18382. var engine = this._engine;
  18383. if (!engine.getCaps().highPrecisionShaderSupported) {
  18384. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18385. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18386. }
  18387. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18388. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18389. this._attributes = engine.getAttributes(this._program, attributesNames);
  18390. for (var index = 0; index < this._samplers.length; index++) {
  18391. var sampler = this.getUniform(this._samplers[index]);
  18392. if (sampler == null) {
  18393. this._samplers.splice(index, 1);
  18394. index--;
  18395. }
  18396. }
  18397. engine.bindSamplers(this);
  18398. this._isReady = true;
  18399. if (this.onCompiled) {
  18400. this.onCompiled(this);
  18401. }
  18402. }
  18403. catch (e) {
  18404. // Is it a problem with precision?
  18405. if (e.message.indexOf("highp") !== -1) {
  18406. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18407. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18408. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18409. return;
  18410. }
  18411. // Let's go through fallbacks then
  18412. if (fallbacks && fallbacks.isMoreFallbacks) {
  18413. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18414. this._dumpShadersName();
  18415. defines = fallbacks.reduce(defines);
  18416. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18417. }
  18418. else {
  18419. BABYLON.Tools.Error("Unable to compile effect: ");
  18420. this._dumpShadersName();
  18421. BABYLON.Tools.Error("Defines: " + defines);
  18422. BABYLON.Tools.Error("Error: " + e.message);
  18423. this._compilationError = e.message;
  18424. if (this.onError) {
  18425. this.onError(this, this._compilationError);
  18426. }
  18427. }
  18428. }
  18429. };
  18430. Object.defineProperty(Effect.prototype, "isSupported", {
  18431. get: function () {
  18432. return this._compilationError === "";
  18433. },
  18434. enumerable: true,
  18435. configurable: true
  18436. });
  18437. Effect.prototype._bindTexture = function (channel, texture) {
  18438. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18439. };
  18440. Effect.prototype.setTexture = function (channel, texture) {
  18441. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18442. };
  18443. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18444. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18445. };
  18446. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18447. if (!this._valueCache[uniformName]) {
  18448. this._valueCache[uniformName] = new BABYLON.Matrix();
  18449. }
  18450. for (var index = 0; index < 16; index++) {
  18451. this._valueCache[uniformName].m[index] = matrix.m[index];
  18452. }
  18453. };
  18454. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18455. if (!this._valueCache[uniformName]) {
  18456. this._valueCache[uniformName] = [x, y];
  18457. return;
  18458. }
  18459. this._valueCache[uniformName][0] = x;
  18460. this._valueCache[uniformName][1] = y;
  18461. };
  18462. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18463. if (!this._valueCache[uniformName]) {
  18464. this._valueCache[uniformName] = [x, y, z];
  18465. return;
  18466. }
  18467. this._valueCache[uniformName][0] = x;
  18468. this._valueCache[uniformName][1] = y;
  18469. this._valueCache[uniformName][2] = z;
  18470. };
  18471. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18472. if (!this._valueCache[uniformName]) {
  18473. this._valueCache[uniformName] = [x, y, z, w];
  18474. return;
  18475. }
  18476. this._valueCache[uniformName][0] = x;
  18477. this._valueCache[uniformName][1] = y;
  18478. this._valueCache[uniformName][2] = z;
  18479. this._valueCache[uniformName][3] = w;
  18480. };
  18481. Effect.prototype.setArray = function (uniformName, array) {
  18482. this._engine.setArray(this.getUniform(uniformName), array);
  18483. return this;
  18484. };
  18485. Effect.prototype.setArray2 = function (uniformName, array) {
  18486. this._engine.setArray2(this.getUniform(uniformName), array);
  18487. return this;
  18488. };
  18489. Effect.prototype.setArray3 = function (uniformName, array) {
  18490. this._engine.setArray3(this.getUniform(uniformName), array);
  18491. return this;
  18492. };
  18493. Effect.prototype.setArray4 = function (uniformName, array) {
  18494. this._engine.setArray4(this.getUniform(uniformName), array);
  18495. return this;
  18496. };
  18497. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18498. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18499. return this;
  18500. };
  18501. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18502. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18503. // return this;
  18504. // this._cacheMatrix(uniformName, matrix);
  18505. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18506. return this;
  18507. };
  18508. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18509. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18510. return this;
  18511. };
  18512. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18513. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18514. return this;
  18515. };
  18516. Effect.prototype.setFloat = function (uniformName, value) {
  18517. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18518. return this;
  18519. this._valueCache[uniformName] = value;
  18520. this._engine.setFloat(this.getUniform(uniformName), value);
  18521. return this;
  18522. };
  18523. Effect.prototype.setBool = function (uniformName, bool) {
  18524. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18525. return this;
  18526. this._valueCache[uniformName] = bool;
  18527. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18528. return this;
  18529. };
  18530. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18531. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18532. return this;
  18533. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18534. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18535. return this;
  18536. };
  18537. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18538. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18539. return this;
  18540. this._cacheFloat2(uniformName, x, y);
  18541. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18542. return this;
  18543. };
  18544. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18545. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18546. return this;
  18547. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18548. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18549. return this;
  18550. };
  18551. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18552. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18553. return this;
  18554. this._cacheFloat3(uniformName, x, y, z);
  18555. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18556. return this;
  18557. };
  18558. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18559. 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)
  18560. return this;
  18561. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18562. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18563. return this;
  18564. };
  18565. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18566. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18567. return this;
  18568. this._cacheFloat4(uniformName, x, y, z, w);
  18569. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18570. return this;
  18571. };
  18572. Effect.prototype.setColor3 = function (uniformName, color3) {
  18573. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18574. return this;
  18575. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18576. this._engine.setColor3(this.getUniform(uniformName), color3);
  18577. return this;
  18578. };
  18579. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18580. 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)
  18581. return this;
  18582. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18583. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18584. return this;
  18585. };
  18586. // Statics
  18587. Effect.ShadersStore = {};
  18588. return Effect;
  18589. })();
  18590. BABYLON.Effect = Effect;
  18591. })(BABYLON || (BABYLON = {}));
  18592. var BABYLON;
  18593. (function (BABYLON) {
  18594. var MaterialDefines = (function () {
  18595. function MaterialDefines() {
  18596. }
  18597. MaterialDefines.prototype.isEqual = function (other) {
  18598. for (var index = 0; index < this._keys.length; index++) {
  18599. var prop = this._keys[index];
  18600. if (this[prop] !== other[prop]) {
  18601. return false;
  18602. }
  18603. }
  18604. return true;
  18605. };
  18606. MaterialDefines.prototype.cloneTo = function (other) {
  18607. for (var index = 0; index < this._keys.length; index++) {
  18608. var prop = this._keys[index];
  18609. other[prop] = this[prop];
  18610. }
  18611. };
  18612. MaterialDefines.prototype.reset = function () {
  18613. for (var index = 0; index < this._keys.length; index++) {
  18614. var prop = this._keys[index];
  18615. if (typeof (this[prop]) === "number") {
  18616. this[prop] = 0;
  18617. }
  18618. else {
  18619. this[prop] = false;
  18620. }
  18621. }
  18622. };
  18623. MaterialDefines.prototype.toString = function () {
  18624. var result = "";
  18625. for (var index = 0; index < this._keys.length; index++) {
  18626. var prop = this._keys[index];
  18627. if (typeof (this[prop]) === "number") {
  18628. result += "#define " + prop + " " + this[prop] + "\n";
  18629. }
  18630. else if (this[prop]) {
  18631. result += "#define " + prop + "\n";
  18632. }
  18633. }
  18634. return result;
  18635. };
  18636. return MaterialDefines;
  18637. })();
  18638. BABYLON.MaterialDefines = MaterialDefines;
  18639. var Material = (function () {
  18640. function Material(name, scene, doNotAdd) {
  18641. this.name = name;
  18642. this.checkReadyOnEveryCall = false;
  18643. this.checkReadyOnlyOnce = false;
  18644. this.state = "";
  18645. this.alpha = 1.0;
  18646. this.backFaceCulling = true;
  18647. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18648. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18649. this.disableDepthWrite = false;
  18650. this.fogEnabled = true;
  18651. this._wasPreviouslyReady = false;
  18652. this._fillMode = Material.TriangleFillMode;
  18653. this.pointSize = 1.0;
  18654. this.zOffset = 0;
  18655. this.id = name;
  18656. this._scene = scene;
  18657. if (!doNotAdd) {
  18658. scene.materials.push(this);
  18659. }
  18660. }
  18661. Object.defineProperty(Material, "TriangleFillMode", {
  18662. get: function () {
  18663. return Material._TriangleFillMode;
  18664. },
  18665. enumerable: true,
  18666. configurable: true
  18667. });
  18668. Object.defineProperty(Material, "WireFrameFillMode", {
  18669. get: function () {
  18670. return Material._WireFrameFillMode;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Object.defineProperty(Material, "PointFillMode", {
  18676. get: function () {
  18677. return Material._PointFillMode;
  18678. },
  18679. enumerable: true,
  18680. configurable: true
  18681. });
  18682. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18683. get: function () {
  18684. return Material._ClockWiseSideOrientation;
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18690. get: function () {
  18691. return Material._CounterClockWiseSideOrientation;
  18692. },
  18693. enumerable: true,
  18694. configurable: true
  18695. });
  18696. Object.defineProperty(Material.prototype, "wireframe", {
  18697. get: function () {
  18698. return this._fillMode === Material.WireFrameFillMode;
  18699. },
  18700. set: function (value) {
  18701. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18702. },
  18703. enumerable: true,
  18704. configurable: true
  18705. });
  18706. Object.defineProperty(Material.prototype, "pointsCloud", {
  18707. get: function () {
  18708. return this._fillMode === Material.PointFillMode;
  18709. },
  18710. set: function (value) {
  18711. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(Material.prototype, "fillMode", {
  18717. get: function () {
  18718. return this._fillMode;
  18719. },
  18720. set: function (value) {
  18721. this._fillMode = value;
  18722. },
  18723. enumerable: true,
  18724. configurable: true
  18725. });
  18726. Object.defineProperty(Material.prototype, "isFrozen", {
  18727. get: function () {
  18728. return this.checkReadyOnlyOnce;
  18729. },
  18730. enumerable: true,
  18731. configurable: true
  18732. });
  18733. Material.prototype.freeze = function () {
  18734. this.checkReadyOnlyOnce = true;
  18735. };
  18736. Material.prototype.unfreeze = function () {
  18737. this.checkReadyOnlyOnce = false;
  18738. };
  18739. Material.prototype.isReady = function (mesh, useInstances) {
  18740. return true;
  18741. };
  18742. Material.prototype.getEffect = function () {
  18743. return this._effect;
  18744. };
  18745. Material.prototype.getScene = function () {
  18746. return this._scene;
  18747. };
  18748. Material.prototype.needAlphaBlending = function () {
  18749. return (this.alpha < 1.0);
  18750. };
  18751. Material.prototype.needAlphaTesting = function () {
  18752. return false;
  18753. };
  18754. Material.prototype.getAlphaTestTexture = function () {
  18755. return null;
  18756. };
  18757. Material.prototype.trackCreation = function (onCompiled, onError) {
  18758. };
  18759. Material.prototype.markDirty = function () {
  18760. this._wasPreviouslyReady = false;
  18761. };
  18762. Material.prototype._preBind = function () {
  18763. var engine = this._scene.getEngine();
  18764. engine.enableEffect(this._effect);
  18765. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18766. };
  18767. Material.prototype.bind = function (world, mesh) {
  18768. this._scene._cachedMaterial = this;
  18769. if (this.onBind) {
  18770. this.onBind(this, mesh);
  18771. }
  18772. if (this.disableDepthWrite) {
  18773. var engine = this._scene.getEngine();
  18774. this._cachedDepthWriteState = engine.getDepthWrite();
  18775. engine.setDepthWrite(false);
  18776. }
  18777. };
  18778. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18779. };
  18780. Material.prototype.unbind = function () {
  18781. if (this.disableDepthWrite) {
  18782. var engine = this._scene.getEngine();
  18783. engine.setDepthWrite(this._cachedDepthWriteState);
  18784. }
  18785. };
  18786. Material.prototype.clone = function (name) {
  18787. return null;
  18788. };
  18789. Material.prototype.getBindedMeshes = function () {
  18790. var result = new Array();
  18791. for (var index = 0; index < this._scene.meshes.length; index++) {
  18792. var mesh = this._scene.meshes[index];
  18793. if (mesh.material === this) {
  18794. result.push(mesh);
  18795. }
  18796. }
  18797. return result;
  18798. };
  18799. Material.prototype.dispose = function (forceDisposeEffect) {
  18800. // Animations
  18801. this.getScene().stopAnimation(this);
  18802. // Remove from scene
  18803. var index = this._scene.materials.indexOf(this);
  18804. if (index >= 0) {
  18805. this._scene.materials.splice(index, 1);
  18806. }
  18807. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18808. if (forceDisposeEffect && this._effect) {
  18809. this._scene.getEngine()._releaseEffect(this._effect);
  18810. this._effect = null;
  18811. }
  18812. // Remove from meshes
  18813. for (index = 0; index < this._scene.meshes.length; index++) {
  18814. var mesh = this._scene.meshes[index];
  18815. if (mesh.material === this) {
  18816. mesh.material = null;
  18817. }
  18818. }
  18819. // Callback
  18820. if (this.onDispose) {
  18821. this.onDispose();
  18822. }
  18823. };
  18824. Material.prototype.copyTo = function (other) {
  18825. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18826. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18827. other.alpha = this.alpha;
  18828. other.fillMode = this.fillMode;
  18829. other.backFaceCulling = this.backFaceCulling;
  18830. other.fogEnabled = this.fogEnabled;
  18831. other.wireframe = this.wireframe;
  18832. other.zOffset = this.zOffset;
  18833. other.alphaMode = this.alphaMode;
  18834. other.sideOrientation = this.sideOrientation;
  18835. other.disableDepthWrite = this.disableDepthWrite;
  18836. other.pointSize = this.pointSize;
  18837. other.pointsCloud = this.pointsCloud;
  18838. };
  18839. Material.prototype.serialize = function () {
  18840. var serializationObject = {};
  18841. serializationObject.name = this.name;
  18842. serializationObject.alpha = this.alpha;
  18843. serializationObject.id = this.id;
  18844. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18845. serializationObject.backFaceCulling = this.backFaceCulling;
  18846. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18847. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18848. return serializationObject;
  18849. };
  18850. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18851. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18852. multiMaterial.id = parsedMultiMaterial.id;
  18853. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18854. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18855. var subMatId = parsedMultiMaterial.materials[matIndex];
  18856. if (subMatId) {
  18857. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18858. }
  18859. else {
  18860. multiMaterial.subMaterials.push(null);
  18861. }
  18862. }
  18863. return multiMaterial;
  18864. };
  18865. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18866. if (!parsedMaterial.customType) {
  18867. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18868. }
  18869. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18870. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18871. ;
  18872. };
  18873. Material._TriangleFillMode = 0;
  18874. Material._WireFrameFillMode = 1;
  18875. Material._PointFillMode = 2;
  18876. Material._ClockWiseSideOrientation = 0;
  18877. Material._CounterClockWiseSideOrientation = 1;
  18878. return Material;
  18879. })();
  18880. BABYLON.Material = Material;
  18881. })(BABYLON || (BABYLON = {}));
  18882. var BABYLON;
  18883. (function (BABYLON) {
  18884. var maxSimultaneousLights = 4;
  18885. var FresnelParameters = (function () {
  18886. function FresnelParameters() {
  18887. this.isEnabled = true;
  18888. this.leftColor = BABYLON.Color3.White();
  18889. this.rightColor = BABYLON.Color3.Black();
  18890. this.bias = 0;
  18891. this.power = 1;
  18892. }
  18893. FresnelParameters.prototype.clone = function () {
  18894. var newFresnelParameters = new FresnelParameters();
  18895. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18896. return new FresnelParameters;
  18897. };
  18898. FresnelParameters.prototype.serialize = function () {
  18899. var serializationObject = {};
  18900. serializationObject.isEnabled = this.isEnabled;
  18901. serializationObject.leftColor = this.leftColor;
  18902. serializationObject.rightColor = this.rightColor;
  18903. serializationObject.bias = this.bias;
  18904. serializationObject.power = this.power;
  18905. return serializationObject;
  18906. };
  18907. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18908. var fresnelParameters = new FresnelParameters();
  18909. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18910. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18911. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18912. fresnelParameters.bias = parsedFresnelParameters.bias;
  18913. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18914. return fresnelParameters;
  18915. };
  18916. return FresnelParameters;
  18917. })();
  18918. BABYLON.FresnelParameters = FresnelParameters;
  18919. var StandardMaterialDefines = (function (_super) {
  18920. __extends(StandardMaterialDefines, _super);
  18921. function StandardMaterialDefines() {
  18922. _super.call(this);
  18923. this.DIFFUSE = false;
  18924. this.AMBIENT = false;
  18925. this.OPACITY = false;
  18926. this.OPACITYRGB = false;
  18927. this.REFLECTION = false;
  18928. this.EMISSIVE = false;
  18929. this.SPECULAR = false;
  18930. this.BUMP = false;
  18931. this.SPECULAROVERALPHA = false;
  18932. this.CLIPPLANE = false;
  18933. this.ALPHATEST = false;
  18934. this.ALPHAFROMDIFFUSE = false;
  18935. this.POINTSIZE = false;
  18936. this.FOG = false;
  18937. this.LIGHT0 = false;
  18938. this.LIGHT1 = false;
  18939. this.LIGHT2 = false;
  18940. this.LIGHT3 = false;
  18941. this.SPOTLIGHT0 = false;
  18942. this.SPOTLIGHT1 = false;
  18943. this.SPOTLIGHT2 = false;
  18944. this.SPOTLIGHT3 = false;
  18945. this.HEMILIGHT0 = false;
  18946. this.HEMILIGHT1 = false;
  18947. this.HEMILIGHT2 = false;
  18948. this.HEMILIGHT3 = false;
  18949. this.POINTLIGHT0 = false;
  18950. this.POINTLIGHT1 = false;
  18951. this.POINTLIGHT2 = false;
  18952. this.POINTLIGHT3 = false;
  18953. this.DIRLIGHT0 = false;
  18954. this.DIRLIGHT1 = false;
  18955. this.DIRLIGHT2 = false;
  18956. this.DIRLIGHT3 = false;
  18957. this.SPECULARTERM = false;
  18958. this.SHADOW0 = false;
  18959. this.SHADOW1 = false;
  18960. this.SHADOW2 = false;
  18961. this.SHADOW3 = false;
  18962. this.SHADOWS = false;
  18963. this.SHADOWVSM0 = false;
  18964. this.SHADOWVSM1 = false;
  18965. this.SHADOWVSM2 = false;
  18966. this.SHADOWVSM3 = false;
  18967. this.SHADOWPCF0 = false;
  18968. this.SHADOWPCF1 = false;
  18969. this.SHADOWPCF2 = false;
  18970. this.SHADOWPCF3 = false;
  18971. this.DIFFUSEFRESNEL = false;
  18972. this.OPACITYFRESNEL = false;
  18973. this.REFLECTIONFRESNEL = false;
  18974. this.EMISSIVEFRESNEL = false;
  18975. this.FRESNEL = false;
  18976. this.NORMAL = false;
  18977. this.UV1 = false;
  18978. this.UV2 = false;
  18979. this.VERTEXCOLOR = false;
  18980. this.VERTEXALPHA = false;
  18981. this.NUM_BONE_INFLUENCERS = 0;
  18982. this.BonesPerMesh = 0;
  18983. this.INSTANCES = false;
  18984. this.GLOSSINESS = false;
  18985. this.ROUGHNESS = false;
  18986. this.EMISSIVEASILLUMINATION = false;
  18987. this.LINKEMISSIVEWITHDIFFUSE = false;
  18988. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18989. this.LIGHTMAP = false;
  18990. this.USELIGHTMAPASSHADOWMAP = false;
  18991. this.REFLECTIONMAP_3D = false;
  18992. this.REFLECTIONMAP_SPHERICAL = false;
  18993. this.REFLECTIONMAP_PLANAR = false;
  18994. this.REFLECTIONMAP_CUBIC = false;
  18995. this.REFLECTIONMAP_PROJECTION = false;
  18996. this.REFLECTIONMAP_SKYBOX = false;
  18997. this.REFLECTIONMAP_EXPLICIT = false;
  18998. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18999. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19000. this.INVERTCUBICMAP = false;
  19001. this.LOGARITHMICDEPTH = false;
  19002. this._keys = Object.keys(this);
  19003. }
  19004. return StandardMaterialDefines;
  19005. })(BABYLON.MaterialDefines);
  19006. var StandardMaterial = (function (_super) {
  19007. __extends(StandardMaterial, _super);
  19008. function StandardMaterial(name, scene) {
  19009. var _this = this;
  19010. _super.call(this, name, scene);
  19011. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19012. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19013. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19014. this.specularPower = 64;
  19015. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19016. this.useAlphaFromDiffuseTexture = false;
  19017. this.useEmissiveAsIllumination = false;
  19018. this.linkEmissiveWithDiffuse = false;
  19019. this.useReflectionFresnelFromSpecular = false;
  19020. this.useSpecularOverAlpha = false;
  19021. this.disableLighting = false;
  19022. this.roughness = 0;
  19023. this.useLightmapAsShadowmap = false;
  19024. this.useGlossinessFromSpecularMapAlpha = false;
  19025. this._renderTargets = new BABYLON.SmartArray(16);
  19026. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19027. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19028. this._defines = new StandardMaterialDefines();
  19029. this._cachedDefines = new StandardMaterialDefines();
  19030. this._cachedDefines.BonesPerMesh = -1;
  19031. this.getRenderTargetTextures = function () {
  19032. _this._renderTargets.reset();
  19033. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19034. _this._renderTargets.push(_this.reflectionTexture);
  19035. }
  19036. return _this._renderTargets;
  19037. };
  19038. }
  19039. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19040. get: function () {
  19041. return this._useLogarithmicDepth;
  19042. },
  19043. set: function (value) {
  19044. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19045. },
  19046. enumerable: true,
  19047. configurable: true
  19048. });
  19049. StandardMaterial.prototype.needAlphaBlending = function () {
  19050. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19051. };
  19052. StandardMaterial.prototype.needAlphaTesting = function () {
  19053. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19054. };
  19055. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19056. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19057. };
  19058. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19059. return this.diffuseTexture;
  19060. };
  19061. // Methods
  19062. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19063. if (!mesh) {
  19064. return true;
  19065. }
  19066. if (this._defines.INSTANCES !== useInstances) {
  19067. return false;
  19068. }
  19069. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19070. return true;
  19071. }
  19072. return false;
  19073. };
  19074. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19075. var lightIndex = 0;
  19076. var needNormals = false;
  19077. for (var index = 0; index < scene.lights.length; index++) {
  19078. var light = scene.lights[index];
  19079. if (!light.isEnabled()) {
  19080. continue;
  19081. }
  19082. // Excluded check
  19083. if (light._excludedMeshesIds.length > 0) {
  19084. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19085. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19086. if (excludedMesh) {
  19087. light.excludedMeshes.push(excludedMesh);
  19088. }
  19089. }
  19090. light._excludedMeshesIds = [];
  19091. }
  19092. // Included check
  19093. if (light._includedOnlyMeshesIds.length > 0) {
  19094. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19095. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19096. if (includedOnlyMesh) {
  19097. light.includedOnlyMeshes.push(includedOnlyMesh);
  19098. }
  19099. }
  19100. light._includedOnlyMeshesIds = [];
  19101. }
  19102. if (!light.canAffectMesh(mesh)) {
  19103. continue;
  19104. }
  19105. needNormals = true;
  19106. defines["LIGHT" + lightIndex] = true;
  19107. var type;
  19108. if (light instanceof BABYLON.SpotLight) {
  19109. type = "SPOTLIGHT" + lightIndex;
  19110. }
  19111. else if (light instanceof BABYLON.HemisphericLight) {
  19112. type = "HEMILIGHT" + lightIndex;
  19113. }
  19114. else if (light instanceof BABYLON.PointLight) {
  19115. type = "POINTLIGHT" + lightIndex;
  19116. }
  19117. else {
  19118. type = "DIRLIGHT" + lightIndex;
  19119. }
  19120. defines[type] = true;
  19121. // Specular
  19122. if (!light.specular.equalsFloats(0, 0, 0)) {
  19123. defines["SPECULARTERM"] = true;
  19124. }
  19125. // Shadows
  19126. if (scene.shadowsEnabled) {
  19127. var shadowGenerator = light.getShadowGenerator();
  19128. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19129. defines["SHADOW" + lightIndex] = true;
  19130. defines["SHADOWS"] = true;
  19131. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19132. defines["SHADOWVSM" + lightIndex] = true;
  19133. }
  19134. if (shadowGenerator.usePoissonSampling) {
  19135. defines["SHADOWPCF" + lightIndex] = true;
  19136. }
  19137. }
  19138. }
  19139. lightIndex++;
  19140. if (lightIndex === maxSimultaneousLights)
  19141. break;
  19142. }
  19143. return needNormals;
  19144. };
  19145. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19146. var lightIndex = 0;
  19147. var depthValuesAlreadySet = false;
  19148. for (var index = 0; index < scene.lights.length; index++) {
  19149. var light = scene.lights[index];
  19150. if (!light.isEnabled()) {
  19151. continue;
  19152. }
  19153. if (!light.canAffectMesh(mesh)) {
  19154. continue;
  19155. }
  19156. if (light instanceof BABYLON.PointLight) {
  19157. // Point Light
  19158. light.transferToEffect(effect, "vLightData" + lightIndex);
  19159. }
  19160. else if (light instanceof BABYLON.DirectionalLight) {
  19161. // Directional Light
  19162. light.transferToEffect(effect, "vLightData" + lightIndex);
  19163. }
  19164. else if (light instanceof BABYLON.SpotLight) {
  19165. // Spot Light
  19166. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19167. }
  19168. else if (light instanceof BABYLON.HemisphericLight) {
  19169. // Hemispheric Light
  19170. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19171. }
  19172. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19173. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19174. if (defines["SPECULARTERM"]) {
  19175. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19176. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19177. }
  19178. // Shadows
  19179. if (scene.shadowsEnabled) {
  19180. var shadowGenerator = light.getShadowGenerator();
  19181. if (mesh.receiveShadows && shadowGenerator) {
  19182. if (!light.needCube()) {
  19183. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19184. }
  19185. else {
  19186. if (!depthValuesAlreadySet) {
  19187. depthValuesAlreadySet = true;
  19188. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19189. }
  19190. }
  19191. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19192. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19193. }
  19194. }
  19195. lightIndex++;
  19196. if (lightIndex === maxSimultaneousLights)
  19197. break;
  19198. }
  19199. };
  19200. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19201. if (this.isFrozen) {
  19202. if (this._wasPreviouslyReady) {
  19203. return true;
  19204. }
  19205. }
  19206. var scene = this.getScene();
  19207. if (!this.checkReadyOnEveryCall) {
  19208. if (this._renderId === scene.getRenderId()) {
  19209. if (this._checkCache(scene, mesh, useInstances)) {
  19210. return true;
  19211. }
  19212. }
  19213. }
  19214. var engine = scene.getEngine();
  19215. var needNormals = false;
  19216. var needUVs = false;
  19217. this._defines.reset();
  19218. // Textures
  19219. if (scene.texturesEnabled) {
  19220. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19221. if (!this.diffuseTexture.isReady()) {
  19222. return false;
  19223. }
  19224. else {
  19225. needUVs = true;
  19226. this._defines.DIFFUSE = true;
  19227. }
  19228. }
  19229. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19230. if (!this.ambientTexture.isReady()) {
  19231. return false;
  19232. }
  19233. else {
  19234. needUVs = true;
  19235. this._defines.AMBIENT = true;
  19236. }
  19237. }
  19238. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19239. if (!this.opacityTexture.isReady()) {
  19240. return false;
  19241. }
  19242. else {
  19243. needUVs = true;
  19244. this._defines.OPACITY = true;
  19245. if (this.opacityTexture.getAlphaFromRGB) {
  19246. this._defines.OPACITYRGB = true;
  19247. }
  19248. }
  19249. }
  19250. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19251. if (!this.reflectionTexture.isReady()) {
  19252. return false;
  19253. }
  19254. else {
  19255. needNormals = true;
  19256. this._defines.REFLECTION = true;
  19257. if (this.roughness > 0) {
  19258. this._defines.ROUGHNESS = true;
  19259. }
  19260. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19261. this._defines.INVERTCUBICMAP = true;
  19262. }
  19263. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19264. switch (this.reflectionTexture.coordinatesMode) {
  19265. case BABYLON.Texture.CUBIC_MODE:
  19266. case BABYLON.Texture.INVCUBIC_MODE:
  19267. this._defines.REFLECTIONMAP_CUBIC = true;
  19268. break;
  19269. case BABYLON.Texture.EXPLICIT_MODE:
  19270. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19271. break;
  19272. case BABYLON.Texture.PLANAR_MODE:
  19273. this._defines.REFLECTIONMAP_PLANAR = true;
  19274. break;
  19275. case BABYLON.Texture.PROJECTION_MODE:
  19276. this._defines.REFLECTIONMAP_PROJECTION = true;
  19277. break;
  19278. case BABYLON.Texture.SKYBOX_MODE:
  19279. this._defines.REFLECTIONMAP_SKYBOX = true;
  19280. break;
  19281. case BABYLON.Texture.SPHERICAL_MODE:
  19282. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19283. break;
  19284. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19285. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19286. break;
  19287. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19288. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19289. break;
  19290. }
  19291. }
  19292. }
  19293. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19294. if (!this.emissiveTexture.isReady()) {
  19295. return false;
  19296. }
  19297. else {
  19298. needUVs = true;
  19299. this._defines.EMISSIVE = true;
  19300. }
  19301. }
  19302. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19303. if (!this.lightmapTexture.isReady()) {
  19304. return false;
  19305. }
  19306. else {
  19307. needUVs = true;
  19308. this._defines.LIGHTMAP = true;
  19309. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19310. }
  19311. }
  19312. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19313. if (!this.specularTexture.isReady()) {
  19314. return false;
  19315. }
  19316. else {
  19317. needUVs = true;
  19318. this._defines.SPECULAR = true;
  19319. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19320. }
  19321. }
  19322. }
  19323. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19324. if (!this.bumpTexture.isReady()) {
  19325. return false;
  19326. }
  19327. else {
  19328. needUVs = true;
  19329. this._defines.BUMP = true;
  19330. }
  19331. }
  19332. // Effect
  19333. if (scene.clipPlane) {
  19334. this._defines.CLIPPLANE = true;
  19335. }
  19336. if (engine.getAlphaTesting()) {
  19337. this._defines.ALPHATEST = true;
  19338. }
  19339. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19340. this._defines.ALPHAFROMDIFFUSE = true;
  19341. }
  19342. if (this.useEmissiveAsIllumination) {
  19343. this._defines.EMISSIVEASILLUMINATION = true;
  19344. }
  19345. if (this.linkEmissiveWithDiffuse) {
  19346. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19347. }
  19348. if (this.useReflectionFresnelFromSpecular) {
  19349. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19350. }
  19351. if (this.useLogarithmicDepth) {
  19352. this._defines.LOGARITHMICDEPTH = true;
  19353. }
  19354. // Point size
  19355. if (this.pointsCloud || scene.forcePointsCloud) {
  19356. this._defines.POINTSIZE = true;
  19357. }
  19358. // Fog
  19359. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19360. this._defines.FOG = true;
  19361. }
  19362. if (scene.lightsEnabled && !this.disableLighting) {
  19363. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19364. }
  19365. if (StandardMaterial.FresnelEnabled) {
  19366. // Fresnel
  19367. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19368. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19369. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19370. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19371. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19372. this._defines.DIFFUSEFRESNEL = true;
  19373. }
  19374. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19375. this._defines.OPACITYFRESNEL = true;
  19376. }
  19377. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19378. this._defines.REFLECTIONFRESNEL = true;
  19379. }
  19380. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19381. this._defines.EMISSIVEFRESNEL = true;
  19382. }
  19383. needNormals = true;
  19384. this._defines.FRESNEL = true;
  19385. }
  19386. }
  19387. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19388. this._defines.SPECULAROVERALPHA = true;
  19389. }
  19390. // Attribs
  19391. if (mesh) {
  19392. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19393. this._defines.NORMAL = true;
  19394. }
  19395. if (needUVs) {
  19396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19397. this._defines.UV1 = true;
  19398. }
  19399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19400. this._defines.UV2 = true;
  19401. }
  19402. }
  19403. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19404. this._defines.VERTEXCOLOR = true;
  19405. if (mesh.hasVertexAlpha) {
  19406. this._defines.VERTEXALPHA = true;
  19407. }
  19408. }
  19409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19410. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19411. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19412. }
  19413. // Instances
  19414. if (useInstances) {
  19415. this._defines.INSTANCES = true;
  19416. }
  19417. }
  19418. // Get correct effect
  19419. if (!this._defines.isEqual(this._cachedDefines)) {
  19420. this._defines.cloneTo(this._cachedDefines);
  19421. scene.resetCachedMaterial();
  19422. // Fallbacks
  19423. var fallbacks = new BABYLON.EffectFallbacks();
  19424. if (this._defines.REFLECTION) {
  19425. fallbacks.addFallback(0, "REFLECTION");
  19426. }
  19427. if (this._defines.SPECULAR) {
  19428. fallbacks.addFallback(0, "SPECULAR");
  19429. }
  19430. if (this._defines.BUMP) {
  19431. fallbacks.addFallback(0, "BUMP");
  19432. }
  19433. if (this._defines.SPECULAROVERALPHA) {
  19434. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19435. }
  19436. if (this._defines.FOG) {
  19437. fallbacks.addFallback(1, "FOG");
  19438. }
  19439. if (this._defines.POINTSIZE) {
  19440. fallbacks.addFallback(0, "POINTSIZE");
  19441. }
  19442. if (this._defines.LOGARITHMICDEPTH) {
  19443. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19444. }
  19445. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19446. if (!this._defines["LIGHT" + lightIndex]) {
  19447. continue;
  19448. }
  19449. if (lightIndex > 0) {
  19450. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19451. }
  19452. if (this._defines["SHADOW" + lightIndex]) {
  19453. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19454. }
  19455. if (this._defines["SHADOWPCF" + lightIndex]) {
  19456. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19457. }
  19458. if (this._defines["SHADOWVSM" + lightIndex]) {
  19459. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19460. }
  19461. }
  19462. if (this._defines.SPECULARTERM) {
  19463. fallbacks.addFallback(0, "SPECULARTERM");
  19464. }
  19465. if (this._defines.DIFFUSEFRESNEL) {
  19466. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19467. }
  19468. if (this._defines.OPACITYFRESNEL) {
  19469. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19470. }
  19471. if (this._defines.REFLECTIONFRESNEL) {
  19472. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19473. }
  19474. if (this._defines.EMISSIVEFRESNEL) {
  19475. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19476. }
  19477. if (this._defines.FRESNEL) {
  19478. fallbacks.addFallback(4, "FRESNEL");
  19479. }
  19480. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19481. fallbacks.addCPUSkinningFallback(0, mesh);
  19482. }
  19483. //Attributes
  19484. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19485. if (this._defines.NORMAL) {
  19486. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19487. }
  19488. if (this._defines.UV1) {
  19489. attribs.push(BABYLON.VertexBuffer.UVKind);
  19490. }
  19491. if (this._defines.UV2) {
  19492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19493. }
  19494. if (this._defines.VERTEXCOLOR) {
  19495. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19496. }
  19497. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19500. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19503. }
  19504. }
  19505. if (this._defines.INSTANCES) {
  19506. attribs.push("world0");
  19507. attribs.push("world1");
  19508. attribs.push("world2");
  19509. attribs.push("world3");
  19510. }
  19511. // Legacy browser patch
  19512. var shaderName = "default";
  19513. if (!scene.getEngine().getCaps().standardDerivatives) {
  19514. shaderName = "legacydefault";
  19515. }
  19516. var join = this._defines.toString();
  19517. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19518. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19519. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19520. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19521. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19522. "vFogInfos", "vFogColor", "pointSize",
  19523. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19524. "mBones",
  19525. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19526. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19527. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19528. "logarithmicDepthConstant"
  19529. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19530. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19531. ], join, fallbacks, this.onCompiled, this.onError);
  19532. }
  19533. if (!this._effect.isReady()) {
  19534. return false;
  19535. }
  19536. this._renderId = scene.getRenderId();
  19537. this._wasPreviouslyReady = true;
  19538. if (mesh) {
  19539. if (!mesh._materialDefines) {
  19540. mesh._materialDefines = new StandardMaterialDefines();
  19541. }
  19542. this._defines.cloneTo(mesh._materialDefines);
  19543. }
  19544. return true;
  19545. };
  19546. StandardMaterial.prototype.unbind = function () {
  19547. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19548. this._effect.setTexture("reflection2DSampler", null);
  19549. }
  19550. _super.prototype.unbind.call(this);
  19551. };
  19552. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19553. this._effect.setMatrix("world", world);
  19554. };
  19555. StandardMaterial.prototype.bind = function (world, mesh) {
  19556. var scene = this.getScene();
  19557. // Matrices
  19558. this.bindOnlyWorldMatrix(world);
  19559. // Bones
  19560. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19561. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19562. }
  19563. if (scene.getCachedMaterial() !== this) {
  19564. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19565. if (StandardMaterial.FresnelEnabled) {
  19566. // Fresnel
  19567. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19568. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19569. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19570. }
  19571. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19572. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19573. }
  19574. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19575. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19576. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19577. }
  19578. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19579. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19580. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19581. }
  19582. }
  19583. // Textures
  19584. if (scene.texturesEnabled) {
  19585. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19586. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19587. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19588. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19589. }
  19590. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19591. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19592. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19593. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19594. }
  19595. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19596. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19597. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19598. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19599. }
  19600. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19601. if (this.reflectionTexture.isCube) {
  19602. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19603. }
  19604. else {
  19605. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19606. }
  19607. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19608. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19609. }
  19610. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19611. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19612. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19613. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19614. }
  19615. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19616. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19617. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19618. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19619. }
  19620. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19621. this._effect.setTexture("specularSampler", this.specularTexture);
  19622. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19623. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19624. }
  19625. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19626. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19627. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19628. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19629. }
  19630. }
  19631. // Clip plane
  19632. if (scene.clipPlane) {
  19633. var clipPlane = scene.clipPlane;
  19634. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19635. }
  19636. // Point size
  19637. if (this.pointsCloud) {
  19638. this._effect.setFloat("pointSize", this.pointSize);
  19639. }
  19640. // Colors
  19641. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19642. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19643. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19644. if (this._defines.SPECULARTERM) {
  19645. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19646. }
  19647. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19648. }
  19649. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19650. // Diffuse
  19651. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19652. // Lights
  19653. if (scene.lightsEnabled && !this.disableLighting) {
  19654. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19655. }
  19656. // View
  19657. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19658. this._effect.setMatrix("view", scene.getViewMatrix());
  19659. }
  19660. // Fog
  19661. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19662. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19663. this._effect.setColor3("vFogColor", scene.fogColor);
  19664. }
  19665. // Log. depth
  19666. if (this._defines.LOGARITHMICDEPTH) {
  19667. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19668. }
  19669. }
  19670. _super.prototype.bind.call(this, world, mesh);
  19671. };
  19672. StandardMaterial.prototype.getAnimatables = function () {
  19673. var results = [];
  19674. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19675. results.push(this.diffuseTexture);
  19676. }
  19677. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19678. results.push(this.ambientTexture);
  19679. }
  19680. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19681. results.push(this.opacityTexture);
  19682. }
  19683. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19684. results.push(this.reflectionTexture);
  19685. }
  19686. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19687. results.push(this.emissiveTexture);
  19688. }
  19689. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19690. results.push(this.specularTexture);
  19691. }
  19692. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19693. results.push(this.bumpTexture);
  19694. }
  19695. return results;
  19696. };
  19697. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19698. if (this.diffuseTexture) {
  19699. this.diffuseTexture.dispose();
  19700. }
  19701. if (this.ambientTexture) {
  19702. this.ambientTexture.dispose();
  19703. }
  19704. if (this.opacityTexture) {
  19705. this.opacityTexture.dispose();
  19706. }
  19707. if (this.reflectionTexture) {
  19708. this.reflectionTexture.dispose();
  19709. }
  19710. if (this.emissiveTexture) {
  19711. this.emissiveTexture.dispose();
  19712. }
  19713. if (this.specularTexture) {
  19714. this.specularTexture.dispose();
  19715. }
  19716. if (this.bumpTexture) {
  19717. this.bumpTexture.dispose();
  19718. }
  19719. _super.prototype.dispose.call(this, forceDisposeEffect);
  19720. };
  19721. StandardMaterial.prototype.clone = function (name) {
  19722. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19723. // Base material
  19724. this.copyTo(newStandardMaterial);
  19725. // Standard material
  19726. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19727. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19728. }
  19729. if (this.ambientTexture && this.ambientTexture.clone) {
  19730. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19731. }
  19732. if (this.opacityTexture && this.opacityTexture.clone) {
  19733. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19734. }
  19735. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19736. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19737. }
  19738. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19739. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19740. }
  19741. if (this.specularTexture && this.specularTexture.clone) {
  19742. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19743. }
  19744. if (this.bumpTexture && this.bumpTexture.clone) {
  19745. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19746. }
  19747. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19748. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19749. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19750. }
  19751. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19752. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19753. newStandardMaterial.specularColor = this.specularColor.clone();
  19754. newStandardMaterial.specularPower = this.specularPower;
  19755. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19756. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19757. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19758. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19759. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19760. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19761. newStandardMaterial.roughness = this.roughness;
  19762. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19763. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19764. }
  19765. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19766. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19767. }
  19768. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19769. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19770. }
  19771. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19772. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19773. }
  19774. return newStandardMaterial;
  19775. };
  19776. StandardMaterial.prototype.serialize = function () {
  19777. var serializationObject = _super.prototype.serialize.call(this);
  19778. serializationObject.ambient = this.ambientColor.asArray();
  19779. serializationObject.diffuse = this.diffuseColor.asArray();
  19780. serializationObject.specular = this.specularColor.asArray();
  19781. serializationObject.specularPower = this.specularPower;
  19782. serializationObject.emissive = this.emissiveColor.asArray();
  19783. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19784. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19785. if (this.diffuseTexture) {
  19786. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19787. }
  19788. if (this.diffuseFresnelParameters) {
  19789. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19790. }
  19791. if (this.ambientTexture) {
  19792. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19793. }
  19794. if (this.opacityTexture) {
  19795. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19796. }
  19797. if (this.opacityFresnelParameters) {
  19798. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19799. }
  19800. if (this.reflectionTexture) {
  19801. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19802. }
  19803. if (this.reflectionFresnelParameters) {
  19804. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19805. }
  19806. if (this.emissiveTexture) {
  19807. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19808. }
  19809. if (this.lightmapTexture) {
  19810. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19811. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19812. }
  19813. if (this.emissiveFresnelParameters) {
  19814. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19815. }
  19816. if (this.specularTexture) {
  19817. serializationObject.specularTexture = this.specularTexture.serialize();
  19818. }
  19819. if (this.bumpTexture) {
  19820. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19821. }
  19822. return serializationObject;
  19823. };
  19824. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19825. var material = new StandardMaterial(source.name, scene);
  19826. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19827. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19828. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19829. material.specularPower = source.specularPower;
  19830. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19831. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19832. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19833. material.alpha = source.alpha;
  19834. material.id = source.id;
  19835. if (source.disableDepthWrite) {
  19836. material.disableDepthWrite = source.disableDepthWrite;
  19837. }
  19838. BABYLON.Tags.AddTagsTo(material, source.tags);
  19839. material.backFaceCulling = source.backFaceCulling;
  19840. material.wireframe = source.wireframe;
  19841. if (source.diffuseTexture) {
  19842. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19843. }
  19844. if (source.diffuseFresnelParameters) {
  19845. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19846. }
  19847. if (source.ambientTexture) {
  19848. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19849. }
  19850. if (source.opacityTexture) {
  19851. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19852. }
  19853. if (source.opacityFresnelParameters) {
  19854. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19855. }
  19856. if (source.reflectionTexture) {
  19857. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19858. }
  19859. if (source.reflectionFresnelParameters) {
  19860. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19861. }
  19862. if (source.emissiveTexture) {
  19863. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19864. }
  19865. if (source.lightmapTexture) {
  19866. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19867. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19868. }
  19869. if (source.emissiveFresnelParameters) {
  19870. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19871. }
  19872. if (source.specularTexture) {
  19873. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19874. }
  19875. if (source.bumpTexture) {
  19876. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19877. }
  19878. if (source.checkReadyOnlyOnce) {
  19879. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19880. }
  19881. return material;
  19882. };
  19883. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19884. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19885. // Statics
  19886. // Flags used to enable or disable a type of texture for all Standard Materials
  19887. StandardMaterial.DiffuseTextureEnabled = true;
  19888. StandardMaterial.AmbientTextureEnabled = true;
  19889. StandardMaterial.OpacityTextureEnabled = true;
  19890. StandardMaterial.ReflectionTextureEnabled = true;
  19891. StandardMaterial.EmissiveTextureEnabled = true;
  19892. StandardMaterial.SpecularTextureEnabled = true;
  19893. StandardMaterial.BumpTextureEnabled = true;
  19894. StandardMaterial.FresnelEnabled = true;
  19895. StandardMaterial.LightmapEnabled = true;
  19896. return StandardMaterial;
  19897. })(BABYLON.Material);
  19898. BABYLON.StandardMaterial = StandardMaterial;
  19899. })(BABYLON || (BABYLON = {}));
  19900. var BABYLON;
  19901. (function (BABYLON) {
  19902. var MultiMaterial = (function (_super) {
  19903. __extends(MultiMaterial, _super);
  19904. function MultiMaterial(name, scene) {
  19905. _super.call(this, name, scene, true);
  19906. this.subMaterials = new Array();
  19907. scene.multiMaterials.push(this);
  19908. }
  19909. // Properties
  19910. MultiMaterial.prototype.getSubMaterial = function (index) {
  19911. if (index < 0 || index >= this.subMaterials.length) {
  19912. return this.getScene().defaultMaterial;
  19913. }
  19914. return this.subMaterials[index];
  19915. };
  19916. // Methods
  19917. MultiMaterial.prototype.isReady = function (mesh) {
  19918. for (var index = 0; index < this.subMaterials.length; index++) {
  19919. var subMaterial = this.subMaterials[index];
  19920. if (subMaterial) {
  19921. if (!this.subMaterials[index].isReady(mesh)) {
  19922. return false;
  19923. }
  19924. }
  19925. }
  19926. return true;
  19927. };
  19928. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19929. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19930. for (var index = 0; index < this.subMaterials.length; index++) {
  19931. var subMaterial = null;
  19932. if (cloneChildren) {
  19933. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19934. }
  19935. else {
  19936. subMaterial = this.subMaterials[index];
  19937. }
  19938. newMultiMaterial.subMaterials.push(subMaterial);
  19939. }
  19940. return newMultiMaterial;
  19941. };
  19942. MultiMaterial.prototype.serialize = function () {
  19943. var serializationObject = {};
  19944. serializationObject.name = this.name;
  19945. serializationObject.id = this.id;
  19946. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19947. serializationObject.materials = [];
  19948. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19949. var subMat = this.subMaterials[matIndex];
  19950. if (subMat) {
  19951. serializationObject.materials.push(subMat.id);
  19952. }
  19953. else {
  19954. serializationObject.materials.push(null);
  19955. }
  19956. }
  19957. return serializationObject;
  19958. };
  19959. return MultiMaterial;
  19960. })(BABYLON.Material);
  19961. BABYLON.MultiMaterial = MultiMaterial;
  19962. })(BABYLON || (BABYLON = {}));
  19963. var BABYLON;
  19964. (function (BABYLON) {
  19965. var SceneLoader = (function () {
  19966. function SceneLoader() {
  19967. }
  19968. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19969. get: function () {
  19970. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19971. },
  19972. set: function (value) {
  19973. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19974. },
  19975. enumerable: true,
  19976. configurable: true
  19977. });
  19978. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19979. get: function () {
  19980. return SceneLoader._ShowLoadingScreen;
  19981. },
  19982. set: function (value) {
  19983. SceneLoader._ShowLoadingScreen = value;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19989. var dotPosition = sceneFilename.lastIndexOf(".");
  19990. var queryStringPosition = sceneFilename.indexOf("?");
  19991. if (queryStringPosition === -1) {
  19992. queryStringPosition = sceneFilename.length;
  19993. }
  19994. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19995. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19996. var plugin = this._registeredPlugins[index];
  19997. if (plugin.extensions.indexOf(extension) !== -1) {
  19998. return plugin;
  19999. }
  20000. }
  20001. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20002. };
  20003. // Public functions
  20004. SceneLoader.RegisterPlugin = function (plugin) {
  20005. plugin.extensions = plugin.extensions.toLowerCase();
  20006. SceneLoader._registeredPlugins.push(plugin);
  20007. };
  20008. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20009. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20010. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20011. return;
  20012. }
  20013. var loadingToken = {};
  20014. scene._addPendingData(loadingToken);
  20015. var manifestChecked = function (success) {
  20016. scene.database = database;
  20017. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20018. var importMeshFromData = function (data) {
  20019. var meshes = [];
  20020. var particleSystems = [];
  20021. var skeletons = [];
  20022. try {
  20023. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20024. if (onerror) {
  20025. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20026. }
  20027. scene._removePendingData(loadingToken);
  20028. return;
  20029. }
  20030. }
  20031. catch (e) {
  20032. if (onerror) {
  20033. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20034. }
  20035. scene._removePendingData(loadingToken);
  20036. return;
  20037. }
  20038. if (onsuccess) {
  20039. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20040. onsuccess(meshes, particleSystems, skeletons);
  20041. scene._removePendingData(loadingToken);
  20042. }
  20043. };
  20044. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20045. // Direct load
  20046. importMeshFromData(sceneFilename.substr(5));
  20047. return;
  20048. }
  20049. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20050. importMeshFromData(data);
  20051. }, progressCallBack, database);
  20052. };
  20053. if (scene.getEngine().enableOfflineSupport) {
  20054. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20055. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20056. }
  20057. else {
  20058. manifestChecked(true);
  20059. }
  20060. };
  20061. /**
  20062. * Load a scene
  20063. * @param rootUrl a string that defines the root url for scene and resources
  20064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20066. */
  20067. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20068. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20069. };
  20070. /**
  20071. * Append a scene
  20072. * @param rootUrl a string that defines the root url for scene and resources
  20073. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20074. * @param scene is the instance of BABYLON.Scene to append to
  20075. */
  20076. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20077. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20078. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20079. return;
  20080. }
  20081. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20082. var database;
  20083. var loadingToken = {};
  20084. scene._addPendingData(loadingToken);
  20085. if (SceneLoader.ShowLoadingScreen) {
  20086. scene.getEngine().displayLoadingUI();
  20087. }
  20088. var loadSceneFromData = function (data) {
  20089. scene.database = database;
  20090. if (!plugin.load(scene, data, rootUrl)) {
  20091. if (onerror) {
  20092. onerror(scene);
  20093. }
  20094. scene._removePendingData(loadingToken);
  20095. scene.getEngine().hideLoadingUI();
  20096. return;
  20097. }
  20098. if (onsuccess) {
  20099. onsuccess(scene);
  20100. }
  20101. scene._removePendingData(loadingToken);
  20102. if (SceneLoader.ShowLoadingScreen) {
  20103. scene.executeWhenReady(function () {
  20104. scene.getEngine().hideLoadingUI();
  20105. });
  20106. }
  20107. };
  20108. var manifestChecked = function (success) {
  20109. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20110. };
  20111. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20112. // Direct load
  20113. loadSceneFromData(sceneFilename.substr(5));
  20114. return;
  20115. }
  20116. if (rootUrl.indexOf("file:") === -1) {
  20117. if (scene.getEngine().enableOfflineSupport) {
  20118. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20119. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20120. }
  20121. else {
  20122. manifestChecked(true);
  20123. }
  20124. }
  20125. else {
  20126. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20127. }
  20128. };
  20129. // Flags
  20130. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20131. SceneLoader._ShowLoadingScreen = true;
  20132. // Members
  20133. SceneLoader._registeredPlugins = new Array();
  20134. return SceneLoader;
  20135. })();
  20136. BABYLON.SceneLoader = SceneLoader;
  20137. ;
  20138. })(BABYLON || (BABYLON = {}));
  20139. var BABYLON;
  20140. (function (BABYLON) {
  20141. var Internals;
  20142. (function (Internals) {
  20143. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20144. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20145. var parsedMaterial = parsedData.materials[index];
  20146. if (parsedMaterial.id === id) {
  20147. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20148. }
  20149. }
  20150. return null;
  20151. };
  20152. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20153. names = (names instanceof Array) ? names : [names];
  20154. for (var i in names) {
  20155. if (mesh.name === names[i]) {
  20156. hierarchyIds.push(mesh.id);
  20157. return true;
  20158. }
  20159. }
  20160. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20161. hierarchyIds.push(mesh.id);
  20162. return true;
  20163. }
  20164. return false;
  20165. };
  20166. BABYLON.SceneLoader.RegisterPlugin({
  20167. extensions: ".babylon",
  20168. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20169. var parsedData = JSON.parse(data);
  20170. var loadedSkeletonsIds = [];
  20171. var loadedMaterialsIds = [];
  20172. var hierarchyIds = [];
  20173. var index;
  20174. var cache;
  20175. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20176. var parsedMesh = parsedData.meshes[index];
  20177. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20178. if (meshesNames instanceof Array) {
  20179. // Remove found mesh name from list.
  20180. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20181. }
  20182. //Geometry?
  20183. if (parsedMesh.geometryId) {
  20184. //does the file contain geometries?
  20185. if (parsedData.geometries) {
  20186. //find the correct geometry and add it to the scene
  20187. var found = false;
  20188. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20189. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20190. return;
  20191. }
  20192. else {
  20193. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20194. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20195. switch (geometryType) {
  20196. case "boxes":
  20197. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20198. break;
  20199. case "spheres":
  20200. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20201. break;
  20202. case "cylinders":
  20203. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20204. break;
  20205. case "toruses":
  20206. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20207. break;
  20208. case "grounds":
  20209. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20210. break;
  20211. case "planes":
  20212. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20213. break;
  20214. case "torusKnots":
  20215. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20216. break;
  20217. case "vertexData":
  20218. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20219. break;
  20220. }
  20221. found = true;
  20222. }
  20223. });
  20224. }
  20225. });
  20226. if (!found) {
  20227. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20228. }
  20229. }
  20230. }
  20231. // Material ?
  20232. if (parsedMesh.materialId) {
  20233. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20234. if (!materialFound && parsedData.multiMaterials) {
  20235. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20236. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20237. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20238. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20239. var subMatId = parsedMultiMaterial.materials[matIndex];
  20240. loadedMaterialsIds.push(subMatId);
  20241. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20242. }
  20243. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20244. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20245. materialFound = true;
  20246. break;
  20247. }
  20248. }
  20249. }
  20250. if (!materialFound) {
  20251. loadedMaterialsIds.push(parsedMesh.materialId);
  20252. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20253. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20254. }
  20255. }
  20256. }
  20257. // Skeleton ?
  20258. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20259. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20260. if (!skeletonAlreadyLoaded) {
  20261. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20262. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20263. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20264. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20265. loadedSkeletonsIds.push(parsedSkeleton.id);
  20266. }
  20267. }
  20268. }
  20269. }
  20270. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20271. meshes.push(mesh);
  20272. }
  20273. }
  20274. // Connecting parents
  20275. var currentMesh;
  20276. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20277. currentMesh = scene.meshes[index];
  20278. if (currentMesh._waitingParentId) {
  20279. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20280. currentMesh._waitingParentId = undefined;
  20281. }
  20282. }
  20283. // freeze world matrix application
  20284. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20285. currentMesh = scene.meshes[index];
  20286. if (currentMesh._waitingFreezeWorldMatrix) {
  20287. currentMesh.freezeWorldMatrix();
  20288. currentMesh._waitingFreezeWorldMatrix = undefined;
  20289. }
  20290. }
  20291. // Particles
  20292. if (parsedData.particleSystems) {
  20293. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20294. var parsedParticleSystem = parsedData.particleSystems[index];
  20295. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20296. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20297. }
  20298. }
  20299. }
  20300. return true;
  20301. },
  20302. load: function (scene, data, rootUrl) {
  20303. var parsedData = JSON.parse(data);
  20304. // Scene
  20305. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20306. scene.autoClear = parsedData.autoClear;
  20307. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20308. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20309. if (parsedData.gravity) {
  20310. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20311. }
  20312. // Fog
  20313. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20314. scene.fogMode = parsedData.fogMode;
  20315. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20316. scene.fogStart = parsedData.fogStart;
  20317. scene.fogEnd = parsedData.fogEnd;
  20318. scene.fogDensity = parsedData.fogDensity;
  20319. }
  20320. //Physics
  20321. if (parsedData.physicsEnabled) {
  20322. var physicsPlugin;
  20323. if (parsedData.physicsEngine === "cannon") {
  20324. physicsPlugin = new BABYLON.CannonJSPlugin();
  20325. }
  20326. else if (parsedData.physicsEngine === "oimo") {
  20327. physicsPlugin = new BABYLON.OimoJSPlugin();
  20328. }
  20329. //else - default engine, which is currently oimo
  20330. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20331. scene.enablePhysics(physicsGravity, physicsPlugin);
  20332. }
  20333. //collisions, if defined. otherwise, default is true
  20334. if (parsedData.collisionsEnabled != undefined) {
  20335. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20336. }
  20337. scene.workerCollisions = !!parsedData.workerCollisions;
  20338. var index;
  20339. var cache;
  20340. // Lights
  20341. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20342. var parsedLight = parsedData.lights[index];
  20343. BABYLON.Light.Parse(parsedLight, scene);
  20344. }
  20345. // Materials
  20346. if (parsedData.materials) {
  20347. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20348. var parsedMaterial = parsedData.materials[index];
  20349. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20350. }
  20351. }
  20352. if (parsedData.multiMaterials) {
  20353. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20354. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20355. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20356. }
  20357. }
  20358. // Skeletons
  20359. if (parsedData.skeletons) {
  20360. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20361. var parsedSkeleton = parsedData.skeletons[index];
  20362. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20363. }
  20364. }
  20365. // Geometries
  20366. var geometries = parsedData.geometries;
  20367. if (geometries) {
  20368. // Boxes
  20369. var boxes = geometries.boxes;
  20370. if (boxes) {
  20371. for (index = 0, cache = boxes.length; index < cache; index++) {
  20372. var parsedBox = boxes[index];
  20373. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20374. }
  20375. }
  20376. // Spheres
  20377. var spheres = geometries.spheres;
  20378. if (spheres) {
  20379. for (index = 0, cache = spheres.length; index < cache; index++) {
  20380. var parsedSphere = spheres[index];
  20381. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20382. }
  20383. }
  20384. // Cylinders
  20385. var cylinders = geometries.cylinders;
  20386. if (cylinders) {
  20387. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20388. var parsedCylinder = cylinders[index];
  20389. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20390. }
  20391. }
  20392. // Toruses
  20393. var toruses = geometries.toruses;
  20394. if (toruses) {
  20395. for (index = 0, cache = toruses.length; index < cache; index++) {
  20396. var parsedTorus = toruses[index];
  20397. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20398. }
  20399. }
  20400. // Grounds
  20401. var grounds = geometries.grounds;
  20402. if (grounds) {
  20403. for (index = 0, cache = grounds.length; index < cache; index++) {
  20404. var parsedGround = grounds[index];
  20405. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20406. }
  20407. }
  20408. // Planes
  20409. var planes = geometries.planes;
  20410. if (planes) {
  20411. for (index = 0, cache = planes.length; index < cache; index++) {
  20412. var parsedPlane = planes[index];
  20413. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20414. }
  20415. }
  20416. // TorusKnots
  20417. var torusKnots = geometries.torusKnots;
  20418. if (torusKnots) {
  20419. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20420. var parsedTorusKnot = torusKnots[index];
  20421. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20422. }
  20423. }
  20424. // VertexData
  20425. var vertexData = geometries.vertexData;
  20426. if (vertexData) {
  20427. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20428. var parsedVertexData = vertexData[index];
  20429. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20430. }
  20431. }
  20432. }
  20433. // Meshes
  20434. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20435. var parsedMesh = parsedData.meshes[index];
  20436. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20437. }
  20438. // Cameras
  20439. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20440. var parsedCamera = parsedData.cameras[index];
  20441. BABYLON.Camera.Parse(parsedCamera, scene);
  20442. }
  20443. if (parsedData.activeCameraID) {
  20444. scene.setActiveCameraByID(parsedData.activeCameraID);
  20445. }
  20446. // Browsing all the graph to connect the dots
  20447. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20448. var camera = scene.cameras[index];
  20449. if (camera._waitingParentId) {
  20450. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20451. camera._waitingParentId = undefined;
  20452. }
  20453. }
  20454. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20455. var light = scene.lights[index];
  20456. if (light._waitingParentId) {
  20457. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20458. light._waitingParentId = undefined;
  20459. }
  20460. }
  20461. // Sounds
  20462. var loadedSounds = [];
  20463. var loadedSound;
  20464. if (BABYLON.AudioEngine && parsedData.sounds) {
  20465. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20466. var parsedSound = parsedData.sounds[index];
  20467. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20468. if (!parsedSound.url)
  20469. parsedSound.url = parsedSound.name;
  20470. if (!loadedSounds[parsedSound.url]) {
  20471. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20472. loadedSounds[parsedSound.url] = loadedSound;
  20473. }
  20474. else {
  20475. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20476. }
  20477. }
  20478. else {
  20479. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20480. }
  20481. }
  20482. }
  20483. loadedSounds = [];
  20484. // Connect parents & children and parse actions
  20485. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20486. var mesh = scene.meshes[index];
  20487. if (mesh._waitingParentId) {
  20488. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20489. mesh._waitingParentId = undefined;
  20490. }
  20491. if (mesh._waitingActions) {
  20492. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20493. mesh._waitingActions = undefined;
  20494. }
  20495. }
  20496. // freeze world matrix application
  20497. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20498. var currentMesh = scene.meshes[index];
  20499. if (currentMesh._waitingFreezeWorldMatrix) {
  20500. currentMesh.freezeWorldMatrix();
  20501. currentMesh._waitingFreezeWorldMatrix = undefined;
  20502. }
  20503. }
  20504. // Particles Systems
  20505. if (parsedData.particleSystems) {
  20506. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20507. var parsedParticleSystem = parsedData.particleSystems[index];
  20508. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20509. }
  20510. }
  20511. // Lens flares
  20512. if (parsedData.lensFlareSystems) {
  20513. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20514. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20515. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20516. }
  20517. }
  20518. // Shadows
  20519. if (parsedData.shadowGenerators) {
  20520. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20521. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20522. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20523. }
  20524. }
  20525. // Actions (scene)
  20526. if (parsedData.actions) {
  20527. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20528. }
  20529. // Finish
  20530. return true;
  20531. }
  20532. });
  20533. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20534. })(BABYLON || (BABYLON = {}));
  20535. var BABYLON;
  20536. (function (BABYLON) {
  20537. var SpriteManager = (function () {
  20538. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20540. this.name = name;
  20541. this.cellSize = cellSize;
  20542. this.sprites = new Array();
  20543. this.renderingGroupId = 0;
  20544. this.layerMask = 0x0FFFFFFF;
  20545. this.fogEnabled = true;
  20546. this.isPickable = false;
  20547. this._vertexDeclaration = [4, 4, 4, 4];
  20548. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20549. this._capacity = capacity;
  20550. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20551. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20552. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20553. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20554. this._scene = scene;
  20555. this._scene.spriteManagers.push(this);
  20556. // VBO
  20557. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20558. var indices = [];
  20559. var index = 0;
  20560. for (var count = 0; count < capacity; count++) {
  20561. indices.push(index);
  20562. indices.push(index + 1);
  20563. indices.push(index + 2);
  20564. indices.push(index);
  20565. indices.push(index + 2);
  20566. indices.push(index + 3);
  20567. index += 4;
  20568. }
  20569. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20570. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20571. // Effects
  20572. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20573. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20574. }
  20575. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20576. var arrayOffset = index * 16;
  20577. if (offsetX === 0)
  20578. offsetX = this._epsilon;
  20579. else if (offsetX === 1)
  20580. offsetX = 1 - this._epsilon;
  20581. if (offsetY === 0)
  20582. offsetY = this._epsilon;
  20583. else if (offsetY === 1)
  20584. offsetY = 1 - this._epsilon;
  20585. this._vertices[arrayOffset] = sprite.position.x;
  20586. this._vertices[arrayOffset + 1] = sprite.position.y;
  20587. this._vertices[arrayOffset + 2] = sprite.position.z;
  20588. this._vertices[arrayOffset + 3] = sprite.angle;
  20589. this._vertices[arrayOffset + 4] = sprite.width;
  20590. this._vertices[arrayOffset + 5] = sprite.height;
  20591. this._vertices[arrayOffset + 6] = offsetX;
  20592. this._vertices[arrayOffset + 7] = offsetY;
  20593. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20594. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20595. var offset = (sprite.cellIndex / rowSize) >> 0;
  20596. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20597. this._vertices[arrayOffset + 11] = offset;
  20598. // Color
  20599. this._vertices[arrayOffset + 12] = sprite.color.r;
  20600. this._vertices[arrayOffset + 13] = sprite.color.g;
  20601. this._vertices[arrayOffset + 14] = sprite.color.b;
  20602. this._vertices[arrayOffset + 15] = sprite.color.a;
  20603. };
  20604. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20605. var count = Math.min(this._capacity, this.sprites.length);
  20606. var min = BABYLON.Vector3.Zero();
  20607. var max = BABYLON.Vector3.Zero();
  20608. var distance = Number.MAX_VALUE;
  20609. var currentSprite;
  20610. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20611. var cameraView = camera.getViewMatrix();
  20612. for (var index = 0; index < count; index++) {
  20613. var sprite = this.sprites[index];
  20614. if (!sprite) {
  20615. continue;
  20616. }
  20617. if (predicate) {
  20618. if (!predicate(sprite)) {
  20619. continue;
  20620. }
  20621. }
  20622. else if (!sprite.isPickable) {
  20623. continue;
  20624. }
  20625. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20626. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20627. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20628. if (ray.intersectsBoxMinMax(min, max)) {
  20629. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20630. if (distance > currentDistance) {
  20631. distance = currentDistance;
  20632. currentSprite = sprite;
  20633. if (fastCheck) {
  20634. break;
  20635. }
  20636. }
  20637. }
  20638. }
  20639. if (currentSprite) {
  20640. var result = new BABYLON.PickingInfo();
  20641. result.hit = true;
  20642. result.pickedSprite = currentSprite;
  20643. result.distance = distance;
  20644. return result;
  20645. }
  20646. return null;
  20647. };
  20648. SpriteManager.prototype.render = function () {
  20649. // Check
  20650. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20651. return;
  20652. var engine = this._scene.getEngine();
  20653. var baseSize = this._spriteTexture.getBaseSize();
  20654. // Sprites
  20655. var deltaTime = engine.getDeltaTime();
  20656. var max = Math.min(this._capacity, this.sprites.length);
  20657. var rowSize = baseSize.width / this.cellSize;
  20658. var offset = 0;
  20659. for (var index = 0; index < max; index++) {
  20660. var sprite = this.sprites[index];
  20661. if (!sprite) {
  20662. continue;
  20663. }
  20664. sprite._animate(deltaTime);
  20665. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20666. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20667. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20668. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20669. }
  20670. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20671. // Render
  20672. var effect = this._effectBase;
  20673. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20674. effect = this._effectFog;
  20675. }
  20676. engine.enableEffect(effect);
  20677. var viewMatrix = this._scene.getViewMatrix();
  20678. effect.setTexture("diffuseSampler", this._spriteTexture);
  20679. effect.setMatrix("view", viewMatrix);
  20680. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20681. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20682. // Fog
  20683. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20684. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20685. effect.setColor3("vFogColor", this._scene.fogColor);
  20686. }
  20687. // VBOs
  20688. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20689. // Draw order
  20690. engine.setDepthFunctionToLessOrEqual();
  20691. effect.setBool("alphaTest", true);
  20692. engine.setColorWrite(false);
  20693. engine.draw(true, 0, max * 6);
  20694. engine.setColorWrite(true);
  20695. effect.setBool("alphaTest", false);
  20696. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20697. engine.draw(true, 0, max * 6);
  20698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20699. };
  20700. SpriteManager.prototype.dispose = function () {
  20701. if (this._vertexBuffer) {
  20702. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20703. this._vertexBuffer = null;
  20704. }
  20705. if (this._indexBuffer) {
  20706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20707. this._indexBuffer = null;
  20708. }
  20709. if (this._spriteTexture) {
  20710. this._spriteTexture.dispose();
  20711. this._spriteTexture = null;
  20712. }
  20713. // Remove from scene
  20714. var index = this._scene.spriteManagers.indexOf(this);
  20715. this._scene.spriteManagers.splice(index, 1);
  20716. // Callback
  20717. if (this.onDispose) {
  20718. this.onDispose();
  20719. }
  20720. };
  20721. return SpriteManager;
  20722. })();
  20723. BABYLON.SpriteManager = SpriteManager;
  20724. })(BABYLON || (BABYLON = {}));
  20725. var BABYLON;
  20726. (function (BABYLON) {
  20727. var Sprite = (function () {
  20728. function Sprite(name, manager) {
  20729. this.name = name;
  20730. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20731. this.width = 1.0;
  20732. this.height = 1.0;
  20733. this.angle = 0;
  20734. this.cellIndex = 0;
  20735. this.invertU = 0;
  20736. this.invertV = 0;
  20737. this.animations = new Array();
  20738. this.isPickable = false;
  20739. this._animationStarted = false;
  20740. this._loopAnimation = false;
  20741. this._fromIndex = 0;
  20742. this._toIndex = 0;
  20743. this._delay = 0;
  20744. this._direction = 1;
  20745. this._frameCount = 0;
  20746. this._time = 0;
  20747. this._manager = manager;
  20748. this._manager.sprites.push(this);
  20749. this.position = BABYLON.Vector3.Zero();
  20750. }
  20751. Object.defineProperty(Sprite.prototype, "size", {
  20752. get: function () {
  20753. return this.width;
  20754. },
  20755. set: function (value) {
  20756. this.width = value;
  20757. this.height = value;
  20758. },
  20759. enumerable: true,
  20760. configurable: true
  20761. });
  20762. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20763. this._fromIndex = from;
  20764. this._toIndex = to;
  20765. this._loopAnimation = loop;
  20766. this._delay = delay;
  20767. this._animationStarted = true;
  20768. this._direction = from < to ? 1 : -1;
  20769. this.cellIndex = from;
  20770. this._time = 0;
  20771. };
  20772. Sprite.prototype.stopAnimation = function () {
  20773. this._animationStarted = false;
  20774. };
  20775. Sprite.prototype._animate = function (deltaTime) {
  20776. if (!this._animationStarted)
  20777. return;
  20778. this._time += deltaTime;
  20779. if (this._time > this._delay) {
  20780. this._time = this._time % this._delay;
  20781. this.cellIndex += this._direction;
  20782. if (this.cellIndex == this._toIndex) {
  20783. if (this._loopAnimation) {
  20784. this.cellIndex = this._fromIndex;
  20785. }
  20786. else {
  20787. this._animationStarted = false;
  20788. if (this.disposeWhenFinishedAnimating) {
  20789. this.dispose();
  20790. }
  20791. }
  20792. }
  20793. }
  20794. };
  20795. Sprite.prototype.dispose = function () {
  20796. for (var i = 0; i < this._manager.sprites.length; i++) {
  20797. if (this._manager.sprites[i] == this) {
  20798. this._manager.sprites.splice(i, 1);
  20799. }
  20800. }
  20801. };
  20802. return Sprite;
  20803. })();
  20804. BABYLON.Sprite = Sprite;
  20805. })(BABYLON || (BABYLON = {}));
  20806. var BABYLON;
  20807. (function (BABYLON) {
  20808. var Layer = (function () {
  20809. function Layer(name, imgUrl, scene, isBackground, color) {
  20810. this.name = name;
  20811. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20812. this._vertexDeclaration = [2];
  20813. this._vertexStrideSize = 2 * 4;
  20814. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20815. this.isBackground = isBackground === undefined ? true : isBackground;
  20816. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20817. this._scene = scene;
  20818. this._scene.layers.push(this);
  20819. // VBO
  20820. var vertices = [];
  20821. vertices.push(1, 1);
  20822. vertices.push(-1, 1);
  20823. vertices.push(-1, -1);
  20824. vertices.push(1, -1);
  20825. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20826. // Indices
  20827. var indices = [];
  20828. indices.push(0);
  20829. indices.push(1);
  20830. indices.push(2);
  20831. indices.push(0);
  20832. indices.push(2);
  20833. indices.push(3);
  20834. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20835. // Effects
  20836. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20837. }
  20838. Layer.prototype.render = function () {
  20839. // Check
  20840. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20841. return;
  20842. var engine = this._scene.getEngine();
  20843. // Render
  20844. engine.enableEffect(this._effect);
  20845. engine.setState(false);
  20846. // Texture
  20847. this._effect.setTexture("textureSampler", this.texture);
  20848. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20849. // Color
  20850. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20851. // VBOs
  20852. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20853. // Draw order
  20854. engine.setAlphaMode(this.alphaBlendingMode);
  20855. engine.draw(true, 0, 6);
  20856. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20857. };
  20858. Layer.prototype.dispose = function () {
  20859. if (this._vertexBuffer) {
  20860. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20861. this._vertexBuffer = null;
  20862. }
  20863. if (this._indexBuffer) {
  20864. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20865. this._indexBuffer = null;
  20866. }
  20867. if (this.texture) {
  20868. this.texture.dispose();
  20869. this.texture = null;
  20870. }
  20871. // Remove from scene
  20872. var index = this._scene.layers.indexOf(this);
  20873. this._scene.layers.splice(index, 1);
  20874. // Callback
  20875. if (this.onDispose) {
  20876. this.onDispose();
  20877. }
  20878. };
  20879. return Layer;
  20880. })();
  20881. BABYLON.Layer = Layer;
  20882. })(BABYLON || (BABYLON = {}));
  20883. var BABYLON;
  20884. (function (BABYLON) {
  20885. var Particle = (function () {
  20886. function Particle() {
  20887. this.position = BABYLON.Vector3.Zero();
  20888. this.direction = BABYLON.Vector3.Zero();
  20889. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20890. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20891. this.lifeTime = 1.0;
  20892. this.age = 0;
  20893. this.size = 0;
  20894. this.angle = 0;
  20895. this.angularSpeed = 0;
  20896. }
  20897. Particle.prototype.copyTo = function (other) {
  20898. other.position.copyFrom(this.position);
  20899. other.direction.copyFrom(this.direction);
  20900. other.color.copyFrom(this.color);
  20901. other.colorStep.copyFrom(this.colorStep);
  20902. other.lifeTime = this.lifeTime;
  20903. other.age = this.age;
  20904. other.size = this.size;
  20905. other.angle = this.angle;
  20906. other.angularSpeed = this.angularSpeed;
  20907. };
  20908. return Particle;
  20909. })();
  20910. BABYLON.Particle = Particle;
  20911. })(BABYLON || (BABYLON = {}));
  20912. var BABYLON;
  20913. (function (BABYLON) {
  20914. var randomNumber = function (min, max) {
  20915. if (min === max) {
  20916. return (min);
  20917. }
  20918. var random = Math.random();
  20919. return ((random * (max - min)) + min);
  20920. };
  20921. var ParticleSystem = (function () {
  20922. function ParticleSystem(name, capacity, scene, customEffect) {
  20923. var _this = this;
  20924. this.name = name;
  20925. this.renderingGroupId = 0;
  20926. this.emitter = null;
  20927. this.emitRate = 10;
  20928. this.manualEmitCount = -1;
  20929. this.updateSpeed = 0.01;
  20930. this.targetStopDuration = 0;
  20931. this.disposeOnStop = false;
  20932. this.minEmitPower = 1;
  20933. this.maxEmitPower = 1;
  20934. this.minLifeTime = 1;
  20935. this.maxLifeTime = 1;
  20936. this.minSize = 1;
  20937. this.maxSize = 1;
  20938. this.minAngularSpeed = 0;
  20939. this.maxAngularSpeed = 0;
  20940. this.layerMask = 0x0FFFFFFF;
  20941. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20942. this.forceDepthWrite = false;
  20943. this.gravity = BABYLON.Vector3.Zero();
  20944. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20945. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20946. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20947. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20948. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20949. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20950. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20951. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20952. this.particles = new Array();
  20953. this._vertexDeclaration = [3, 4, 4];
  20954. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20955. this._stockParticles = new Array();
  20956. this._newPartsExcess = 0;
  20957. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20958. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20959. this._scaledDirection = BABYLON.Vector3.Zero();
  20960. this._scaledGravity = BABYLON.Vector3.Zero();
  20961. this._currentRenderId = -1;
  20962. this._started = false;
  20963. this._stopped = false;
  20964. this._actualFrame = 0;
  20965. this.id = name;
  20966. this._capacity = capacity;
  20967. this._scene = scene;
  20968. this._customEffect = customEffect;
  20969. scene.particleSystems.push(this);
  20970. // VBO
  20971. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20972. var indices = [];
  20973. var index = 0;
  20974. for (var count = 0; count < capacity; count++) {
  20975. indices.push(index);
  20976. indices.push(index + 1);
  20977. indices.push(index + 2);
  20978. indices.push(index);
  20979. indices.push(index + 2);
  20980. indices.push(index + 3);
  20981. index += 4;
  20982. }
  20983. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20984. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20985. // Default behaviors
  20986. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20987. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20988. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20989. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20990. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20991. };
  20992. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20993. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20994. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20995. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20997. };
  20998. this.updateFunction = function (particles) {
  20999. for (var index = 0; index < particles.length; index++) {
  21000. var particle = particles[index];
  21001. particle.age += _this._scaledUpdateSpeed;
  21002. if (particle.age >= particle.lifeTime) {
  21003. _this.recycleParticle(particle);
  21004. index--;
  21005. continue;
  21006. }
  21007. else {
  21008. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21009. particle.color.addInPlace(_this._scaledColorStep);
  21010. if (particle.color.a < 0)
  21011. particle.color.a = 0;
  21012. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21013. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21014. particle.position.addInPlace(_this._scaledDirection);
  21015. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21016. particle.direction.addInPlace(_this._scaledGravity);
  21017. }
  21018. }
  21019. };
  21020. }
  21021. ParticleSystem.prototype.recycleParticle = function (particle) {
  21022. var lastParticle = this.particles.pop();
  21023. if (lastParticle !== particle) {
  21024. lastParticle.copyTo(particle);
  21025. this._stockParticles.push(lastParticle);
  21026. }
  21027. };
  21028. ParticleSystem.prototype.getCapacity = function () {
  21029. return this._capacity;
  21030. };
  21031. ParticleSystem.prototype.isAlive = function () {
  21032. return this._alive;
  21033. };
  21034. ParticleSystem.prototype.isStarted = function () {
  21035. return this._started;
  21036. };
  21037. ParticleSystem.prototype.start = function () {
  21038. this._started = true;
  21039. this._stopped = false;
  21040. this._actualFrame = 0;
  21041. };
  21042. ParticleSystem.prototype.stop = function () {
  21043. this._stopped = true;
  21044. };
  21045. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21046. var offset = index * 11;
  21047. this._vertices[offset] = particle.position.x;
  21048. this._vertices[offset + 1] = particle.position.y;
  21049. this._vertices[offset + 2] = particle.position.z;
  21050. this._vertices[offset + 3] = particle.color.r;
  21051. this._vertices[offset + 4] = particle.color.g;
  21052. this._vertices[offset + 5] = particle.color.b;
  21053. this._vertices[offset + 6] = particle.color.a;
  21054. this._vertices[offset + 7] = particle.angle;
  21055. this._vertices[offset + 8] = particle.size;
  21056. this._vertices[offset + 9] = offsetX;
  21057. this._vertices[offset + 10] = offsetY;
  21058. };
  21059. ParticleSystem.prototype._update = function (newParticles) {
  21060. // Update current
  21061. this._alive = this.particles.length > 0;
  21062. this.updateFunction(this.particles);
  21063. // Add new ones
  21064. var worldMatrix;
  21065. if (this.emitter.position) {
  21066. worldMatrix = this.emitter.getWorldMatrix();
  21067. }
  21068. else {
  21069. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21070. }
  21071. var particle;
  21072. for (var index = 0; index < newParticles; index++) {
  21073. if (this.particles.length === this._capacity) {
  21074. break;
  21075. }
  21076. if (this._stockParticles.length !== 0) {
  21077. particle = this._stockParticles.pop();
  21078. particle.age = 0;
  21079. }
  21080. else {
  21081. particle = new BABYLON.Particle();
  21082. }
  21083. this.particles.push(particle);
  21084. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21085. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21086. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21087. particle.size = randomNumber(this.minSize, this.maxSize);
  21088. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21089. this.startPositionFunction(worldMatrix, particle.position, particle);
  21090. var step = randomNumber(0, 1.0);
  21091. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21092. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21093. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21094. }
  21095. };
  21096. ParticleSystem.prototype._getEffect = function () {
  21097. if (this._customEffect) {
  21098. return this._customEffect;
  21099. }
  21100. ;
  21101. var defines = [];
  21102. if (this._scene.clipPlane) {
  21103. defines.push("#define CLIPPLANE");
  21104. }
  21105. // Effect
  21106. var join = defines.join("\n");
  21107. if (this._cachedDefines !== join) {
  21108. this._cachedDefines = join;
  21109. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21110. }
  21111. return this._effect;
  21112. };
  21113. ParticleSystem.prototype.animate = function () {
  21114. if (!this._started)
  21115. return;
  21116. var effect = this._getEffect();
  21117. // Check
  21118. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21119. return;
  21120. if (this._currentRenderId === this._scene.getRenderId()) {
  21121. return;
  21122. }
  21123. this._currentRenderId = this._scene.getRenderId();
  21124. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21125. // determine the number of particles we need to create
  21126. var newParticles;
  21127. if (this.manualEmitCount > -1) {
  21128. newParticles = this.manualEmitCount;
  21129. this._newPartsExcess = 0;
  21130. this.manualEmitCount = 0;
  21131. }
  21132. else {
  21133. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21134. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21135. }
  21136. if (this._newPartsExcess > 1.0) {
  21137. newParticles += this._newPartsExcess >> 0;
  21138. this._newPartsExcess -= this._newPartsExcess >> 0;
  21139. }
  21140. this._alive = false;
  21141. if (!this._stopped) {
  21142. this._actualFrame += this._scaledUpdateSpeed;
  21143. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21144. this.stop();
  21145. }
  21146. else {
  21147. newParticles = 0;
  21148. }
  21149. this._update(newParticles);
  21150. // Stopped?
  21151. if (this._stopped) {
  21152. if (!this._alive) {
  21153. this._started = false;
  21154. if (this.disposeOnStop) {
  21155. this._scene._toBeDisposed.push(this);
  21156. }
  21157. }
  21158. }
  21159. // Update VBO
  21160. var offset = 0;
  21161. for (var index = 0; index < this.particles.length; index++) {
  21162. var particle = this.particles[index];
  21163. this._appendParticleVertex(offset++, particle, 0, 0);
  21164. this._appendParticleVertex(offset++, particle, 1, 0);
  21165. this._appendParticleVertex(offset++, particle, 1, 1);
  21166. this._appendParticleVertex(offset++, particle, 0, 1);
  21167. }
  21168. var engine = this._scene.getEngine();
  21169. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21170. };
  21171. ParticleSystem.prototype.render = function () {
  21172. var effect = this._getEffect();
  21173. // Check
  21174. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21175. return 0;
  21176. var engine = this._scene.getEngine();
  21177. // Render
  21178. engine.enableEffect(effect);
  21179. engine.setState(false);
  21180. var viewMatrix = this._scene.getViewMatrix();
  21181. effect.setTexture("diffuseSampler", this.particleTexture);
  21182. effect.setMatrix("view", viewMatrix);
  21183. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21184. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21185. if (this._scene.clipPlane) {
  21186. var clipPlane = this._scene.clipPlane;
  21187. var invView = viewMatrix.clone();
  21188. invView.invert();
  21189. effect.setMatrix("invView", invView);
  21190. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21191. }
  21192. // VBOs
  21193. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21194. // Draw order
  21195. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21196. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21197. }
  21198. else {
  21199. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21200. }
  21201. if (this.forceDepthWrite) {
  21202. engine.setDepthWrite(true);
  21203. }
  21204. engine.draw(true, 0, this.particles.length * 6);
  21205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21206. return this.particles.length;
  21207. };
  21208. ParticleSystem.prototype.dispose = function () {
  21209. if (this._vertexBuffer) {
  21210. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21211. this._vertexBuffer = null;
  21212. }
  21213. if (this._indexBuffer) {
  21214. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21215. this._indexBuffer = null;
  21216. }
  21217. if (this.particleTexture) {
  21218. this.particleTexture.dispose();
  21219. this.particleTexture = null;
  21220. }
  21221. // Remove from scene
  21222. var index = this._scene.particleSystems.indexOf(this);
  21223. this._scene.particleSystems.splice(index, 1);
  21224. // Callback
  21225. if (this.onDispose) {
  21226. this.onDispose();
  21227. }
  21228. };
  21229. // Clone
  21230. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21231. var result = new ParticleSystem(name, this._capacity, this._scene);
  21232. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21233. if (newEmitter === undefined) {
  21234. newEmitter = this.emitter;
  21235. }
  21236. result.emitter = newEmitter;
  21237. if (this.particleTexture) {
  21238. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21239. }
  21240. result.start();
  21241. return result;
  21242. };
  21243. ParticleSystem.prototype.serialize = function () {
  21244. var serializationObject = {};
  21245. serializationObject.name = this.name;
  21246. if (this.emitter.position) {
  21247. serializationObject.emitterId = this.emitter.id;
  21248. }
  21249. else {
  21250. serializationObject.emitter = this.emitter.asArray();
  21251. ;
  21252. }
  21253. serializationObject.capacity = this.getCapacity();
  21254. if (this.particleTexture) {
  21255. serializationObject.textureName = this.particleTexture.name;
  21256. }
  21257. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21258. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21259. serializationObject.minSize = this.minSize;
  21260. serializationObject.maxSize = this.maxSize;
  21261. serializationObject.minEmitPower = this.minEmitPower;
  21262. serializationObject.maxEmitPower = this.maxEmitPower;
  21263. serializationObject.minLifeTime = this.minLifeTime;
  21264. serializationObject.maxLifeTime = this.maxLifeTime;
  21265. serializationObject.emitRate = this.emitRate;
  21266. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21267. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21268. serializationObject.gravity = this.gravity.asArray();
  21269. serializationObject.direction1 = this.direction1.asArray();
  21270. serializationObject.direction2 = this.direction2.asArray();
  21271. serializationObject.color1 = this.color1.asArray();
  21272. serializationObject.color2 = this.color2.asArray();
  21273. serializationObject.colorDead = this.colorDead.asArray();
  21274. serializationObject.updateSpeed = this.updateSpeed;
  21275. serializationObject.targetStopDuration = this.targetStopDuration;
  21276. serializationObject.textureMask = this.textureMask.asArray();
  21277. serializationObject.blendMode = this.blendMode;
  21278. return serializationObject;
  21279. };
  21280. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21281. var name = parsedParticleSystem.name;
  21282. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21283. if (parsedParticleSystem.textureName) {
  21284. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21285. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21286. }
  21287. if (parsedParticleSystem.emitterId) {
  21288. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21289. }
  21290. else {
  21291. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21292. }
  21293. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21294. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21295. particleSystem.minSize = parsedParticleSystem.minSize;
  21296. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21297. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21298. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21299. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21300. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21301. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21302. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21303. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21304. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21305. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21306. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21307. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21308. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21309. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21310. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21311. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21312. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21313. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21314. particleSystem.start();
  21315. return particleSystem;
  21316. };
  21317. // Statics
  21318. ParticleSystem.BLENDMODE_ONEONE = 0;
  21319. ParticleSystem.BLENDMODE_STANDARD = 1;
  21320. return ParticleSystem;
  21321. })();
  21322. BABYLON.ParticleSystem = ParticleSystem;
  21323. })(BABYLON || (BABYLON = {}));
  21324. var BABYLON;
  21325. (function (BABYLON) {
  21326. var AnimationRange = (function () {
  21327. function AnimationRange(name, from, to) {
  21328. this.name = name;
  21329. this.from = from;
  21330. this.to = to;
  21331. }
  21332. return AnimationRange;
  21333. })();
  21334. BABYLON.AnimationRange = AnimationRange;
  21335. /**
  21336. * Composed of a frame, and an action function
  21337. */
  21338. var AnimationEvent = (function () {
  21339. function AnimationEvent(frame, action, onlyOnce) {
  21340. this.frame = frame;
  21341. this.action = action;
  21342. this.onlyOnce = onlyOnce;
  21343. this.isDone = false;
  21344. }
  21345. return AnimationEvent;
  21346. })();
  21347. BABYLON.AnimationEvent = AnimationEvent;
  21348. var Animation = (function () {
  21349. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21350. this.name = name;
  21351. this.targetProperty = targetProperty;
  21352. this.framePerSecond = framePerSecond;
  21353. this.dataType = dataType;
  21354. this.loopMode = loopMode;
  21355. this._offsetsCache = {};
  21356. this._highLimitsCache = {};
  21357. this._stopped = false;
  21358. // The set of event that will be linked to this animation
  21359. this._events = new Array();
  21360. this.allowMatricesInterpolation = false;
  21361. this._ranges = new Array();
  21362. this.targetPropertyPath = targetProperty.split(".");
  21363. this.dataType = dataType;
  21364. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21365. }
  21366. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21367. var dataType = undefined;
  21368. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21369. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21370. }
  21371. else if (from instanceof BABYLON.Quaternion) {
  21372. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21373. }
  21374. else if (from instanceof BABYLON.Vector3) {
  21375. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21376. }
  21377. else if (from instanceof BABYLON.Vector2) {
  21378. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21379. }
  21380. else if (from instanceof BABYLON.Color3) {
  21381. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21382. }
  21383. if (dataType == undefined) {
  21384. return null;
  21385. }
  21386. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21387. var keys = [];
  21388. keys.push({ frame: 0, value: from });
  21389. keys.push({ frame: totalFrame, value: to });
  21390. animation.setKeys(keys);
  21391. if (easingFunction !== undefined) {
  21392. animation.setEasingFunction(easingFunction);
  21393. }
  21394. return animation;
  21395. };
  21396. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21397. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21398. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21399. };
  21400. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21401. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21402. node.animations.push(animation);
  21403. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21404. };
  21405. // Methods
  21406. /**
  21407. * Add an event to this animation.
  21408. */
  21409. Animation.prototype.addEvent = function (event) {
  21410. this._events.push(event);
  21411. };
  21412. /**
  21413. * Remove all events found at the given frame
  21414. * @param frame
  21415. */
  21416. Animation.prototype.removeEvents = function (frame) {
  21417. for (var index = 0; index < this._events.length; index++) {
  21418. if (this._events[index].frame === frame) {
  21419. this._events.splice(index, 1);
  21420. index--;
  21421. }
  21422. }
  21423. };
  21424. Animation.prototype.createRange = function (name, from, to) {
  21425. this._ranges.push(new AnimationRange(name, from, to));
  21426. };
  21427. Animation.prototype.deleteRange = function (name) {
  21428. for (var index = 0; index < this._ranges.length; index++) {
  21429. if (this._ranges[index].name === name) {
  21430. this._ranges.splice(index, 1);
  21431. return;
  21432. }
  21433. }
  21434. };
  21435. Animation.prototype.getRange = function (name) {
  21436. for (var index = 0; index < this._ranges.length; index++) {
  21437. if (this._ranges[index].name === name) {
  21438. return this._ranges[index];
  21439. }
  21440. }
  21441. return null;
  21442. };
  21443. Animation.prototype.reset = function () {
  21444. this._offsetsCache = {};
  21445. this._highLimitsCache = {};
  21446. this.currentFrame = 0;
  21447. };
  21448. Animation.prototype.isStopped = function () {
  21449. return this._stopped;
  21450. };
  21451. Animation.prototype.getKeys = function () {
  21452. return this._keys;
  21453. };
  21454. Animation.prototype.getEasingFunction = function () {
  21455. return this._easingFunction;
  21456. };
  21457. Animation.prototype.setEasingFunction = function (easingFunction) {
  21458. this._easingFunction = easingFunction;
  21459. };
  21460. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21461. return startValue + (endValue - startValue) * gradient;
  21462. };
  21463. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21464. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21465. };
  21466. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21467. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21468. };
  21469. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21470. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21471. };
  21472. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21473. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21474. };
  21475. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21476. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21477. };
  21478. Animation.prototype.clone = function () {
  21479. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21480. if (this._keys) {
  21481. clone.setKeys(this._keys);
  21482. }
  21483. return clone;
  21484. };
  21485. Animation.prototype.setKeys = function (values) {
  21486. this._keys = values.slice(0);
  21487. this._offsetsCache = {};
  21488. this._highLimitsCache = {};
  21489. };
  21490. Animation.prototype._getKeyValue = function (value) {
  21491. if (typeof value === "function") {
  21492. return value();
  21493. }
  21494. return value;
  21495. };
  21496. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21497. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21498. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21499. }
  21500. this.currentFrame = currentFrame;
  21501. // Try to get a hash to find the right key
  21502. 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));
  21503. if (this._keys[startKey].frame >= currentFrame) {
  21504. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21505. startKey--;
  21506. }
  21507. }
  21508. for (var key = startKey; key < this._keys.length; key++) {
  21509. if (this._keys[key + 1].frame >= currentFrame) {
  21510. var startValue = this._getKeyValue(this._keys[key].value);
  21511. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21512. // gradient : percent of currentFrame between the frame inf and the frame sup
  21513. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21514. // check for easingFunction and correction of gradient
  21515. if (this._easingFunction != null) {
  21516. gradient = this._easingFunction.ease(gradient);
  21517. }
  21518. switch (this.dataType) {
  21519. // Float
  21520. case Animation.ANIMATIONTYPE_FLOAT:
  21521. switch (loopMode) {
  21522. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21523. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21524. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21525. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21526. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21527. }
  21528. break;
  21529. // Quaternion
  21530. case Animation.ANIMATIONTYPE_QUATERNION:
  21531. var quaternion = null;
  21532. switch (loopMode) {
  21533. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21534. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21535. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21536. break;
  21537. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21538. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21539. break;
  21540. }
  21541. return quaternion;
  21542. // Vector3
  21543. case Animation.ANIMATIONTYPE_VECTOR3:
  21544. switch (loopMode) {
  21545. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21546. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21547. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21548. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21549. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21550. }
  21551. // Vector2
  21552. case Animation.ANIMATIONTYPE_VECTOR2:
  21553. switch (loopMode) {
  21554. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21555. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21556. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21557. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21558. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21559. }
  21560. // Color3
  21561. case Animation.ANIMATIONTYPE_COLOR3:
  21562. switch (loopMode) {
  21563. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21564. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21565. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21566. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21567. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21568. }
  21569. // Matrix
  21570. case Animation.ANIMATIONTYPE_MATRIX:
  21571. switch (loopMode) {
  21572. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21573. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21574. if (this.allowMatricesInterpolation) {
  21575. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21576. }
  21577. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21578. return startValue;
  21579. }
  21580. default:
  21581. break;
  21582. }
  21583. break;
  21584. }
  21585. }
  21586. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21587. };
  21588. Animation.prototype.setValue = function (currentValue) {
  21589. // Set value
  21590. if (this.targetPropertyPath.length > 1) {
  21591. var property = this._target[this.targetPropertyPath[0]];
  21592. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21593. property = property[this.targetPropertyPath[index]];
  21594. }
  21595. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21596. }
  21597. else {
  21598. this._target[this.targetPropertyPath[0]] = currentValue;
  21599. }
  21600. if (this._target.markAsDirty) {
  21601. this._target.markAsDirty(this.targetProperty);
  21602. }
  21603. };
  21604. Animation.prototype.goToFrame = function (frame) {
  21605. if (frame < this._keys[0].frame) {
  21606. frame = this._keys[0].frame;
  21607. }
  21608. else if (frame > this._keys[this._keys.length - 1].frame) {
  21609. frame = this._keys[this._keys.length - 1].frame;
  21610. }
  21611. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21612. this.setValue(currentValue);
  21613. };
  21614. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21615. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21616. this._stopped = true;
  21617. return false;
  21618. }
  21619. var returnValue = true;
  21620. // Adding a start key at frame 0 if missing
  21621. if (this._keys[0].frame !== 0) {
  21622. var newKey = { frame: 0, value: this._keys[0].value };
  21623. this._keys.splice(0, 0, newKey);
  21624. }
  21625. // Check limits
  21626. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21627. from = this._keys[0].frame;
  21628. }
  21629. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21630. to = this._keys[this._keys.length - 1].frame;
  21631. }
  21632. // Compute ratio
  21633. var range = to - from;
  21634. var offsetValue;
  21635. // ratio represents the frame delta between from and to
  21636. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21637. var highLimitValue = 0;
  21638. if (ratio > range && !loop) {
  21639. returnValue = false;
  21640. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21641. }
  21642. else {
  21643. // Get max value if required
  21644. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21645. var keyOffset = to.toString() + from.toString();
  21646. if (!this._offsetsCache[keyOffset]) {
  21647. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21648. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21649. switch (this.dataType) {
  21650. // Float
  21651. case Animation.ANIMATIONTYPE_FLOAT:
  21652. this._offsetsCache[keyOffset] = toValue - fromValue;
  21653. break;
  21654. // Quaternion
  21655. case Animation.ANIMATIONTYPE_QUATERNION:
  21656. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21657. break;
  21658. // Vector3
  21659. case Animation.ANIMATIONTYPE_VECTOR3:
  21660. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21661. // Vector2
  21662. case Animation.ANIMATIONTYPE_VECTOR2:
  21663. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21664. // Color3
  21665. case Animation.ANIMATIONTYPE_COLOR3:
  21666. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21667. default:
  21668. break;
  21669. }
  21670. this._highLimitsCache[keyOffset] = toValue;
  21671. }
  21672. highLimitValue = this._highLimitsCache[keyOffset];
  21673. offsetValue = this._offsetsCache[keyOffset];
  21674. }
  21675. }
  21676. if (offsetValue === undefined) {
  21677. switch (this.dataType) {
  21678. // Float
  21679. case Animation.ANIMATIONTYPE_FLOAT:
  21680. offsetValue = 0;
  21681. break;
  21682. // Quaternion
  21683. case Animation.ANIMATIONTYPE_QUATERNION:
  21684. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21685. break;
  21686. // Vector3
  21687. case Animation.ANIMATIONTYPE_VECTOR3:
  21688. offsetValue = BABYLON.Vector3.Zero();
  21689. break;
  21690. // Vector2
  21691. case Animation.ANIMATIONTYPE_VECTOR2:
  21692. offsetValue = BABYLON.Vector2.Zero();
  21693. break;
  21694. // Color3
  21695. case Animation.ANIMATIONTYPE_COLOR3:
  21696. offsetValue = BABYLON.Color3.Black();
  21697. }
  21698. }
  21699. // Compute value
  21700. var repeatCount = (ratio / range) >> 0;
  21701. var currentFrame = returnValue ? from + ratio % range : to;
  21702. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21703. // Check events
  21704. for (var index = 0; index < this._events.length; index++) {
  21705. if (currentFrame >= this._events[index].frame) {
  21706. var event = this._events[index];
  21707. if (!event.isDone) {
  21708. // If event should be done only once, remove it.
  21709. if (event.onlyOnce) {
  21710. this._events.splice(index, 1);
  21711. index--;
  21712. }
  21713. event.isDone = true;
  21714. event.action();
  21715. } // Don't do anything if the event has already be done.
  21716. }
  21717. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21718. // reset event, the animation is looping
  21719. this._events[index].isDone = false;
  21720. }
  21721. }
  21722. // Set value
  21723. this.setValue(currentValue);
  21724. if (!returnValue) {
  21725. this._stopped = true;
  21726. }
  21727. return returnValue;
  21728. };
  21729. Animation.prototype.serialize = function () {
  21730. var serializationObject = {};
  21731. serializationObject.name = this.name;
  21732. serializationObject.property = this.targetProperty;
  21733. serializationObject.framePerSecond = this.framePerSecond;
  21734. serializationObject.dataType = this.dataType;
  21735. serializationObject.loopBehavior = this.loopMode;
  21736. var dataType = this.dataType;
  21737. serializationObject.keys = [];
  21738. var keys = this.getKeys();
  21739. for (var index = 0; index < keys.length; index++) {
  21740. var animationKey = keys[index];
  21741. var key = {};
  21742. key.frame = animationKey.frame;
  21743. switch (dataType) {
  21744. case Animation.ANIMATIONTYPE_FLOAT:
  21745. key.values = [animationKey.value];
  21746. break;
  21747. case Animation.ANIMATIONTYPE_QUATERNION:
  21748. case Animation.ANIMATIONTYPE_MATRIX:
  21749. case Animation.ANIMATIONTYPE_VECTOR3:
  21750. case Animation.ANIMATIONTYPE_COLOR3:
  21751. key.values = animationKey.value.asArray();
  21752. break;
  21753. }
  21754. serializationObject.keys.push(key);
  21755. }
  21756. return serializationObject;
  21757. };
  21758. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21759. get: function () {
  21760. return Animation._ANIMATIONTYPE_FLOAT;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21766. get: function () {
  21767. return Animation._ANIMATIONTYPE_VECTOR3;
  21768. },
  21769. enumerable: true,
  21770. configurable: true
  21771. });
  21772. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21773. get: function () {
  21774. return Animation._ANIMATIONTYPE_VECTOR2;
  21775. },
  21776. enumerable: true,
  21777. configurable: true
  21778. });
  21779. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21780. get: function () {
  21781. return Animation._ANIMATIONTYPE_QUATERNION;
  21782. },
  21783. enumerable: true,
  21784. configurable: true
  21785. });
  21786. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21787. get: function () {
  21788. return Animation._ANIMATIONTYPE_MATRIX;
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21794. get: function () {
  21795. return Animation._ANIMATIONTYPE_COLOR3;
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21801. get: function () {
  21802. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21808. get: function () {
  21809. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21815. get: function () {
  21816. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Animation.Parse = function (parsedAnimation) {
  21822. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21823. var dataType = parsedAnimation.dataType;
  21824. var keys = [];
  21825. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21826. var key = parsedAnimation.keys[index];
  21827. var data;
  21828. switch (dataType) {
  21829. case Animation.ANIMATIONTYPE_FLOAT:
  21830. data = key.values[0];
  21831. break;
  21832. case Animation.ANIMATIONTYPE_QUATERNION:
  21833. data = BABYLON.Quaternion.FromArray(key.values);
  21834. break;
  21835. case Animation.ANIMATIONTYPE_MATRIX:
  21836. data = BABYLON.Matrix.FromArray(key.values);
  21837. break;
  21838. case Animation.ANIMATIONTYPE_COLOR3:
  21839. data = BABYLON.Color3.FromArray(key.values);
  21840. break;
  21841. case Animation.ANIMATIONTYPE_VECTOR3:
  21842. default:
  21843. data = BABYLON.Vector3.FromArray(key.values);
  21844. break;
  21845. }
  21846. keys.push({
  21847. frame: key.frame,
  21848. value: data
  21849. });
  21850. }
  21851. animation.setKeys(keys);
  21852. return animation;
  21853. };
  21854. Animation.AppendSerializedAnimations = function (source, destination) {
  21855. if (source.animations) {
  21856. destination.animations = [];
  21857. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21858. var animation = source.animations[animationIndex];
  21859. destination.animations.push(animation.serialize());
  21860. }
  21861. }
  21862. };
  21863. // Statics
  21864. Animation._ANIMATIONTYPE_FLOAT = 0;
  21865. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21866. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21867. Animation._ANIMATIONTYPE_MATRIX = 3;
  21868. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21869. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21870. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21871. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21872. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21873. return Animation;
  21874. })();
  21875. BABYLON.Animation = Animation;
  21876. })(BABYLON || (BABYLON = {}));
  21877. var BABYLON;
  21878. (function (BABYLON) {
  21879. var Animatable = (function () {
  21880. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21881. if (fromFrame === void 0) { fromFrame = 0; }
  21882. if (toFrame === void 0) { toFrame = 100; }
  21883. if (loopAnimation === void 0) { loopAnimation = false; }
  21884. if (speedRatio === void 0) { speedRatio = 1.0; }
  21885. this.target = target;
  21886. this.fromFrame = fromFrame;
  21887. this.toFrame = toFrame;
  21888. this.loopAnimation = loopAnimation;
  21889. this.speedRatio = speedRatio;
  21890. this.onAnimationEnd = onAnimationEnd;
  21891. this._animations = new Array();
  21892. this._paused = false;
  21893. this.animationStarted = false;
  21894. if (animations) {
  21895. this.appendAnimations(target, animations);
  21896. }
  21897. this._scene = scene;
  21898. scene._activeAnimatables.push(this);
  21899. }
  21900. // Methods
  21901. Animatable.prototype.getAnimations = function () {
  21902. return this._animations;
  21903. };
  21904. Animatable.prototype.appendAnimations = function (target, animations) {
  21905. for (var index = 0; index < animations.length; index++) {
  21906. var animation = animations[index];
  21907. animation._target = target;
  21908. this._animations.push(animation);
  21909. }
  21910. };
  21911. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21912. var animations = this._animations;
  21913. for (var index = 0; index < animations.length; index++) {
  21914. if (animations[index].targetProperty === property) {
  21915. return animations[index];
  21916. }
  21917. }
  21918. return null;
  21919. };
  21920. Animatable.prototype.reset = function () {
  21921. var animations = this._animations;
  21922. for (var index = 0; index < animations.length; index++) {
  21923. animations[index].reset();
  21924. }
  21925. this._localDelayOffset = null;
  21926. this._pausedDelay = null;
  21927. };
  21928. Animatable.prototype.goToFrame = function (frame) {
  21929. var animations = this._animations;
  21930. for (var index = 0; index < animations.length; index++) {
  21931. animations[index].goToFrame(frame);
  21932. }
  21933. };
  21934. Animatable.prototype.pause = function () {
  21935. if (this._paused) {
  21936. return;
  21937. }
  21938. this._paused = true;
  21939. };
  21940. Animatable.prototype.restart = function () {
  21941. this._paused = false;
  21942. };
  21943. Animatable.prototype.stop = function () {
  21944. var index = this._scene._activeAnimatables.indexOf(this);
  21945. if (index > -1) {
  21946. this._scene._activeAnimatables.splice(index, 1);
  21947. }
  21948. if (this.onAnimationEnd) {
  21949. this.onAnimationEnd();
  21950. }
  21951. };
  21952. Animatable.prototype._animate = function (delay) {
  21953. if (this._paused) {
  21954. this.animationStarted = false;
  21955. if (!this._pausedDelay) {
  21956. this._pausedDelay = delay;
  21957. }
  21958. return true;
  21959. }
  21960. if (!this._localDelayOffset) {
  21961. this._localDelayOffset = delay;
  21962. }
  21963. else if (this._pausedDelay) {
  21964. this._localDelayOffset += delay - this._pausedDelay;
  21965. this._pausedDelay = null;
  21966. }
  21967. // Animating
  21968. var running = false;
  21969. var animations = this._animations;
  21970. var index;
  21971. for (index = 0; index < animations.length; index++) {
  21972. var animation = animations[index];
  21973. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21974. running = running || isRunning;
  21975. }
  21976. this.animationStarted = running;
  21977. if (!running) {
  21978. // Remove from active animatables
  21979. index = this._scene._activeAnimatables.indexOf(this);
  21980. this._scene._activeAnimatables.splice(index, 1);
  21981. }
  21982. if (!running && this.onAnimationEnd) {
  21983. this.onAnimationEnd();
  21984. }
  21985. return running;
  21986. };
  21987. return Animatable;
  21988. })();
  21989. BABYLON.Animatable = Animatable;
  21990. })(BABYLON || (BABYLON = {}));
  21991. var BABYLON;
  21992. (function (BABYLON) {
  21993. var EasingFunction = (function () {
  21994. function EasingFunction() {
  21995. // Properties
  21996. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21997. }
  21998. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21999. get: function () {
  22000. return EasingFunction._EASINGMODE_EASEIN;
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22006. get: function () {
  22007. return EasingFunction._EASINGMODE_EASEOUT;
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22013. get: function () {
  22014. return EasingFunction._EASINGMODE_EASEINOUT;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22020. var n = Math.min(Math.max(easingMode, 0), 2);
  22021. this._easingMode = n;
  22022. };
  22023. EasingFunction.prototype.getEasingMode = function () {
  22024. return this._easingMode;
  22025. };
  22026. EasingFunction.prototype.easeInCore = function (gradient) {
  22027. throw new Error('You must implement this method');
  22028. };
  22029. EasingFunction.prototype.ease = function (gradient) {
  22030. switch (this._easingMode) {
  22031. case EasingFunction.EASINGMODE_EASEIN:
  22032. return this.easeInCore(gradient);
  22033. case EasingFunction.EASINGMODE_EASEOUT:
  22034. return (1 - this.easeInCore(1 - gradient));
  22035. }
  22036. if (gradient >= 0.5) {
  22037. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22038. }
  22039. return (this.easeInCore(gradient * 2) * 0.5);
  22040. };
  22041. //Statics
  22042. EasingFunction._EASINGMODE_EASEIN = 0;
  22043. EasingFunction._EASINGMODE_EASEOUT = 1;
  22044. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22045. return EasingFunction;
  22046. })();
  22047. BABYLON.EasingFunction = EasingFunction;
  22048. var CircleEase = (function (_super) {
  22049. __extends(CircleEase, _super);
  22050. function CircleEase() {
  22051. _super.apply(this, arguments);
  22052. }
  22053. CircleEase.prototype.easeInCore = function (gradient) {
  22054. gradient = Math.max(0, Math.min(1, gradient));
  22055. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22056. };
  22057. return CircleEase;
  22058. })(EasingFunction);
  22059. BABYLON.CircleEase = CircleEase;
  22060. var BackEase = (function (_super) {
  22061. __extends(BackEase, _super);
  22062. function BackEase(amplitude) {
  22063. if (amplitude === void 0) { amplitude = 1; }
  22064. _super.call(this);
  22065. this.amplitude = amplitude;
  22066. }
  22067. BackEase.prototype.easeInCore = function (gradient) {
  22068. var num = Math.max(0, this.amplitude);
  22069. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22070. };
  22071. return BackEase;
  22072. })(EasingFunction);
  22073. BABYLON.BackEase = BackEase;
  22074. var BounceEase = (function (_super) {
  22075. __extends(BounceEase, _super);
  22076. function BounceEase(bounces, bounciness) {
  22077. if (bounces === void 0) { bounces = 3; }
  22078. if (bounciness === void 0) { bounciness = 2; }
  22079. _super.call(this);
  22080. this.bounces = bounces;
  22081. this.bounciness = bounciness;
  22082. }
  22083. BounceEase.prototype.easeInCore = function (gradient) {
  22084. var y = Math.max(0.0, this.bounces);
  22085. var bounciness = this.bounciness;
  22086. if (bounciness <= 1.0) {
  22087. bounciness = 1.001;
  22088. }
  22089. var num9 = Math.pow(bounciness, y);
  22090. var num5 = 1.0 - bounciness;
  22091. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22092. var num15 = gradient * num4;
  22093. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22094. var num3 = Math.floor(num65);
  22095. var num13 = num3 + 1.0;
  22096. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22097. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22098. var num7 = (num8 + num12) * 0.5;
  22099. var num6 = gradient - num7;
  22100. var num2 = num7 - num8;
  22101. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22102. };
  22103. return BounceEase;
  22104. })(EasingFunction);
  22105. BABYLON.BounceEase = BounceEase;
  22106. var CubicEase = (function (_super) {
  22107. __extends(CubicEase, _super);
  22108. function CubicEase() {
  22109. _super.apply(this, arguments);
  22110. }
  22111. CubicEase.prototype.easeInCore = function (gradient) {
  22112. return (gradient * gradient * gradient);
  22113. };
  22114. return CubicEase;
  22115. })(EasingFunction);
  22116. BABYLON.CubicEase = CubicEase;
  22117. var ElasticEase = (function (_super) {
  22118. __extends(ElasticEase, _super);
  22119. function ElasticEase(oscillations, springiness) {
  22120. if (oscillations === void 0) { oscillations = 3; }
  22121. if (springiness === void 0) { springiness = 3; }
  22122. _super.call(this);
  22123. this.oscillations = oscillations;
  22124. this.springiness = springiness;
  22125. }
  22126. ElasticEase.prototype.easeInCore = function (gradient) {
  22127. var num2;
  22128. var num3 = Math.max(0.0, this.oscillations);
  22129. var num = Math.max(0.0, this.springiness);
  22130. if (num == 0) {
  22131. num2 = gradient;
  22132. }
  22133. else {
  22134. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22135. }
  22136. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22137. };
  22138. return ElasticEase;
  22139. })(EasingFunction);
  22140. BABYLON.ElasticEase = ElasticEase;
  22141. var ExponentialEase = (function (_super) {
  22142. __extends(ExponentialEase, _super);
  22143. function ExponentialEase(exponent) {
  22144. if (exponent === void 0) { exponent = 2; }
  22145. _super.call(this);
  22146. this.exponent = exponent;
  22147. }
  22148. ExponentialEase.prototype.easeInCore = function (gradient) {
  22149. if (this.exponent <= 0) {
  22150. return gradient;
  22151. }
  22152. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22153. };
  22154. return ExponentialEase;
  22155. })(EasingFunction);
  22156. BABYLON.ExponentialEase = ExponentialEase;
  22157. var PowerEase = (function (_super) {
  22158. __extends(PowerEase, _super);
  22159. function PowerEase(power) {
  22160. if (power === void 0) { power = 2; }
  22161. _super.call(this);
  22162. this.power = power;
  22163. }
  22164. PowerEase.prototype.easeInCore = function (gradient) {
  22165. var y = Math.max(0.0, this.power);
  22166. return Math.pow(gradient, y);
  22167. };
  22168. return PowerEase;
  22169. })(EasingFunction);
  22170. BABYLON.PowerEase = PowerEase;
  22171. var QuadraticEase = (function (_super) {
  22172. __extends(QuadraticEase, _super);
  22173. function QuadraticEase() {
  22174. _super.apply(this, arguments);
  22175. }
  22176. QuadraticEase.prototype.easeInCore = function (gradient) {
  22177. return (gradient * gradient);
  22178. };
  22179. return QuadraticEase;
  22180. })(EasingFunction);
  22181. BABYLON.QuadraticEase = QuadraticEase;
  22182. var QuarticEase = (function (_super) {
  22183. __extends(QuarticEase, _super);
  22184. function QuarticEase() {
  22185. _super.apply(this, arguments);
  22186. }
  22187. QuarticEase.prototype.easeInCore = function (gradient) {
  22188. return (gradient * gradient * gradient * gradient);
  22189. };
  22190. return QuarticEase;
  22191. })(EasingFunction);
  22192. BABYLON.QuarticEase = QuarticEase;
  22193. var QuinticEase = (function (_super) {
  22194. __extends(QuinticEase, _super);
  22195. function QuinticEase() {
  22196. _super.apply(this, arguments);
  22197. }
  22198. QuinticEase.prototype.easeInCore = function (gradient) {
  22199. return (gradient * gradient * gradient * gradient * gradient);
  22200. };
  22201. return QuinticEase;
  22202. })(EasingFunction);
  22203. BABYLON.QuinticEase = QuinticEase;
  22204. var SineEase = (function (_super) {
  22205. __extends(SineEase, _super);
  22206. function SineEase() {
  22207. _super.apply(this, arguments);
  22208. }
  22209. SineEase.prototype.easeInCore = function (gradient) {
  22210. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22211. };
  22212. return SineEase;
  22213. })(EasingFunction);
  22214. BABYLON.SineEase = SineEase;
  22215. var BezierCurveEase = (function (_super) {
  22216. __extends(BezierCurveEase, _super);
  22217. function BezierCurveEase(x1, y1, x2, y2) {
  22218. if (x1 === void 0) { x1 = 0; }
  22219. if (y1 === void 0) { y1 = 0; }
  22220. if (x2 === void 0) { x2 = 1; }
  22221. if (y2 === void 0) { y2 = 1; }
  22222. _super.call(this);
  22223. this.x1 = x1;
  22224. this.y1 = y1;
  22225. this.x2 = x2;
  22226. this.y2 = y2;
  22227. }
  22228. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22229. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22230. };
  22231. return BezierCurveEase;
  22232. })(EasingFunction);
  22233. BABYLON.BezierCurveEase = BezierCurveEase;
  22234. })(BABYLON || (BABYLON = {}));
  22235. var BABYLON;
  22236. (function (BABYLON) {
  22237. var Bone = (function (_super) {
  22238. __extends(Bone, _super);
  22239. function Bone(name, skeleton, parentBone, matrix) {
  22240. _super.call(this, name, skeleton.getScene());
  22241. this.name = name;
  22242. this.children = new Array();
  22243. this.animations = new Array();
  22244. this._worldTransform = new BABYLON.Matrix();
  22245. this._absoluteTransform = new BABYLON.Matrix();
  22246. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22247. this._skeleton = skeleton;
  22248. this._matrix = matrix;
  22249. this._baseMatrix = matrix;
  22250. skeleton.bones.push(this);
  22251. if (parentBone) {
  22252. this._parent = parentBone;
  22253. parentBone.children.push(this);
  22254. }
  22255. else {
  22256. this._parent = null;
  22257. }
  22258. this._updateDifferenceMatrix();
  22259. }
  22260. // Members
  22261. Bone.prototype.getParent = function () {
  22262. return this._parent;
  22263. };
  22264. Bone.prototype.getLocalMatrix = function () {
  22265. return this._matrix;
  22266. };
  22267. Bone.prototype.getBaseMatrix = function () {
  22268. return this._baseMatrix;
  22269. };
  22270. Bone.prototype.getWorldMatrix = function () {
  22271. return this._worldTransform;
  22272. };
  22273. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22274. return this._invertedAbsoluteTransform;
  22275. };
  22276. Bone.prototype.getAbsoluteMatrix = function () {
  22277. var matrix = this._matrix.clone();
  22278. var parent = this._parent;
  22279. while (parent) {
  22280. matrix = matrix.multiply(parent.getLocalMatrix());
  22281. parent = parent.getParent();
  22282. }
  22283. return matrix;
  22284. };
  22285. // Methods
  22286. Bone.prototype.updateMatrix = function (matrix) {
  22287. this._matrix = matrix;
  22288. this._skeleton._markAsDirty();
  22289. this._updateDifferenceMatrix();
  22290. };
  22291. Bone.prototype._updateDifferenceMatrix = function () {
  22292. if (this._parent) {
  22293. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22294. }
  22295. else {
  22296. this._absoluteTransform.copyFrom(this._matrix);
  22297. }
  22298. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22299. for (var index = 0; index < this.children.length; index++) {
  22300. this.children[index]._updateDifferenceMatrix();
  22301. }
  22302. };
  22303. Bone.prototype.markAsDirty = function () {
  22304. this._currentRenderId++;
  22305. this._skeleton._markAsDirty();
  22306. };
  22307. return Bone;
  22308. })(BABYLON.Node);
  22309. BABYLON.Bone = Bone;
  22310. })(BABYLON || (BABYLON = {}));
  22311. var BABYLON;
  22312. (function (BABYLON) {
  22313. var Skeleton = (function () {
  22314. function Skeleton(name, id, scene) {
  22315. this.name = name;
  22316. this.id = id;
  22317. this.bones = new Array();
  22318. this._isDirty = true;
  22319. this._identity = BABYLON.Matrix.Identity();
  22320. this._ranges = new Array();
  22321. this.bones = [];
  22322. this._scene = scene;
  22323. scene.skeletons.push(this);
  22324. this.prepare();
  22325. //make sure it will recalculate the matrix next time prepare is called.
  22326. this._isDirty = true;
  22327. }
  22328. // Members
  22329. Skeleton.prototype.getTransformMatrices = function () {
  22330. return this._transformMatrices;
  22331. };
  22332. Skeleton.prototype.getScene = function () {
  22333. return this._scene;
  22334. };
  22335. // Methods
  22336. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22337. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22338. };
  22339. Skeleton.prototype.deleteAnimationRange = function (name) {
  22340. for (var index = 0; index < this._ranges.length; index++) {
  22341. if (this._ranges[index].name === name) {
  22342. this._ranges.splice(index, 1);
  22343. return;
  22344. }
  22345. }
  22346. };
  22347. Skeleton.prototype.getAnimationRange = function (name) {
  22348. for (var index = 0; index < this._ranges.length; index++) {
  22349. if (this._ranges[index].name === name) {
  22350. return this._ranges[index];
  22351. }
  22352. }
  22353. return null;
  22354. };
  22355. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22356. var range = this.getAnimationRange(name);
  22357. if (!range) {
  22358. return null;
  22359. }
  22360. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22361. };
  22362. Skeleton.prototype._markAsDirty = function () {
  22363. this._isDirty = true;
  22364. };
  22365. Skeleton.prototype.prepare = function () {
  22366. if (!this._isDirty) {
  22367. return;
  22368. }
  22369. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22370. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22371. }
  22372. for (var index = 0; index < this.bones.length; index++) {
  22373. var bone = this.bones[index];
  22374. var parentBone = bone.getParent();
  22375. if (parentBone) {
  22376. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22377. }
  22378. else {
  22379. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22380. }
  22381. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22382. }
  22383. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22384. this._isDirty = false;
  22385. this._scene._activeBones += this.bones.length;
  22386. };
  22387. Skeleton.prototype.getAnimatables = function () {
  22388. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22389. this._animatables = [];
  22390. for (var index = 0; index < this.bones.length; index++) {
  22391. this._animatables.push(this.bones[index]);
  22392. }
  22393. }
  22394. return this._animatables;
  22395. };
  22396. Skeleton.prototype.clone = function (name, id) {
  22397. var result = new Skeleton(name, id || name, this._scene);
  22398. for (var index = 0; index < this.bones.length; index++) {
  22399. var source = this.bones[index];
  22400. var parentBone = null;
  22401. if (source.getParent()) {
  22402. var parentIndex = this.bones.indexOf(source.getParent());
  22403. parentBone = result.bones[parentIndex];
  22404. }
  22405. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone());
  22406. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22407. }
  22408. return result;
  22409. };
  22410. Skeleton.prototype.dispose = function () {
  22411. // Animations
  22412. this.getScene().stopAnimation(this);
  22413. // Remove from scene
  22414. this.getScene().removeSkeleton(this);
  22415. };
  22416. Skeleton.prototype.serialize = function () {
  22417. var serializationObject = {};
  22418. serializationObject.name = this.name;
  22419. serializationObject.id = this.id;
  22420. serializationObject.bones = [];
  22421. for (var index = 0; index < this.bones.length; index++) {
  22422. var bone = this.bones[index];
  22423. var serializedBone = {
  22424. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22425. name: bone.name,
  22426. matrix: bone.getLocalMatrix().toArray()
  22427. };
  22428. serializationObject.bones.push(serializedBone);
  22429. if (bone.length) {
  22430. serializedBone.length = bone.length;
  22431. }
  22432. if (bone.animations && bone.animations.length > 0) {
  22433. serializedBone.animation = bone.animations[0].serialize();
  22434. }
  22435. }
  22436. return serializationObject;
  22437. };
  22438. Skeleton.Parse = function (parsedSkeleton, scene) {
  22439. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22440. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22441. var parsedBone = parsedSkeleton.bones[index];
  22442. var parentBone = null;
  22443. if (parsedBone.parentBoneIndex > -1) {
  22444. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22445. }
  22446. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22447. if (parsedBone.length) {
  22448. bone.length = parsedBone.length;
  22449. }
  22450. if (parsedBone.animation) {
  22451. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22452. }
  22453. }
  22454. return skeleton;
  22455. };
  22456. return Skeleton;
  22457. })();
  22458. BABYLON.Skeleton = Skeleton;
  22459. })(BABYLON || (BABYLON = {}));
  22460. var BABYLON;
  22461. (function (BABYLON) {
  22462. var PostProcess = (function () {
  22463. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22465. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22466. this.name = name;
  22467. this.width = -1;
  22468. this.height = -1;
  22469. this._reusable = false;
  22470. this._textures = new BABYLON.SmartArray(2);
  22471. this._currentRenderTextureInd = 0;
  22472. if (camera != null) {
  22473. this._camera = camera;
  22474. this._scene = camera.getScene();
  22475. camera.attachPostProcess(this);
  22476. this._engine = this._scene.getEngine();
  22477. }
  22478. else {
  22479. this._engine = engine;
  22480. }
  22481. this._renderRatio = ratio;
  22482. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22483. this._reusable = reusable || false;
  22484. this._textureType = textureType;
  22485. this._samplers = samplers || [];
  22486. this._samplers.push("textureSampler");
  22487. this._fragmentUrl = fragmentUrl;
  22488. this._parameters = parameters || [];
  22489. this.updateEffect(defines);
  22490. }
  22491. PostProcess.prototype.updateEffect = function (defines) {
  22492. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22493. };
  22494. PostProcess.prototype.isReusable = function () {
  22495. return this._reusable;
  22496. };
  22497. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22498. camera = camera || this._camera;
  22499. var scene = camera.getScene();
  22500. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22501. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22502. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22503. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22504. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22505. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22506. if (this._textures.length > 0) {
  22507. for (var i = 0; i < this._textures.length; i++) {
  22508. this._engine._releaseTexture(this._textures.data[i]);
  22509. }
  22510. this._textures.reset();
  22511. }
  22512. this.width = desiredWidth;
  22513. this.height = desiredHeight;
  22514. 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 }));
  22515. if (this._reusable) {
  22516. 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 }));
  22517. }
  22518. if (this.onSizeChanged) {
  22519. this.onSizeChanged();
  22520. }
  22521. }
  22522. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22523. if (this.onActivate) {
  22524. this.onActivate(camera);
  22525. }
  22526. // Clear
  22527. if (this.clearColor) {
  22528. this._engine.clear(this.clearColor, true, true);
  22529. }
  22530. else {
  22531. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22532. }
  22533. if (this._reusable) {
  22534. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22535. }
  22536. };
  22537. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22538. get: function () {
  22539. return this._effect.isSupported;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. PostProcess.prototype.apply = function () {
  22545. // Check
  22546. if (!this._effect.isReady())
  22547. return null;
  22548. // States
  22549. this._engine.enableEffect(this._effect);
  22550. this._engine.setState(false);
  22551. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22552. this._engine.setDepthBuffer(false);
  22553. this._engine.setDepthWrite(false);
  22554. // Texture
  22555. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22556. // Parameters
  22557. if (this.onApply) {
  22558. this.onApply(this._effect);
  22559. }
  22560. return this._effect;
  22561. };
  22562. PostProcess.prototype.dispose = function (camera) {
  22563. camera = camera || this._camera;
  22564. if (this._textures.length > 0) {
  22565. for (var i = 0; i < this._textures.length; i++) {
  22566. this._engine._releaseTexture(this._textures.data[i]);
  22567. }
  22568. this._textures.reset();
  22569. }
  22570. if (!camera) {
  22571. return;
  22572. }
  22573. camera.detachPostProcess(this);
  22574. var index = camera._postProcesses.indexOf(this);
  22575. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22576. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22577. }
  22578. };
  22579. return PostProcess;
  22580. })();
  22581. BABYLON.PostProcess = PostProcess;
  22582. })(BABYLON || (BABYLON = {}));
  22583. var BABYLON;
  22584. (function (BABYLON) {
  22585. var PostProcessManager = (function () {
  22586. function PostProcessManager(scene) {
  22587. this._vertexDeclaration = [2];
  22588. this._vertexStrideSize = 2 * 4;
  22589. this._scene = scene;
  22590. }
  22591. PostProcessManager.prototype._prepareBuffers = function () {
  22592. if (this._vertexBuffer) {
  22593. return;
  22594. }
  22595. // VBO
  22596. var vertices = [];
  22597. vertices.push(1, 1);
  22598. vertices.push(-1, 1);
  22599. vertices.push(-1, -1);
  22600. vertices.push(1, -1);
  22601. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22602. // Indices
  22603. var indices = [];
  22604. indices.push(0);
  22605. indices.push(1);
  22606. indices.push(2);
  22607. indices.push(0);
  22608. indices.push(2);
  22609. indices.push(3);
  22610. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22611. };
  22612. // Methods
  22613. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22614. var postProcesses = this._scene.activeCamera._postProcesses;
  22615. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22616. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22617. return false;
  22618. }
  22619. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22620. return true;
  22621. };
  22622. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22623. var engine = this._scene.getEngine();
  22624. for (var index = 0; index < postProcesses.length; index++) {
  22625. if (index < postProcesses.length - 1) {
  22626. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22627. }
  22628. else {
  22629. if (targetTexture) {
  22630. engine.bindFramebuffer(targetTexture);
  22631. }
  22632. else {
  22633. engine.restoreDefaultFramebuffer();
  22634. }
  22635. }
  22636. var pp = postProcesses[index];
  22637. var effect = pp.apply();
  22638. if (effect) {
  22639. if (pp.onBeforeRender) {
  22640. pp.onBeforeRender(effect);
  22641. }
  22642. // VBOs
  22643. this._prepareBuffers();
  22644. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22645. // Draw order
  22646. engine.draw(true, 0, 6);
  22647. if (pp.onAfterRender) {
  22648. pp.onAfterRender(effect);
  22649. }
  22650. }
  22651. }
  22652. // Restore depth buffer
  22653. engine.setDepthBuffer(true);
  22654. engine.setDepthWrite(true);
  22655. };
  22656. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22657. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22658. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22659. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22660. return;
  22661. }
  22662. var engine = this._scene.getEngine();
  22663. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22664. if (index < postProcessesTakenIndices.length - 1) {
  22665. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  22666. }
  22667. else {
  22668. if (targetTexture) {
  22669. engine.bindFramebuffer(targetTexture, faceIndex);
  22670. }
  22671. else {
  22672. engine.restoreDefaultFramebuffer();
  22673. }
  22674. }
  22675. if (doNotPresent) {
  22676. break;
  22677. }
  22678. var pp = postProcesses[postProcessesTakenIndices[index]];
  22679. var effect = pp.apply();
  22680. if (effect) {
  22681. if (pp.onBeforeRender) {
  22682. pp.onBeforeRender(effect);
  22683. }
  22684. // VBOs
  22685. this._prepareBuffers();
  22686. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22687. // Draw order
  22688. engine.draw(true, 0, 6);
  22689. if (pp.onAfterRender) {
  22690. pp.onAfterRender(effect);
  22691. }
  22692. }
  22693. }
  22694. // Restore depth buffer
  22695. engine.setDepthBuffer(true);
  22696. engine.setDepthWrite(true);
  22697. };
  22698. PostProcessManager.prototype.dispose = function () {
  22699. if (this._vertexBuffer) {
  22700. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22701. this._vertexBuffer = null;
  22702. }
  22703. if (this._indexBuffer) {
  22704. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22705. this._indexBuffer = null;
  22706. }
  22707. };
  22708. return PostProcessManager;
  22709. })();
  22710. BABYLON.PostProcessManager = PostProcessManager;
  22711. })(BABYLON || (BABYLON = {}));
  22712. var BABYLON;
  22713. (function (BABYLON) {
  22714. var PassPostProcess = (function (_super) {
  22715. __extends(PassPostProcess, _super);
  22716. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22717. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22718. }
  22719. return PassPostProcess;
  22720. })(BABYLON.PostProcess);
  22721. BABYLON.PassPostProcess = PassPostProcess;
  22722. })(BABYLON || (BABYLON = {}));
  22723. var BABYLON;
  22724. (function (BABYLON) {
  22725. var PhysicsEngine = (function () {
  22726. function PhysicsEngine(plugin) {
  22727. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22728. }
  22729. PhysicsEngine.prototype._initialize = function (gravity) {
  22730. this._currentPlugin.initialize();
  22731. this._setGravity(gravity);
  22732. };
  22733. PhysicsEngine.prototype._runOneStep = function (delta) {
  22734. if (delta > 0.1) {
  22735. delta = 0.1;
  22736. }
  22737. else if (delta <= 0) {
  22738. delta = 1.0 / 60.0;
  22739. }
  22740. this._currentPlugin.runOneStep(delta);
  22741. };
  22742. PhysicsEngine.prototype._setGravity = function (gravity) {
  22743. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22744. this._currentPlugin.setGravity(this.gravity);
  22745. };
  22746. PhysicsEngine.prototype._getGravity = function () {
  22747. return this._currentPlugin.getGravity();
  22748. };
  22749. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22750. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22751. };
  22752. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22753. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22754. };
  22755. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22756. this._currentPlugin.unregisterMesh(mesh);
  22757. };
  22758. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22759. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22760. };
  22761. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22762. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22763. };
  22764. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22765. this._currentPlugin.updateBodyPosition(mesh);
  22766. };
  22767. PhysicsEngine.prototype.dispose = function () {
  22768. this._currentPlugin.dispose();
  22769. };
  22770. PhysicsEngine.prototype.isSupported = function () {
  22771. return this._currentPlugin.isSupported();
  22772. };
  22773. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22774. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22775. };
  22776. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22777. return this._currentPlugin.name;
  22778. };
  22779. // Statics
  22780. PhysicsEngine.NoImpostor = 0;
  22781. PhysicsEngine.SphereImpostor = 1;
  22782. PhysicsEngine.BoxImpostor = 2;
  22783. PhysicsEngine.PlaneImpostor = 3;
  22784. PhysicsEngine.MeshImpostor = 4;
  22785. PhysicsEngine.CapsuleImpostor = 5;
  22786. PhysicsEngine.ConeImpostor = 6;
  22787. PhysicsEngine.CylinderImpostor = 7;
  22788. PhysicsEngine.ConvexHullImpostor = 8;
  22789. PhysicsEngine.HeightmapImpostor = 9;
  22790. PhysicsEngine.Epsilon = 0.001;
  22791. return PhysicsEngine;
  22792. })();
  22793. BABYLON.PhysicsEngine = PhysicsEngine;
  22794. })(BABYLON || (BABYLON = {}));
  22795. var BABYLON;
  22796. (function (BABYLON) {
  22797. var VertexData = (function () {
  22798. function VertexData() {
  22799. }
  22800. VertexData.prototype.set = function (data, kind) {
  22801. switch (kind) {
  22802. case BABYLON.VertexBuffer.PositionKind:
  22803. this.positions = data;
  22804. break;
  22805. case BABYLON.VertexBuffer.NormalKind:
  22806. this.normals = data;
  22807. break;
  22808. case BABYLON.VertexBuffer.UVKind:
  22809. this.uvs = data;
  22810. break;
  22811. case BABYLON.VertexBuffer.UV2Kind:
  22812. this.uvs2 = data;
  22813. break;
  22814. case BABYLON.VertexBuffer.UV3Kind:
  22815. this.uvs3 = data;
  22816. break;
  22817. case BABYLON.VertexBuffer.UV4Kind:
  22818. this.uvs4 = data;
  22819. break;
  22820. case BABYLON.VertexBuffer.UV5Kind:
  22821. this.uvs5 = data;
  22822. break;
  22823. case BABYLON.VertexBuffer.UV6Kind:
  22824. this.uvs6 = data;
  22825. break;
  22826. case BABYLON.VertexBuffer.ColorKind:
  22827. this.colors = data;
  22828. break;
  22829. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22830. this.matricesIndices = data;
  22831. break;
  22832. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22833. this.matricesWeights = data;
  22834. break;
  22835. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22836. this.matricesIndicesExtra = data;
  22837. break;
  22838. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22839. this.matricesWeightsExtra = data;
  22840. break;
  22841. }
  22842. };
  22843. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22844. this._applyTo(mesh, updatable);
  22845. };
  22846. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22847. this._applyTo(geometry, updatable);
  22848. };
  22849. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22850. this._update(mesh);
  22851. };
  22852. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22853. this._update(geometry);
  22854. };
  22855. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22856. if (this.positions) {
  22857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22858. }
  22859. if (this.normals) {
  22860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22861. }
  22862. if (this.uvs) {
  22863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22864. }
  22865. if (this.uvs2) {
  22866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22867. }
  22868. if (this.uvs3) {
  22869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22870. }
  22871. if (this.uvs4) {
  22872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22873. }
  22874. if (this.uvs5) {
  22875. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22876. }
  22877. if (this.uvs6) {
  22878. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22879. }
  22880. if (this.colors) {
  22881. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22882. }
  22883. if (this.matricesIndices) {
  22884. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22885. }
  22886. if (this.matricesWeights) {
  22887. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22888. }
  22889. if (this.matricesIndicesExtra) {
  22890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22891. }
  22892. if (this.matricesWeightsExtra) {
  22893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22894. }
  22895. if (this.indices) {
  22896. meshOrGeometry.setIndices(this.indices);
  22897. }
  22898. };
  22899. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22900. if (this.positions) {
  22901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22902. }
  22903. if (this.normals) {
  22904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22905. }
  22906. if (this.uvs) {
  22907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22908. }
  22909. if (this.uvs2) {
  22910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22911. }
  22912. if (this.uvs3) {
  22913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22914. }
  22915. if (this.uvs4) {
  22916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22917. }
  22918. if (this.uvs5) {
  22919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22920. }
  22921. if (this.uvs6) {
  22922. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22923. }
  22924. if (this.colors) {
  22925. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22926. }
  22927. if (this.matricesIndices) {
  22928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22929. }
  22930. if (this.matricesWeights) {
  22931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22932. }
  22933. if (this.matricesIndicesExtra) {
  22934. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22935. }
  22936. if (this.matricesWeightsExtra) {
  22937. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22938. }
  22939. if (this.indices) {
  22940. meshOrGeometry.setIndices(this.indices);
  22941. }
  22942. };
  22943. VertexData.prototype.transform = function (matrix) {
  22944. var transformed = BABYLON.Vector3.Zero();
  22945. var index;
  22946. if (this.positions) {
  22947. var position = BABYLON.Vector3.Zero();
  22948. for (index = 0; index < this.positions.length; index += 3) {
  22949. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22950. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22951. this.positions[index] = transformed.x;
  22952. this.positions[index + 1] = transformed.y;
  22953. this.positions[index + 2] = transformed.z;
  22954. }
  22955. }
  22956. if (this.normals) {
  22957. var normal = BABYLON.Vector3.Zero();
  22958. for (index = 0; index < this.normals.length; index += 3) {
  22959. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22960. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22961. this.normals[index] = transformed.x;
  22962. this.normals[index + 1] = transformed.y;
  22963. this.normals[index + 2] = transformed.z;
  22964. }
  22965. }
  22966. };
  22967. VertexData.prototype.merge = function (other) {
  22968. if (other.indices) {
  22969. if (!this.indices) {
  22970. this.indices = [];
  22971. }
  22972. var offset = this.positions ? this.positions.length / 3 : 0;
  22973. for (var index = 0; index < other.indices.length; index++) {
  22974. //TODO check type - if Int32Array!
  22975. this.indices.push(other.indices[index] + offset);
  22976. }
  22977. }
  22978. this.positions = this._mergeElement(this.positions, other.positions);
  22979. this.normals = this._mergeElement(this.normals, other.normals);
  22980. this.uvs = this._mergeElement(this.uvs, other.uvs);
  22981. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  22982. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  22983. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  22984. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  22985. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  22986. this.colors = this._mergeElement(this.colors, other.colors);
  22987. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  22988. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  22989. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  22990. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  22991. };
  22992. VertexData.prototype._mergeElement = function (source, other) {
  22993. if (!other)
  22994. return source;
  22995. if (!source)
  22996. return other;
  22997. var len = other.length + source.length;
  22998. var isSrcTypedArray = source instanceof Float32Array;
  22999. var isOthTypedArray = other instanceof Float32Array;
  23000. // use non-loop method when the source is Float32Array
  23001. if (isSrcTypedArray) {
  23002. var ret32 = new Float32Array(len);
  23003. ret32.set(source);
  23004. ret32.set(other, source.length);
  23005. return ret32;
  23006. }
  23007. else if (!isOthTypedArray) {
  23008. return source.concat(other);
  23009. }
  23010. else {
  23011. var ret = source.slice(0); // copy source to a separate array
  23012. for (var i = 0, len = other.length; i < len; i++) {
  23013. ret.push(other[i]);
  23014. }
  23015. return ret;
  23016. }
  23017. };
  23018. VertexData.prototype.serialize = function () {
  23019. var serializationObject = this.serialize();
  23020. if (this.positions) {
  23021. serializationObject.positions = this.positions;
  23022. }
  23023. if (this.normals) {
  23024. serializationObject.normals = this.normals;
  23025. }
  23026. if (this.uvs) {
  23027. serializationObject.uvs = this.uvs;
  23028. }
  23029. if (this.uvs2) {
  23030. serializationObject.uvs2 = this.uvs2;
  23031. }
  23032. if (this.uvs3) {
  23033. serializationObject.uvs3 = this.uvs3;
  23034. }
  23035. if (this.uvs4) {
  23036. serializationObject.uvs4 = this.uvs4;
  23037. }
  23038. if (this.uvs5) {
  23039. serializationObject.uvs5 = this.uvs5;
  23040. }
  23041. if (this.uvs6) {
  23042. serializationObject.uvs6 = this.uvs6;
  23043. }
  23044. if (this.colors) {
  23045. serializationObject.colors = this.colors;
  23046. }
  23047. if (this.matricesIndices) {
  23048. serializationObject.matricesIndices = this.matricesIndices;
  23049. serializationObject.matricesIndices._isExpanded = true;
  23050. }
  23051. if (this.matricesWeights) {
  23052. serializationObject.matricesWeights = this.matricesWeights;
  23053. }
  23054. if (this.matricesIndicesExtra) {
  23055. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23056. serializationObject.matricesIndicesExtra._isExpanded = true;
  23057. }
  23058. if (this.matricesWeightsExtra) {
  23059. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23060. }
  23061. serializationObject.indices = this.indices;
  23062. return serializationObject;
  23063. };
  23064. // Statics
  23065. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23066. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23067. };
  23068. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23069. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23070. };
  23071. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23072. var result = new VertexData();
  23073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23074. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23075. }
  23076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23077. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23078. }
  23079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23080. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23081. }
  23082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23083. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23084. }
  23085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23086. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23087. }
  23088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23089. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23090. }
  23091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23092. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23093. }
  23094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23095. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23096. }
  23097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23098. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23099. }
  23100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23101. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23102. }
  23103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23104. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23105. }
  23106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23107. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23108. }
  23109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23110. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23111. }
  23112. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23113. return result;
  23114. };
  23115. VertexData.CreateRibbon = function (options) {
  23116. var pathArray = options.pathArray;
  23117. var closeArray = options.closeArray || false;
  23118. var closePath = options.closePath || false;
  23119. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23120. var offset = options.offset || defaultOffset;
  23121. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23123. var positions = [];
  23124. var indices = [];
  23125. var normals = [];
  23126. var uvs = [];
  23127. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23128. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23129. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23130. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23131. var minlg; // minimal length among all paths from pathArray
  23132. var lg = []; // array of path lengths : nb of vertex per path
  23133. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23134. var p; // path iterator
  23135. var i; // point iterator
  23136. var j; // point iterator
  23137. // if single path in pathArray
  23138. if (pathArray.length < 2) {
  23139. var ar1 = [];
  23140. var ar2 = [];
  23141. for (i = 0; i < pathArray[0].length - offset; i++) {
  23142. ar1.push(pathArray[0][i]);
  23143. ar2.push(pathArray[0][i + offset]);
  23144. }
  23145. pathArray = [ar1, ar2];
  23146. }
  23147. // positions and horizontal distances (u)
  23148. var idc = 0;
  23149. var closePathCorr = (closePath) ? 1 : 0;
  23150. var path;
  23151. var l;
  23152. minlg = pathArray[0].length;
  23153. var vectlg;
  23154. var dist;
  23155. for (p = 0; p < pathArray.length; p++) {
  23156. uTotalDistance[p] = 0;
  23157. us[p] = [0];
  23158. path = pathArray[p];
  23159. l = path.length;
  23160. minlg = (minlg < l) ? minlg : l;
  23161. j = 0;
  23162. while (j < l) {
  23163. positions.push(path[j].x, path[j].y, path[j].z);
  23164. if (j > 0) {
  23165. vectlg = path[j].subtract(path[j - 1]).length();
  23166. dist = vectlg + uTotalDistance[p];
  23167. us[p].push(dist);
  23168. uTotalDistance[p] = dist;
  23169. }
  23170. j++;
  23171. }
  23172. if (closePath) {
  23173. j--;
  23174. positions.push(path[0].x, path[0].y, path[0].z);
  23175. vectlg = path[j].subtract(path[0]).length();
  23176. dist = vectlg + uTotalDistance[p];
  23177. us[p].push(dist);
  23178. uTotalDistance[p] = dist;
  23179. }
  23180. lg[p] = l + closePathCorr;
  23181. idx[p] = idc;
  23182. idc += (l + closePathCorr);
  23183. }
  23184. // vertical distances (v)
  23185. var path1;
  23186. var path2;
  23187. var vertex1;
  23188. var vertex2;
  23189. for (i = 0; i < minlg + closePathCorr; i++) {
  23190. vTotalDistance[i] = 0;
  23191. vs[i] = [0];
  23192. for (p = 0; p < pathArray.length - 1; p++) {
  23193. path1 = pathArray[p];
  23194. path2 = pathArray[p + 1];
  23195. if (i === minlg) {
  23196. vertex1 = path1[0];
  23197. vertex2 = path2[0];
  23198. }
  23199. else {
  23200. vertex1 = path1[i];
  23201. vertex2 = path2[i];
  23202. }
  23203. vectlg = vertex2.subtract(vertex1).length();
  23204. dist = vectlg + vTotalDistance[i];
  23205. vs[i].push(dist);
  23206. vTotalDistance[i] = dist;
  23207. }
  23208. if (closeArray) {
  23209. path1 = pathArray[p];
  23210. path2 = pathArray[0];
  23211. if (i === minlg) {
  23212. vertex2 = path2[0];
  23213. }
  23214. vectlg = vertex2.subtract(vertex1).length();
  23215. dist = vectlg + vTotalDistance[i];
  23216. vTotalDistance[i] = dist;
  23217. }
  23218. }
  23219. // uvs
  23220. var u;
  23221. var v;
  23222. for (p = 0; p < pathArray.length; p++) {
  23223. for (i = 0; i < minlg + closePathCorr; i++) {
  23224. u = us[p][i] / uTotalDistance[p];
  23225. v = vs[i][p] / vTotalDistance[i];
  23226. uvs.push(u, v);
  23227. }
  23228. }
  23229. // indices
  23230. p = 0; // path index
  23231. var pi = 0; // positions array index
  23232. var l1 = lg[p] - 1; // path1 length
  23233. var l2 = lg[p + 1] - 1; // path2 length
  23234. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23235. var shft = idx[1] - idx[0]; // shift
  23236. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23237. while (pi <= min && p < path1nb) {
  23238. // 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
  23239. indices.push(pi, pi + shft, pi + 1);
  23240. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23241. pi += 1;
  23242. if (pi === min) {
  23243. p++;
  23244. if (p === lg.length - 1) {
  23245. shft = idx[0] - idx[p];
  23246. l1 = lg[p] - 1;
  23247. l2 = lg[0] - 1;
  23248. }
  23249. else {
  23250. shft = idx[p + 1] - idx[p];
  23251. l1 = lg[p] - 1;
  23252. l2 = lg[p + 1] - 1;
  23253. }
  23254. pi = idx[p];
  23255. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23256. }
  23257. }
  23258. // normals
  23259. VertexData.ComputeNormals(positions, indices, normals);
  23260. if (closePath) {
  23261. var indexFirst = 0;
  23262. var indexLast = 0;
  23263. for (p = 0; p < pathArray.length; p++) {
  23264. indexFirst = idx[p] * 3;
  23265. if (p + 1 < pathArray.length) {
  23266. indexLast = (idx[p + 1] - 1) * 3;
  23267. }
  23268. else {
  23269. indexLast = normals.length - 3;
  23270. }
  23271. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23272. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23273. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23274. normals[indexLast] = normals[indexFirst];
  23275. normals[indexLast + 1] = normals[indexFirst + 1];
  23276. normals[indexLast + 2] = normals[indexFirst + 2];
  23277. }
  23278. }
  23279. // sides
  23280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23281. // Result
  23282. var vertexData = new VertexData();
  23283. vertexData.indices = indices;
  23284. vertexData.positions = positions;
  23285. vertexData.normals = normals;
  23286. vertexData.uvs = uvs;
  23287. if (closePath) {
  23288. vertexData._idx = idx;
  23289. }
  23290. return vertexData;
  23291. };
  23292. VertexData.CreateBox = function (options) {
  23293. var normalsSource = [
  23294. new BABYLON.Vector3(0, 0, 1),
  23295. new BABYLON.Vector3(0, 0, -1),
  23296. new BABYLON.Vector3(1, 0, 0),
  23297. new BABYLON.Vector3(-1, 0, 0),
  23298. new BABYLON.Vector3(0, 1, 0),
  23299. new BABYLON.Vector3(0, -1, 0)
  23300. ];
  23301. var indices = [];
  23302. var positions = [];
  23303. var normals = [];
  23304. var uvs = [];
  23305. var width = options.width || options.size || 1;
  23306. var height = options.height || options.size || 1;
  23307. var depth = options.depth || options.size || 1;
  23308. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23309. var faceUV = options.faceUV || new Array(6);
  23310. var faceColors = options.faceColors;
  23311. var colors = [];
  23312. // default face colors and UV if undefined
  23313. for (var f = 0; f < 6; f++) {
  23314. if (faceUV[f] === undefined) {
  23315. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23316. }
  23317. if (faceColors && faceColors[f] === undefined) {
  23318. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23319. }
  23320. }
  23321. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23322. // Create each face in turn.
  23323. for (var index = 0; index < normalsSource.length; index++) {
  23324. var normal = normalsSource[index];
  23325. // Get two vectors perpendicular to the face normal and to each other.
  23326. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23327. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23328. // Six indices (two triangles) per face.
  23329. var verticesLength = positions.length / 3;
  23330. indices.push(verticesLength);
  23331. indices.push(verticesLength + 1);
  23332. indices.push(verticesLength + 2);
  23333. indices.push(verticesLength);
  23334. indices.push(verticesLength + 2);
  23335. indices.push(verticesLength + 3);
  23336. // Four vertices per face.
  23337. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23338. positions.push(vertex.x, vertex.y, vertex.z);
  23339. normals.push(normal.x, normal.y, normal.z);
  23340. uvs.push(faceUV[index].z, faceUV[index].w);
  23341. if (faceColors) {
  23342. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23343. }
  23344. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23345. positions.push(vertex.x, vertex.y, vertex.z);
  23346. normals.push(normal.x, normal.y, normal.z);
  23347. uvs.push(faceUV[index].x, faceUV[index].w);
  23348. if (faceColors) {
  23349. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23350. }
  23351. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23352. positions.push(vertex.x, vertex.y, vertex.z);
  23353. normals.push(normal.x, normal.y, normal.z);
  23354. uvs.push(faceUV[index].x, faceUV[index].y);
  23355. if (faceColors) {
  23356. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23357. }
  23358. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23359. positions.push(vertex.x, vertex.y, vertex.z);
  23360. normals.push(normal.x, normal.y, normal.z);
  23361. uvs.push(faceUV[index].z, faceUV[index].y);
  23362. if (faceColors) {
  23363. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23364. }
  23365. }
  23366. // sides
  23367. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23368. // Result
  23369. var vertexData = new VertexData();
  23370. vertexData.indices = indices;
  23371. vertexData.positions = positions;
  23372. vertexData.normals = normals;
  23373. vertexData.uvs = uvs;
  23374. if (faceColors) {
  23375. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23376. vertexData.colors = totalColors;
  23377. }
  23378. return vertexData;
  23379. };
  23380. VertexData.CreateSphere = function (options) {
  23381. var segments = options.segments || 32;
  23382. var diameterX = options.diameterX || options.diameter || 1;
  23383. var diameterY = options.diameterY || options.diameter || 1;
  23384. var diameterZ = options.diameterZ || options.diameter || 1;
  23385. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23386. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23387. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23388. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23389. var totalZRotationSteps = 2 + segments;
  23390. var totalYRotationSteps = 2 * totalZRotationSteps;
  23391. var indices = [];
  23392. var positions = [];
  23393. var normals = [];
  23394. var uvs = [];
  23395. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23396. var normalizedZ = zRotationStep / totalZRotationSteps;
  23397. var angleZ = normalizedZ * Math.PI * slice;
  23398. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23399. var normalizedY = yRotationStep / totalYRotationSteps;
  23400. var angleY = normalizedY * Math.PI * 2 * arc;
  23401. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23402. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23403. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23404. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23405. var vertex = complete.multiply(radius);
  23406. var normal = complete.divide(radius).normalize();
  23407. positions.push(vertex.x, vertex.y, vertex.z);
  23408. normals.push(normal.x, normal.y, normal.z);
  23409. uvs.push(normalizedY, normalizedZ);
  23410. }
  23411. if (zRotationStep > 0) {
  23412. var verticesCount = positions.length / 3;
  23413. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23414. indices.push((firstIndex));
  23415. indices.push((firstIndex + 1));
  23416. indices.push(firstIndex + totalYRotationSteps + 1);
  23417. indices.push((firstIndex + totalYRotationSteps + 1));
  23418. indices.push((firstIndex + 1));
  23419. indices.push((firstIndex + totalYRotationSteps + 2));
  23420. }
  23421. }
  23422. }
  23423. // Sides
  23424. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23425. // Result
  23426. var vertexData = new VertexData();
  23427. vertexData.indices = indices;
  23428. vertexData.positions = positions;
  23429. vertexData.normals = normals;
  23430. vertexData.uvs = uvs;
  23431. return vertexData;
  23432. };
  23433. // Cylinder and cone
  23434. VertexData.CreateCylinder = function (options) {
  23435. var height = options.height || 2;
  23436. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23437. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23438. var tessellation = options.tessellation || 24;
  23439. var subdivisions = options.subdivisions || 1;
  23440. var hasRings = options.hasRings;
  23441. var enclose = options.enclose;
  23442. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23443. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23444. var faceUV = options.faceUV || new Array(3);
  23445. var faceColors = options.faceColors;
  23446. // default face colors and UV if undefined
  23447. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23448. var ringNb = (hasRings) ? subdivisions : 1;
  23449. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23450. var f;
  23451. for (f = 0; f < surfaceNb; f++) {
  23452. if (faceColors && faceColors[f] === undefined) {
  23453. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23454. }
  23455. }
  23456. for (f = 0; f < surfaceNb; f++) {
  23457. if (faceUV && faceUV[f] === undefined) {
  23458. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23459. }
  23460. }
  23461. var indices = [];
  23462. var positions = [];
  23463. var normals = [];
  23464. var uvs = [];
  23465. var colors = [];
  23466. var angle_step = Math.PI * 2 * arc / tessellation;
  23467. var angle;
  23468. var h;
  23469. var radius;
  23470. var tan = (diameterBottom - diameterTop) / 2 / height;
  23471. var ringVertex = BABYLON.Vector3.Zero();
  23472. var ringNormal = BABYLON.Vector3.Zero();
  23473. var ringFirstVertex = BABYLON.Vector3.Zero();
  23474. var ringFirstNormal = BABYLON.Vector3.Zero();
  23475. var quadNormal = BABYLON.Vector3.Zero();
  23476. var Y = BABYLON.Axis.Y;
  23477. // positions, normals, uvs
  23478. var i;
  23479. var j;
  23480. var r;
  23481. var ringIdx = 1;
  23482. var s = 1; // surface index
  23483. var cs = 0;
  23484. var v = 0;
  23485. for (i = 0; i <= subdivisions; i++) {
  23486. h = i / subdivisions;
  23487. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23488. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23489. for (r = 0; r < ringIdx; r++) {
  23490. if (hasRings) {
  23491. s += r;
  23492. }
  23493. if (enclose) {
  23494. s += 2 * r;
  23495. }
  23496. for (j = 0; j <= tessellation; j++) {
  23497. angle = j * angle_step;
  23498. // position
  23499. ringVertex.x = Math.cos(-angle) * radius;
  23500. ringVertex.y = -height / 2 + h * height;
  23501. ringVertex.z = Math.sin(-angle) * radius;
  23502. // normal
  23503. if (diameterTop === 0 && i === subdivisions) {
  23504. // if no top cap, reuse former normals
  23505. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23506. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23507. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23508. }
  23509. else {
  23510. ringNormal.x = ringVertex.x;
  23511. ringNormal.z = ringVertex.z;
  23512. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23513. ringNormal.normalize();
  23514. }
  23515. // keep first ring vertex values for enclose
  23516. if (j === 0) {
  23517. ringFirstVertex.copyFrom(ringVertex);
  23518. ringFirstNormal.copyFrom(ringNormal);
  23519. }
  23520. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23521. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23522. if (hasRings) {
  23523. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23524. }
  23525. else {
  23526. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23527. }
  23528. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23529. if (faceColors) {
  23530. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23531. }
  23532. }
  23533. // if enclose, add four vertices and their dedicated normals
  23534. if (arc !== 1 && enclose) {
  23535. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23536. positions.push(0, ringVertex.y, 0);
  23537. positions.push(0, ringVertex.y, 0);
  23538. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23539. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23540. quadNormal.normalize();
  23541. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23542. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23543. quadNormal.normalize();
  23544. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23545. if (hasRings) {
  23546. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23547. }
  23548. else {
  23549. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23550. }
  23551. uvs.push(faceUV[s + 1].x, v);
  23552. uvs.push(faceUV[s + 1].z, v);
  23553. if (hasRings) {
  23554. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23555. }
  23556. else {
  23557. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23558. }
  23559. uvs.push(faceUV[s + 2].x, v);
  23560. uvs.push(faceUV[s + 2].z, v);
  23561. if (faceColors) {
  23562. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23563. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23564. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23565. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23566. }
  23567. }
  23568. if (cs !== s) {
  23569. cs = s;
  23570. }
  23571. }
  23572. }
  23573. // indices
  23574. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23575. var s;
  23576. i = 0;
  23577. for (s = 0; s < subdivisions; s++) {
  23578. for (j = 0; j < tessellation; j++) {
  23579. var i0 = i * (e + 1) + j;
  23580. var i1 = (i + 1) * (e + 1) + j;
  23581. var i2 = i * (e + 1) + (j + 1);
  23582. var i3 = (i + 1) * (e + 1) + (j + 1);
  23583. indices.push(i0, i1, i2);
  23584. indices.push(i3, i2, i1);
  23585. }
  23586. if (arc !== 1 && enclose) {
  23587. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23588. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23589. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23590. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23591. }
  23592. i = (hasRings) ? (i + 2) : (i + 1);
  23593. }
  23594. // Caps
  23595. var createCylinderCap = function (isTop) {
  23596. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23597. if (radius === 0) {
  23598. return;
  23599. }
  23600. // Cap positions, normals & uvs
  23601. var angle;
  23602. var circleVector;
  23603. var i;
  23604. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23605. var c;
  23606. if (faceColors) {
  23607. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23608. }
  23609. // cap center
  23610. var vbase = positions.length / 3;
  23611. var offset = isTop ? height / 2 : -height / 2;
  23612. var center = new BABYLON.Vector3(0, offset, 0);
  23613. positions.push(center.x, center.y, center.z);
  23614. normals.push(0, isTop ? 1 : -1, 0);
  23615. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23616. if (faceColors) {
  23617. colors.push(c.r, c.g, c.b, c.a);
  23618. }
  23619. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23620. for (i = 0; i <= tessellation; i++) {
  23621. angle = Math.PI * 2 * i * arc / tessellation;
  23622. var cos = Math.cos(-angle);
  23623. var sin = Math.sin(-angle);
  23624. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23625. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23626. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23627. normals.push(0, isTop ? 1 : -1, 0);
  23628. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23629. if (faceColors) {
  23630. colors.push(c.r, c.g, c.b, c.a);
  23631. }
  23632. }
  23633. // Cap indices
  23634. for (i = 0; i < tessellation; i++) {
  23635. if (!isTop) {
  23636. indices.push(vbase);
  23637. indices.push(vbase + (i + 1));
  23638. indices.push(vbase + (i + 2));
  23639. }
  23640. else {
  23641. indices.push(vbase);
  23642. indices.push(vbase + (i + 2));
  23643. indices.push(vbase + (i + 1));
  23644. }
  23645. }
  23646. };
  23647. // add caps to geometry
  23648. createCylinderCap(false);
  23649. createCylinderCap(true);
  23650. // Sides
  23651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23652. var vertexData = new VertexData();
  23653. vertexData.indices = indices;
  23654. vertexData.positions = positions;
  23655. vertexData.normals = normals;
  23656. vertexData.uvs = uvs;
  23657. if (faceColors) {
  23658. vertexData.colors = colors;
  23659. }
  23660. return vertexData;
  23661. };
  23662. VertexData.CreateTorus = function (options) {
  23663. var indices = [];
  23664. var positions = [];
  23665. var normals = [];
  23666. var uvs = [];
  23667. var diameter = options.diameter || 1;
  23668. var thickness = options.thickness || 0.5;
  23669. var tessellation = options.tessellation || 16;
  23670. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23671. var stride = tessellation + 1;
  23672. for (var i = 0; i <= tessellation; i++) {
  23673. var u = i / tessellation;
  23674. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23675. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23676. for (var j = 0; j <= tessellation; j++) {
  23677. var v = 1 - j / tessellation;
  23678. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23679. var dx = Math.cos(innerAngle);
  23680. var dy = Math.sin(innerAngle);
  23681. // Create a vertex.
  23682. var normal = new BABYLON.Vector3(dx, dy, 0);
  23683. var position = normal.scale(thickness / 2);
  23684. var textureCoordinate = new BABYLON.Vector2(u, v);
  23685. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23686. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23687. positions.push(position.x, position.y, position.z);
  23688. normals.push(normal.x, normal.y, normal.z);
  23689. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23690. // And create indices for two triangles.
  23691. var nextI = (i + 1) % stride;
  23692. var nextJ = (j + 1) % stride;
  23693. indices.push(i * stride + j);
  23694. indices.push(i * stride + nextJ);
  23695. indices.push(nextI * stride + j);
  23696. indices.push(i * stride + nextJ);
  23697. indices.push(nextI * stride + nextJ);
  23698. indices.push(nextI * stride + j);
  23699. }
  23700. }
  23701. // Sides
  23702. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23703. // Result
  23704. var vertexData = new VertexData();
  23705. vertexData.indices = indices;
  23706. vertexData.positions = positions;
  23707. vertexData.normals = normals;
  23708. vertexData.uvs = uvs;
  23709. return vertexData;
  23710. };
  23711. VertexData.CreateLines = function (options) {
  23712. var indices = [];
  23713. var positions = [];
  23714. var points = options.points;
  23715. for (var index = 0; index < points.length; index++) {
  23716. positions.push(points[index].x, points[index].y, points[index].z);
  23717. if (index > 0) {
  23718. indices.push(index - 1);
  23719. indices.push(index);
  23720. }
  23721. }
  23722. // Result
  23723. var vertexData = new VertexData();
  23724. vertexData.indices = indices;
  23725. vertexData.positions = positions;
  23726. return vertexData;
  23727. };
  23728. VertexData.CreateDashedLines = function (options) {
  23729. var dashSize = options.dashSize || 3;
  23730. var gapSize = options.gapSize || 1;
  23731. var dashNb = options.dashNb || 200;
  23732. var points = options.points;
  23733. var positions = new Array();
  23734. var indices = new Array();
  23735. var curvect = BABYLON.Vector3.Zero();
  23736. var lg = 0;
  23737. var nb = 0;
  23738. var shft = 0;
  23739. var dashshft = 0;
  23740. var curshft = 0;
  23741. var idx = 0;
  23742. var i = 0;
  23743. for (i = 0; i < points.length - 1; i++) {
  23744. points[i + 1].subtractToRef(points[i], curvect);
  23745. lg += curvect.length();
  23746. }
  23747. shft = lg / dashNb;
  23748. dashshft = dashSize * shft / (dashSize + gapSize);
  23749. for (i = 0; i < points.length - 1; i++) {
  23750. points[i + 1].subtractToRef(points[i], curvect);
  23751. nb = Math.floor(curvect.length() / shft);
  23752. curvect.normalize();
  23753. for (var j = 0; j < nb; j++) {
  23754. curshft = shft * j;
  23755. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23756. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23757. indices.push(idx, idx + 1);
  23758. idx += 2;
  23759. }
  23760. }
  23761. // Result
  23762. var vertexData = new VertexData();
  23763. vertexData.positions = positions;
  23764. vertexData.indices = indices;
  23765. return vertexData;
  23766. };
  23767. VertexData.CreateGround = function (options) {
  23768. var indices = [];
  23769. var positions = [];
  23770. var normals = [];
  23771. var uvs = [];
  23772. var row, col;
  23773. var width = options.width || 1;
  23774. var height = options.height || 1;
  23775. var subdivisions = options.subdivisions || 1;
  23776. for (row = 0; row <= subdivisions; row++) {
  23777. for (col = 0; col <= subdivisions; col++) {
  23778. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23779. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23780. positions.push(position.x, position.y, position.z);
  23781. normals.push(normal.x, normal.y, normal.z);
  23782. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23783. }
  23784. }
  23785. for (row = 0; row < subdivisions; row++) {
  23786. for (col = 0; col < subdivisions; col++) {
  23787. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23788. indices.push(col + 1 + row * (subdivisions + 1));
  23789. indices.push(col + row * (subdivisions + 1));
  23790. indices.push(col + (row + 1) * (subdivisions + 1));
  23791. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23792. indices.push(col + row * (subdivisions + 1));
  23793. }
  23794. }
  23795. // Result
  23796. var vertexData = new VertexData();
  23797. vertexData.indices = indices;
  23798. vertexData.positions = positions;
  23799. vertexData.normals = normals;
  23800. vertexData.uvs = uvs;
  23801. return vertexData;
  23802. };
  23803. VertexData.CreateTiledGround = function (options) {
  23804. var xmin = options.xmin;
  23805. var zmin = options.zmin;
  23806. var xmax = options.xmax;
  23807. var zmax = options.zmax;
  23808. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23809. var precision = options.precision || { w: 1, h: 1 };
  23810. var indices = [];
  23811. var positions = [];
  23812. var normals = [];
  23813. var uvs = [];
  23814. var row, col, tileRow, tileCol;
  23815. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23816. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23817. precision.w = (precision.w < 1) ? 1 : precision.w;
  23818. precision.h = (precision.h < 1) ? 1 : precision.h;
  23819. var tileSize = {
  23820. 'w': (xmax - xmin) / subdivisions.w,
  23821. 'h': (zmax - zmin) / subdivisions.h
  23822. };
  23823. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23824. // Indices
  23825. var base = positions.length / 3;
  23826. var rowLength = precision.w + 1;
  23827. for (row = 0; row < precision.h; row++) {
  23828. for (col = 0; col < precision.w; col++) {
  23829. var square = [
  23830. base + col + row * rowLength,
  23831. base + (col + 1) + row * rowLength,
  23832. base + (col + 1) + (row + 1) * rowLength,
  23833. base + col + (row + 1) * rowLength
  23834. ];
  23835. indices.push(square[1]);
  23836. indices.push(square[2]);
  23837. indices.push(square[3]);
  23838. indices.push(square[0]);
  23839. indices.push(square[1]);
  23840. indices.push(square[3]);
  23841. }
  23842. }
  23843. // Position, normals and uvs
  23844. var position = BABYLON.Vector3.Zero();
  23845. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23846. for (row = 0; row <= precision.h; row++) {
  23847. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23848. for (col = 0; col <= precision.w; col++) {
  23849. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23850. position.y = 0;
  23851. positions.push(position.x, position.y, position.z);
  23852. normals.push(normal.x, normal.y, normal.z);
  23853. uvs.push(col / precision.w, row / precision.h);
  23854. }
  23855. }
  23856. }
  23857. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23858. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23859. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23860. }
  23861. }
  23862. // Result
  23863. var vertexData = new VertexData();
  23864. vertexData.indices = indices;
  23865. vertexData.positions = positions;
  23866. vertexData.normals = normals;
  23867. vertexData.uvs = uvs;
  23868. return vertexData;
  23869. };
  23870. VertexData.CreateGroundFromHeightMap = function (options) {
  23871. var indices = [];
  23872. var positions = [];
  23873. var normals = [];
  23874. var uvs = [];
  23875. var row, col;
  23876. // Vertices
  23877. for (row = 0; row <= options.subdivisions; row++) {
  23878. for (col = 0; col <= options.subdivisions; col++) {
  23879. 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));
  23880. // Compute height
  23881. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23882. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23883. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23884. var r = options.buffer[pos] / 255.0;
  23885. var g = options.buffer[pos + 1] / 255.0;
  23886. var b = options.buffer[pos + 2] / 255.0;
  23887. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23888. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23889. // Add vertex
  23890. positions.push(position.x, position.y, position.z);
  23891. normals.push(0, 0, 0);
  23892. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23893. }
  23894. }
  23895. // Indices
  23896. for (row = 0; row < options.subdivisions; row++) {
  23897. for (col = 0; col < options.subdivisions; col++) {
  23898. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23899. indices.push(col + 1 + row * (options.subdivisions + 1));
  23900. indices.push(col + row * (options.subdivisions + 1));
  23901. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23902. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23903. indices.push(col + row * (options.subdivisions + 1));
  23904. }
  23905. }
  23906. // Normals
  23907. VertexData.ComputeNormals(positions, indices, normals);
  23908. // Result
  23909. var vertexData = new VertexData();
  23910. vertexData.indices = indices;
  23911. vertexData.positions = positions;
  23912. vertexData.normals = normals;
  23913. vertexData.uvs = uvs;
  23914. return vertexData;
  23915. };
  23916. VertexData.CreatePlane = function (options) {
  23917. var indices = [];
  23918. var positions = [];
  23919. var normals = [];
  23920. var uvs = [];
  23921. var width = options.width || options.size || 1;
  23922. var height = options.height || options.size || 1;
  23923. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23924. // Vertices
  23925. var halfWidth = width / 2.0;
  23926. var halfHeight = height / 2.0;
  23927. positions.push(-halfWidth, -halfHeight, 0);
  23928. normals.push(0, 0, -1.0);
  23929. uvs.push(0.0, 0.0);
  23930. positions.push(halfWidth, -halfHeight, 0);
  23931. normals.push(0, 0, -1.0);
  23932. uvs.push(1.0, 0.0);
  23933. positions.push(halfWidth, halfHeight, 0);
  23934. normals.push(0, 0, -1.0);
  23935. uvs.push(1.0, 1.0);
  23936. positions.push(-halfWidth, halfHeight, 0);
  23937. normals.push(0, 0, -1.0);
  23938. uvs.push(0.0, 1.0);
  23939. // Indices
  23940. indices.push(0);
  23941. indices.push(1);
  23942. indices.push(2);
  23943. indices.push(0);
  23944. indices.push(2);
  23945. indices.push(3);
  23946. // Sides
  23947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23948. // Result
  23949. var vertexData = new VertexData();
  23950. vertexData.indices = indices;
  23951. vertexData.positions = positions;
  23952. vertexData.normals = normals;
  23953. vertexData.uvs = uvs;
  23954. return vertexData;
  23955. };
  23956. VertexData.CreateDisc = function (options) {
  23957. var positions = [];
  23958. var indices = [];
  23959. var normals = [];
  23960. var uvs = [];
  23961. var radius = options.radius || 0.5;
  23962. var tessellation = options.tessellation || 64;
  23963. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23964. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23965. // positions and uvs
  23966. positions.push(0, 0, 0); // disc center first
  23967. uvs.push(0.5, 0.5);
  23968. var theta = Math.PI * 2 * arc;
  23969. var step = theta / tessellation;
  23970. for (var a = 0; a < theta; a += step) {
  23971. var x = Math.cos(a);
  23972. var y = Math.sin(a);
  23973. var u = (x + 1) / 2;
  23974. var v = (1 - y) / 2;
  23975. positions.push(radius * x, radius * y, 0);
  23976. uvs.push(u, v);
  23977. }
  23978. if (arc === 1) {
  23979. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23980. uvs.push(uvs[2], uvs[3]);
  23981. }
  23982. //indices
  23983. var vertexNb = positions.length / 3;
  23984. for (var i = 1; i < vertexNb - 1; i++) {
  23985. indices.push(i + 1, 0, i);
  23986. }
  23987. // result
  23988. VertexData.ComputeNormals(positions, indices, normals);
  23989. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23990. var vertexData = new VertexData();
  23991. vertexData.indices = indices;
  23992. vertexData.positions = positions;
  23993. vertexData.normals = normals;
  23994. vertexData.uvs = uvs;
  23995. return vertexData;
  23996. };
  23997. VertexData.CreateIcoSphere = function (options) {
  23998. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23999. var radius = options.radius || 1;
  24000. var flat = (options.flat === undefined) ? true : options.flat;
  24001. var subdivisions = options.subdivisions || 4;
  24002. var radiusX = options.radiusX || radius;
  24003. var radiusY = options.radiusY || radius;
  24004. var radiusZ = options.radiusZ || radius;
  24005. var t = (1 + Math.sqrt(5)) / 2;
  24006. // 12 vertex x,y,z
  24007. var ico_vertices = [
  24008. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24009. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24010. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24011. ];
  24012. // index of 3 vertex makes a face of icopshere
  24013. var ico_indices = [
  24014. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24015. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24016. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24017. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24018. ];
  24019. // vertex for uv have aliased position, not for UV
  24020. var vertices_unalias_id = [
  24021. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24022. // vertex alias
  24023. 0,
  24024. 2,
  24025. 3,
  24026. 3,
  24027. 3,
  24028. 4,
  24029. 7,
  24030. 8,
  24031. 9,
  24032. 9,
  24033. 10,
  24034. 11 // 23: B + 12
  24035. ];
  24036. // uv as integer step (not pixels !)
  24037. var ico_vertexuv = [
  24038. 5, 1, 3, 1, 6, 4, 0, 0,
  24039. 5, 3, 4, 2, 2, 2, 4, 0,
  24040. 2, 0, 1, 1, 6, 0, 6, 2,
  24041. // vertex alias (for same vertex on different faces)
  24042. 0, 4,
  24043. 3, 3,
  24044. 4, 4,
  24045. 3, 1,
  24046. 4, 2,
  24047. 4, 4,
  24048. 0, 2,
  24049. 1, 1,
  24050. 2, 2,
  24051. 3, 3,
  24052. 1, 3,
  24053. 2, 4 // 23: B + 12
  24054. ];
  24055. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24056. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24057. // First island of uv mapping
  24058. // v = 4h 3+ 2
  24059. // v = 3h 9+ 4
  24060. // v = 2h 9+ 5 B
  24061. // v = 1h 9 1 0
  24062. // v = 0h 3 8 7 A
  24063. // u = 0 1 2 3 4 5 6 *a
  24064. // Second island of uv mapping
  24065. // v = 4h 0+ B+ 4+
  24066. // v = 3h A+ 2+
  24067. // v = 2h 7+ 6 3+
  24068. // v = 1h 8+ 3+
  24069. // v = 0h
  24070. // u = 0 1 2 3 4 5 6 *a
  24071. // Face layout on texture UV mapping
  24072. // ============
  24073. // \ 4 /\ 16 / ======
  24074. // \ / \ / /\ 11 /
  24075. // \/ 7 \/ / \ /
  24076. // ======= / 10 \/
  24077. // /\ 17 /\ =======
  24078. // / \ / \ \ 15 /\
  24079. // / 8 \/ 12 \ \ / \
  24080. // ============ \/ 6 \
  24081. // \ 18 /\ ============
  24082. // \ / \ \ 5 /\ 0 /
  24083. // \/ 13 \ \ / \ /
  24084. // ======= \/ 1 \/
  24085. // =============
  24086. // /\ 19 /\ 2 /\
  24087. // / \ / \ / \
  24088. // / 14 \/ 9 \/ 3 \
  24089. // ===================
  24090. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24091. var ustep = 138 / 1024;
  24092. var vstep = 239 / 1024;
  24093. var uoffset = 60 / 1024;
  24094. var voffset = 26 / 1024;
  24095. // Second island should have margin, not to touch the first island
  24096. // avoid any borderline artefact in pixel rounding
  24097. var island_u_offset = -40 / 1024;
  24098. var island_v_offset = +20 / 1024;
  24099. // face is either island 0 or 1 :
  24100. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24101. var island = [
  24102. 0, 0, 0, 0, 1,
  24103. 0, 0, 1, 1, 0,
  24104. 0, 0, 1, 1, 0,
  24105. 0, 1, 1, 1, 0 // 15 - 19
  24106. ];
  24107. var indices = [];
  24108. var positions = [];
  24109. var normals = [];
  24110. var uvs = [];
  24111. var current_indice = 0;
  24112. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24113. var face_vertex_pos = new Array(3);
  24114. var face_vertex_uv = new Array(3);
  24115. var v012;
  24116. for (v012 = 0; v012 < 3; v012++) {
  24117. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24118. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24119. }
  24120. // create all with normals
  24121. for (var face = 0; face < 20; face++) {
  24122. // 3 vertex per face
  24123. for (v012 = 0; v012 < 3; v012++) {
  24124. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24125. var v_id = ico_indices[3 * face + v012];
  24126. // vertex have 3D position (x,y,z)
  24127. 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]);
  24128. // Normalize to get normal, then scale to radius
  24129. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24130. // uv Coordinates from vertex ID
  24131. 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);
  24132. }
  24133. // Subdivide the face (interpolate pos, norm, uv)
  24134. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24135. // - norm is linear interpolation of vertex corner normal
  24136. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24137. // - uv is linear interpolation
  24138. //
  24139. // Topology is as below for sub-divide by 2
  24140. // vertex shown as v0,v1,v2
  24141. // interp index is i1 to progress in range [v0,v1[
  24142. // interp index is i2 to progress in range [v0,v2[
  24143. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24144. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24145. //
  24146. //
  24147. // i2 v2
  24148. // ^ ^
  24149. // / / \
  24150. // / / \
  24151. // / / \
  24152. // / / (0,1) \
  24153. // / #---------\
  24154. // / / \ (0,0)'/ \
  24155. // / / \ / \
  24156. // / / \ / \
  24157. // / / (0,0) \ / (1,0) \
  24158. // / #---------#---------\
  24159. // v0 v1
  24160. //
  24161. // --------------------> i1
  24162. //
  24163. // interp of (i1,i2):
  24164. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24165. // along i1 : lerp(x0,x1, i1/(S-i2))
  24166. //
  24167. // centroid of triangle is needed to get help normal computation
  24168. // (c1,c2) are used for centroid location
  24169. var interp_vertex = function (i1, i2, c1, c2) {
  24170. // vertex is interpolated from
  24171. // - face_vertex_pos[0..2]
  24172. // - face_vertex_uv[0..2]
  24173. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24174. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24175. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24176. pos_interp.normalize();
  24177. var vertex_normal;
  24178. if (flat) {
  24179. // in flat mode, recalculate normal as face centroid normal
  24180. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24181. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24182. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24183. }
  24184. else {
  24185. // in smooth mode, recalculate normal from each single vertex position
  24186. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24187. }
  24188. // Vertex normal need correction due to X,Y,Z radius scaling
  24189. vertex_normal.x /= radiusX;
  24190. vertex_normal.y /= radiusY;
  24191. vertex_normal.z /= radiusZ;
  24192. vertex_normal.normalize();
  24193. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24194. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24195. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24196. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24197. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24198. uvs.push(uv_interp.x, uv_interp.y);
  24199. // push each vertex has member of a face
  24200. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24201. indices.push(current_indice);
  24202. current_indice++;
  24203. };
  24204. for (var i2 = 0; i2 < subdivisions; i2++) {
  24205. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24206. // face : (i1,i2) for /\ :
  24207. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24208. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24209. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24210. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24211. if (i1 + i2 + 1 < subdivisions) {
  24212. // face : (i1,i2)' for \/ :
  24213. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24214. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24215. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24216. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24217. }
  24218. }
  24219. }
  24220. }
  24221. // Sides
  24222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24223. // Result
  24224. var vertexData = new VertexData();
  24225. vertexData.indices = indices;
  24226. vertexData.positions = positions;
  24227. vertexData.normals = normals;
  24228. vertexData.uvs = uvs;
  24229. return vertexData;
  24230. };
  24231. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24232. VertexData.CreatePolyhedron = function (options) {
  24233. // provided polyhedron types :
  24234. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24235. // 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)
  24236. var polyhedra = [];
  24237. 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]] };
  24238. 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]] };
  24239. polyhedra[2] = {
  24240. 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]],
  24241. 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]]
  24242. };
  24243. polyhedra[3] = {
  24244. 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]],
  24245. 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]]
  24246. };
  24247. polyhedra[4] = {
  24248. 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]],
  24249. 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]]
  24250. };
  24251. 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]] };
  24252. 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]] };
  24253. 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]] };
  24254. 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]] };
  24255. 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]] };
  24256. 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]] };
  24257. 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]] };
  24258. 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]] };
  24259. 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]] };
  24260. polyhedra[14] = {
  24261. 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]],
  24262. 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]]
  24263. };
  24264. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24265. var size = options.size;
  24266. var sizeX = options.sizeX || size || 1;
  24267. var sizeY = options.sizeY || size || 1;
  24268. var sizeZ = options.sizeZ || size || 1;
  24269. var data = options.custom || polyhedra[type];
  24270. var nbfaces = data.face.length;
  24271. var faceUV = options.faceUV || new Array(nbfaces);
  24272. var faceColors = options.faceColors;
  24273. var flat = (options.flat === undefined) ? true : options.flat;
  24274. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24275. var positions = [];
  24276. var indices = [];
  24277. var normals = [];
  24278. var uvs = [];
  24279. var colors = [];
  24280. var index = 0;
  24281. var faceIdx = 0; // face cursor in the array "indexes"
  24282. var indexes = [];
  24283. var i = 0;
  24284. var f = 0;
  24285. var u, v, ang, x, y, tmp;
  24286. // default face colors and UV if undefined
  24287. if (flat) {
  24288. for (f = 0; f < nbfaces; f++) {
  24289. if (faceColors && faceColors[f] === undefined) {
  24290. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24291. }
  24292. if (faceUV && faceUV[f] === undefined) {
  24293. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24294. }
  24295. }
  24296. }
  24297. if (!flat) {
  24298. for (i = 0; i < data.vertex.length; i++) {
  24299. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24300. uvs.push(0, 0);
  24301. }
  24302. for (f = 0; f < nbfaces; f++) {
  24303. for (i = 0; i < data.face[f].length - 2; i++) {
  24304. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24305. }
  24306. }
  24307. }
  24308. else {
  24309. for (f = 0; f < nbfaces; f++) {
  24310. var fl = data.face[f].length; // number of vertices of the current face
  24311. ang = 2 * Math.PI / fl;
  24312. x = 0.5 * Math.tan(ang / 2);
  24313. y = 0.5;
  24314. // positions, uvs, colors
  24315. for (i = 0; i < fl; i++) {
  24316. // positions
  24317. 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);
  24318. indexes.push(index);
  24319. index++;
  24320. // uvs
  24321. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24322. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24323. uvs.push(u, v);
  24324. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24325. y = x * Math.sin(ang) + y * Math.cos(ang);
  24326. x = tmp;
  24327. // colors
  24328. if (faceColors) {
  24329. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24330. }
  24331. }
  24332. // indices from indexes
  24333. for (i = 0; i < fl - 2; i++) {
  24334. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24335. }
  24336. faceIdx += fl;
  24337. }
  24338. }
  24339. VertexData.ComputeNormals(positions, indices, normals);
  24340. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24341. var vertexData = new VertexData();
  24342. vertexData.positions = positions;
  24343. vertexData.indices = indices;
  24344. vertexData.normals = normals;
  24345. vertexData.uvs = uvs;
  24346. if (faceColors && flat) {
  24347. vertexData.colors = colors;
  24348. }
  24349. return vertexData;
  24350. };
  24351. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24352. VertexData.CreateTorusKnot = function (options) {
  24353. var indices = [];
  24354. var positions = [];
  24355. var normals = [];
  24356. var uvs = [];
  24357. var radius = options.radius || 2;
  24358. var tube = options.tube || 0.5;
  24359. var radialSegments = options.radialSegments || 32;
  24360. var tubularSegments = options.tubularSegments || 32;
  24361. var p = options.p || 2;
  24362. var q = options.q || 3;
  24363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24364. // Helper
  24365. var getPos = function (angle) {
  24366. var cu = Math.cos(angle);
  24367. var su = Math.sin(angle);
  24368. var quOverP = q / p * angle;
  24369. var cs = Math.cos(quOverP);
  24370. var tx = radius * (2 + cs) * 0.5 * cu;
  24371. var ty = radius * (2 + cs) * su * 0.5;
  24372. var tz = radius * Math.sin(quOverP) * 0.5;
  24373. return new BABYLON.Vector3(tx, ty, tz);
  24374. };
  24375. // Vertices
  24376. var i;
  24377. var j;
  24378. for (i = 0; i <= radialSegments; i++) {
  24379. var modI = i % radialSegments;
  24380. var u = modI / radialSegments * 2 * p * Math.PI;
  24381. var p1 = getPos(u);
  24382. var p2 = getPos(u + 0.01);
  24383. var tang = p2.subtract(p1);
  24384. var n = p2.add(p1);
  24385. var bitan = BABYLON.Vector3.Cross(tang, n);
  24386. n = BABYLON.Vector3.Cross(bitan, tang);
  24387. bitan.normalize();
  24388. n.normalize();
  24389. for (j = 0; j < tubularSegments; j++) {
  24390. var modJ = j % tubularSegments;
  24391. var v = modJ / tubularSegments * 2 * Math.PI;
  24392. var cx = -tube * Math.cos(v);
  24393. var cy = tube * Math.sin(v);
  24394. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24395. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24396. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24397. uvs.push(i / radialSegments);
  24398. uvs.push(j / tubularSegments);
  24399. }
  24400. }
  24401. for (i = 0; i < radialSegments; i++) {
  24402. for (j = 0; j < tubularSegments; j++) {
  24403. var jNext = (j + 1) % tubularSegments;
  24404. var a = i * tubularSegments + j;
  24405. var b = (i + 1) * tubularSegments + j;
  24406. var c = (i + 1) * tubularSegments + jNext;
  24407. var d = i * tubularSegments + jNext;
  24408. indices.push(d);
  24409. indices.push(b);
  24410. indices.push(a);
  24411. indices.push(d);
  24412. indices.push(c);
  24413. indices.push(b);
  24414. }
  24415. }
  24416. // Normals
  24417. VertexData.ComputeNormals(positions, indices, normals);
  24418. // Sides
  24419. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24420. // Result
  24421. var vertexData = new VertexData();
  24422. vertexData.indices = indices;
  24423. vertexData.positions = positions;
  24424. vertexData.normals = normals;
  24425. vertexData.uvs = uvs;
  24426. return vertexData;
  24427. };
  24428. // Tools
  24429. /**
  24430. * @param {any} - positions (number[] or Float32Array)
  24431. * @param {any} - indices (number[] or Uint16Array)
  24432. * @param {any} - normals (number[] or Float32Array)
  24433. */
  24434. VertexData.ComputeNormals = function (positions, indices, normals) {
  24435. var index = 0;
  24436. var p1p2x = 0.0;
  24437. var p1p2y = 0.0;
  24438. var p1p2z = 0.0;
  24439. var p3p2x = 0.0;
  24440. var p3p2y = 0.0;
  24441. var p3p2z = 0.0;
  24442. var faceNormalx = 0.0;
  24443. var faceNormaly = 0.0;
  24444. var faceNormalz = 0.0;
  24445. var length = 0.0;
  24446. var i1 = 0;
  24447. var i2 = 0;
  24448. var i3 = 0;
  24449. for (index = 0; index < positions.length; index++) {
  24450. normals[index] = 0.0;
  24451. }
  24452. // indice triplet = 1 face
  24453. var nbFaces = indices.length / 3;
  24454. for (index = 0; index < nbFaces; index++) {
  24455. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24456. i2 = indices[index * 3 + 1];
  24457. i3 = indices[index * 3 + 2];
  24458. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24459. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24460. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24461. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24462. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24463. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24464. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24465. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24466. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24467. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24468. length = (length === 0) ? 1.0 : length;
  24469. faceNormalx /= length; // normalize this normal
  24470. faceNormaly /= length;
  24471. faceNormalz /= length;
  24472. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24473. normals[i1 * 3 + 1] += faceNormaly;
  24474. normals[i1 * 3 + 2] += faceNormalz;
  24475. normals[i2 * 3] += faceNormalx;
  24476. normals[i2 * 3 + 1] += faceNormaly;
  24477. normals[i2 * 3 + 2] += faceNormalz;
  24478. normals[i3 * 3] += faceNormalx;
  24479. normals[i3 * 3 + 1] += faceNormaly;
  24480. normals[i3 * 3 + 2] += faceNormalz;
  24481. }
  24482. // last normalization of each normal
  24483. for (index = 0; index < normals.length / 3; index++) {
  24484. faceNormalx = normals[index * 3];
  24485. faceNormaly = normals[index * 3 + 1];
  24486. faceNormalz = normals[index * 3 + 2];
  24487. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24488. length = (length === 0) ? 1.0 : length;
  24489. faceNormalx /= length;
  24490. faceNormaly /= length;
  24491. faceNormalz /= length;
  24492. normals[index * 3] = faceNormalx;
  24493. normals[index * 3 + 1] = faceNormaly;
  24494. normals[index * 3 + 2] = faceNormalz;
  24495. }
  24496. };
  24497. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24498. var li = indices.length;
  24499. var ln = normals.length;
  24500. var i;
  24501. var n;
  24502. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24503. switch (sideOrientation) {
  24504. case BABYLON.Mesh.FRONTSIDE:
  24505. // nothing changed
  24506. break;
  24507. case BABYLON.Mesh.BACKSIDE:
  24508. var tmp;
  24509. // indices
  24510. for (i = 0; i < li; i += 3) {
  24511. tmp = indices[i];
  24512. indices[i] = indices[i + 2];
  24513. indices[i + 2] = tmp;
  24514. }
  24515. // normals
  24516. for (n = 0; n < ln; n++) {
  24517. normals[n] = -normals[n];
  24518. }
  24519. break;
  24520. case BABYLON.Mesh.DOUBLESIDE:
  24521. // positions
  24522. var lp = positions.length;
  24523. var l = lp / 3;
  24524. for (var p = 0; p < lp; p++) {
  24525. positions[lp + p] = positions[p];
  24526. }
  24527. // indices
  24528. for (i = 0; i < li; i += 3) {
  24529. indices[i + li] = indices[i + 2] + l;
  24530. indices[i + 1 + li] = indices[i + 1] + l;
  24531. indices[i + 2 + li] = indices[i] + l;
  24532. }
  24533. // normals
  24534. for (n = 0; n < ln; n++) {
  24535. normals[ln + n] = -normals[n];
  24536. }
  24537. // uvs
  24538. var lu = uvs.length;
  24539. for (var u = 0; u < lu; u++) {
  24540. uvs[u + lu] = uvs[u];
  24541. }
  24542. break;
  24543. }
  24544. };
  24545. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24546. var vertexData = new VertexData();
  24547. // positions
  24548. var positions = parsedVertexData.positions;
  24549. if (positions) {
  24550. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24551. }
  24552. // normals
  24553. var normals = parsedVertexData.normals;
  24554. if (normals) {
  24555. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24556. }
  24557. // uvs
  24558. var uvs = parsedVertexData.uvs;
  24559. if (uvs) {
  24560. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24561. }
  24562. // uv2s
  24563. var uv2s = parsedVertexData.uv2s;
  24564. if (uv2s) {
  24565. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24566. }
  24567. // uv3s
  24568. var uv3s = parsedVertexData.uv3s;
  24569. if (uv3s) {
  24570. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24571. }
  24572. // uv4s
  24573. var uv4s = parsedVertexData.uv4s;
  24574. if (uv4s) {
  24575. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24576. }
  24577. // uv5s
  24578. var uv5s = parsedVertexData.uv5s;
  24579. if (uv5s) {
  24580. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24581. }
  24582. // uv6s
  24583. var uv6s = parsedVertexData.uv6s;
  24584. if (uv6s) {
  24585. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24586. }
  24587. // colors
  24588. var colors = parsedVertexData.colors;
  24589. if (colors) {
  24590. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24591. }
  24592. // matricesIndices
  24593. var matricesIndices = parsedVertexData.matricesIndices;
  24594. if (matricesIndices) {
  24595. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24596. }
  24597. // matricesWeights
  24598. var matricesWeights = parsedVertexData.matricesWeights;
  24599. if (matricesWeights) {
  24600. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24601. }
  24602. // indices
  24603. var indices = parsedVertexData.indices;
  24604. if (indices) {
  24605. vertexData.indices = indices;
  24606. }
  24607. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24608. };
  24609. return VertexData;
  24610. })();
  24611. BABYLON.VertexData = VertexData;
  24612. })(BABYLON || (BABYLON = {}));
  24613. var BABYLON;
  24614. (function (BABYLON) {
  24615. var Tags = (function () {
  24616. function Tags() {
  24617. }
  24618. Tags.EnableFor = function (obj) {
  24619. obj._tags = obj._tags || {};
  24620. obj.hasTags = function () {
  24621. return Tags.HasTags(obj);
  24622. };
  24623. obj.addTags = function (tagsString) {
  24624. return Tags.AddTagsTo(obj, tagsString);
  24625. };
  24626. obj.removeTags = function (tagsString) {
  24627. return Tags.RemoveTagsFrom(obj, tagsString);
  24628. };
  24629. obj.matchesTagsQuery = function (tagsQuery) {
  24630. return Tags.MatchesQuery(obj, tagsQuery);
  24631. };
  24632. };
  24633. Tags.DisableFor = function (obj) {
  24634. delete obj._tags;
  24635. delete obj.hasTags;
  24636. delete obj.addTags;
  24637. delete obj.removeTags;
  24638. delete obj.matchesTagsQuery;
  24639. };
  24640. Tags.HasTags = function (obj) {
  24641. if (!obj._tags) {
  24642. return false;
  24643. }
  24644. return !BABYLON.Tools.IsEmpty(obj._tags);
  24645. };
  24646. Tags.GetTags = function (obj) {
  24647. if (!obj._tags) {
  24648. return null;
  24649. }
  24650. return obj._tags;
  24651. };
  24652. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24653. // a tag cannot start with '||', '&&', and '!'
  24654. // it cannot contain whitespaces
  24655. Tags.AddTagsTo = function (obj, tagsString) {
  24656. if (!tagsString) {
  24657. return;
  24658. }
  24659. if (typeof tagsString !== "string") {
  24660. return;
  24661. }
  24662. var tags = tagsString.split(" ");
  24663. for (var t in tags) {
  24664. Tags._AddTagTo(obj, tags[t]);
  24665. }
  24666. };
  24667. Tags._AddTagTo = function (obj, tag) {
  24668. tag = tag.trim();
  24669. if (tag === "" || tag === "true" || tag === "false") {
  24670. return;
  24671. }
  24672. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24673. return;
  24674. }
  24675. Tags.EnableFor(obj);
  24676. obj._tags[tag] = true;
  24677. };
  24678. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24679. if (!Tags.HasTags(obj)) {
  24680. return;
  24681. }
  24682. var tags = tagsString.split(" ");
  24683. for (var t in tags) {
  24684. Tags._RemoveTagFrom(obj, tags[t]);
  24685. }
  24686. };
  24687. Tags._RemoveTagFrom = function (obj, tag) {
  24688. delete obj._tags[tag];
  24689. };
  24690. Tags.MatchesQuery = function (obj, tagsQuery) {
  24691. if (tagsQuery === undefined) {
  24692. return true;
  24693. }
  24694. if (tagsQuery === "") {
  24695. return Tags.HasTags(obj);
  24696. }
  24697. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24698. };
  24699. return Tags;
  24700. })();
  24701. BABYLON.Tags = Tags;
  24702. })(BABYLON || (BABYLON = {}));
  24703. var BABYLON;
  24704. (function (BABYLON) {
  24705. var Internals;
  24706. (function (Internals) {
  24707. var AndOrNotEvaluator = (function () {
  24708. function AndOrNotEvaluator() {
  24709. }
  24710. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24711. if (!query.match(/\([^\(\)]*\)/g)) {
  24712. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24713. }
  24714. else {
  24715. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24716. // remove parenthesis
  24717. r = r.slice(1, r.length - 1);
  24718. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24719. });
  24720. }
  24721. if (query === "true") {
  24722. return true;
  24723. }
  24724. if (query === "false") {
  24725. return false;
  24726. }
  24727. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24728. };
  24729. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24730. evaluateCallback = evaluateCallback || (function (r) {
  24731. return r === "true" ? true : false;
  24732. });
  24733. var result;
  24734. var or = parenthesisContent.split("||");
  24735. for (var i in or) {
  24736. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24737. var and = ori.split("&&");
  24738. if (and.length > 1) {
  24739. for (var j = 0; j < and.length; ++j) {
  24740. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24741. if (andj !== "true" && andj !== "false") {
  24742. if (andj[0] === "!") {
  24743. result = !evaluateCallback(andj.substring(1));
  24744. }
  24745. else {
  24746. result = evaluateCallback(andj);
  24747. }
  24748. }
  24749. else {
  24750. result = andj === "true" ? true : false;
  24751. }
  24752. if (!result) {
  24753. ori = "false";
  24754. break;
  24755. }
  24756. }
  24757. }
  24758. if (result || ori === "true") {
  24759. result = true;
  24760. break;
  24761. }
  24762. // result equals false (or undefined)
  24763. if (ori !== "true" && ori !== "false") {
  24764. if (ori[0] === "!") {
  24765. result = !evaluateCallback(ori.substring(1));
  24766. }
  24767. else {
  24768. result = evaluateCallback(ori);
  24769. }
  24770. }
  24771. else {
  24772. result = ori === "true" ? true : false;
  24773. }
  24774. }
  24775. // the whole parenthesis scope is replaced by 'true' or 'false'
  24776. return result ? "true" : "false";
  24777. };
  24778. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24779. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24780. // remove whitespaces
  24781. r = r.replace(/[\s]/g, function () { return ""; });
  24782. return r.length % 2 ? "!" : "";
  24783. });
  24784. booleanString = booleanString.trim();
  24785. if (booleanString === "!true") {
  24786. booleanString = "false";
  24787. }
  24788. else if (booleanString === "!false") {
  24789. booleanString = "true";
  24790. }
  24791. return booleanString;
  24792. };
  24793. return AndOrNotEvaluator;
  24794. })();
  24795. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24796. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24797. })(BABYLON || (BABYLON = {}));
  24798. var BABYLON;
  24799. (function (BABYLON) {
  24800. var PostProcessRenderPass = (function () {
  24801. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24802. this._enabled = true;
  24803. this._refCount = 0;
  24804. this._name = name;
  24805. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24806. this.setRenderList(renderList);
  24807. this._renderTexture.onBeforeRender = beforeRender;
  24808. this._renderTexture.onAfterRender = afterRender;
  24809. this._scene = scene;
  24810. this._renderList = renderList;
  24811. }
  24812. // private
  24813. PostProcessRenderPass.prototype._incRefCount = function () {
  24814. if (this._refCount === 0) {
  24815. this._scene.customRenderTargets.push(this._renderTexture);
  24816. }
  24817. return ++this._refCount;
  24818. };
  24819. PostProcessRenderPass.prototype._decRefCount = function () {
  24820. this._refCount--;
  24821. if (this._refCount <= 0) {
  24822. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24823. }
  24824. return this._refCount;
  24825. };
  24826. PostProcessRenderPass.prototype._update = function () {
  24827. this.setRenderList(this._renderList);
  24828. };
  24829. // public
  24830. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24831. this._renderTexture.renderList = renderList;
  24832. };
  24833. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24834. return this._renderTexture;
  24835. };
  24836. return PostProcessRenderPass;
  24837. })();
  24838. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24839. })(BABYLON || (BABYLON = {}));
  24840. var BABYLON;
  24841. (function (BABYLON) {
  24842. var PostProcessRenderEffect = (function () {
  24843. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24844. this._engine = engine;
  24845. this._name = name;
  24846. this._singleInstance = singleInstance || true;
  24847. this._getPostProcess = getPostProcess;
  24848. this._cameras = [];
  24849. this._indicesForCamera = [];
  24850. this._postProcesses = {};
  24851. this._renderPasses = {};
  24852. this._renderEffectAsPasses = {};
  24853. }
  24854. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24855. get: function () {
  24856. for (var index in this._postProcesses) {
  24857. if (!this._postProcesses[index].isSupported) {
  24858. return false;
  24859. }
  24860. }
  24861. return true;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. PostProcessRenderEffect.prototype._update = function () {
  24867. for (var renderPassName in this._renderPasses) {
  24868. this._renderPasses[renderPassName]._update();
  24869. }
  24870. };
  24871. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24872. this._renderPasses[renderPass._name] = renderPass;
  24873. this._linkParameters();
  24874. };
  24875. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24876. delete this._renderPasses[renderPass._name];
  24877. this._linkParameters();
  24878. };
  24879. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24880. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24881. this._linkParameters();
  24882. };
  24883. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24884. for (var renderPassName in this._renderPasses) {
  24885. if (renderPassName === passName) {
  24886. return this._renderPasses[passName];
  24887. }
  24888. }
  24889. };
  24890. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24891. this._renderPasses = {};
  24892. this._linkParameters();
  24893. };
  24894. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24895. var cameraKey;
  24896. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24897. for (var i = 0; i < _cam.length; i++) {
  24898. var camera = _cam[i];
  24899. var cameraName = camera.name;
  24900. if (this._singleInstance) {
  24901. cameraKey = 0;
  24902. }
  24903. else {
  24904. cameraKey = cameraName;
  24905. }
  24906. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24907. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24908. if (!this._indicesForCamera[cameraName]) {
  24909. this._indicesForCamera[cameraName] = [];
  24910. }
  24911. this._indicesForCamera[cameraName].push(index);
  24912. if (this._cameras.indexOf(camera) === -1) {
  24913. this._cameras[cameraName] = camera;
  24914. }
  24915. for (var passName in this._renderPasses) {
  24916. this._renderPasses[passName]._incRefCount();
  24917. }
  24918. }
  24919. this._linkParameters();
  24920. };
  24921. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24922. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24923. for (var i = 0; i < _cam.length; i++) {
  24924. var camera = _cam[i];
  24925. var cameraName = camera.name;
  24926. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24927. var index = this._cameras.indexOf(cameraName);
  24928. this._indicesForCamera.splice(index, 1);
  24929. this._cameras.splice(index, 1);
  24930. for (var passName in this._renderPasses) {
  24931. this._renderPasses[passName]._decRefCount();
  24932. }
  24933. }
  24934. };
  24935. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24936. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24937. for (var i = 0; i < _cam.length; i++) {
  24938. var camera = _cam[i];
  24939. var cameraName = camera.name;
  24940. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24941. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24942. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24943. }
  24944. }
  24945. for (var passName in this._renderPasses) {
  24946. this._renderPasses[passName]._incRefCount();
  24947. }
  24948. }
  24949. };
  24950. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24951. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24952. for (var i = 0; i < _cam.length; i++) {
  24953. var camera = _cam[i];
  24954. var cameraName = camera.Name;
  24955. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24956. for (var passName in this._renderPasses) {
  24957. this._renderPasses[passName]._decRefCount();
  24958. }
  24959. }
  24960. };
  24961. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24962. if (this._singleInstance) {
  24963. return this._postProcesses[0];
  24964. }
  24965. else {
  24966. return this._postProcesses[camera.name];
  24967. }
  24968. };
  24969. PostProcessRenderEffect.prototype._linkParameters = function () {
  24970. var _this = this;
  24971. for (var index in this._postProcesses) {
  24972. if (this.applyParameters) {
  24973. this.applyParameters(this._postProcesses[index]);
  24974. }
  24975. this._postProcesses[index].onBeforeRender = function (effect) {
  24976. _this._linkTextures(effect);
  24977. };
  24978. }
  24979. };
  24980. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24981. for (var renderPassName in this._renderPasses) {
  24982. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24983. }
  24984. for (var renderEffectName in this._renderEffectAsPasses) {
  24985. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24986. }
  24987. };
  24988. return PostProcessRenderEffect;
  24989. })();
  24990. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24991. })(BABYLON || (BABYLON = {}));
  24992. var BABYLON;
  24993. (function (BABYLON) {
  24994. var PostProcessRenderPipeline = (function () {
  24995. function PostProcessRenderPipeline(engine, name) {
  24996. this._engine = engine;
  24997. this._name = name;
  24998. this._renderEffects = {};
  24999. this._renderEffectsForIsolatedPass = {};
  25000. this._cameras = [];
  25001. }
  25002. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25003. get: function () {
  25004. for (var renderEffectName in this._renderEffects) {
  25005. if (!this._renderEffects[renderEffectName].isSupported) {
  25006. return false;
  25007. }
  25008. }
  25009. return true;
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25015. this._renderEffects[renderEffect._name] = renderEffect;
  25016. };
  25017. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25018. var renderEffects = this._renderEffects[renderEffectName];
  25019. if (!renderEffects) {
  25020. return;
  25021. }
  25022. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25023. };
  25024. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25025. var renderEffects = this._renderEffects[renderEffectName];
  25026. if (!renderEffects) {
  25027. return;
  25028. }
  25029. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25030. };
  25031. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25032. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25033. var indicesToDelete = [];
  25034. var i;
  25035. for (i = 0; i < _cam.length; i++) {
  25036. var camera = _cam[i];
  25037. var cameraName = camera.name;
  25038. if (this._cameras.indexOf(camera) === -1) {
  25039. this._cameras[cameraName] = camera;
  25040. }
  25041. else if (unique) {
  25042. indicesToDelete.push(i);
  25043. }
  25044. }
  25045. for (i = 0; i < indicesToDelete.length; i++) {
  25046. cameras.splice(indicesToDelete[i], 1);
  25047. }
  25048. for (var renderEffectName in this._renderEffects) {
  25049. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25050. }
  25051. };
  25052. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25053. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25054. for (var renderEffectName in this._renderEffects) {
  25055. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25056. }
  25057. for (var i = 0; i < _cam.length; i++) {
  25058. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25059. }
  25060. };
  25061. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25062. var _this = this;
  25063. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25064. var pass = null;
  25065. var renderEffectName;
  25066. for (renderEffectName in this._renderEffects) {
  25067. pass = this._renderEffects[renderEffectName].getPass(passName);
  25068. if (pass != null) {
  25069. break;
  25070. }
  25071. }
  25072. if (pass === null) {
  25073. return;
  25074. }
  25075. for (renderEffectName in this._renderEffects) {
  25076. this._renderEffects[renderEffectName]._disable(_cam);
  25077. }
  25078. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25079. for (var i = 0; i < _cam.length; i++) {
  25080. var camera = _cam[i];
  25081. var cameraName = camera.name;
  25082. 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); });
  25083. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25084. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25085. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25086. }
  25087. };
  25088. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25089. var _this = this;
  25090. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25091. for (var i = 0; i < _cam.length; i++) {
  25092. var camera = _cam[i];
  25093. var cameraName = camera.name;
  25094. 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); });
  25095. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25096. }
  25097. for (var renderEffectName in this._renderEffects) {
  25098. this._renderEffects[renderEffectName]._enable(_cam);
  25099. }
  25100. };
  25101. PostProcessRenderPipeline.prototype._update = function () {
  25102. for (var renderEffectName in this._renderEffects) {
  25103. this._renderEffects[renderEffectName]._update();
  25104. }
  25105. for (var i = 0; i < this._cameras.length; i++) {
  25106. var cameraName = this._cameras[i].name;
  25107. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25108. this._renderEffectsForIsolatedPass[cameraName]._update();
  25109. }
  25110. }
  25111. };
  25112. PostProcessRenderPipeline.prototype.dispose = function () {
  25113. // Must be implemented by children
  25114. };
  25115. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25116. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25117. return PostProcessRenderPipeline;
  25118. })();
  25119. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25120. })(BABYLON || (BABYLON = {}));
  25121. var BABYLON;
  25122. (function (BABYLON) {
  25123. var PostProcessRenderPipelineManager = (function () {
  25124. function PostProcessRenderPipelineManager() {
  25125. this._renderPipelines = {};
  25126. }
  25127. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25128. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25129. };
  25130. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25131. var renderPipeline = this._renderPipelines[renderPipelineName];
  25132. if (!renderPipeline) {
  25133. return;
  25134. }
  25135. renderPipeline._attachCameras(cameras, unique);
  25136. };
  25137. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25138. var renderPipeline = this._renderPipelines[renderPipelineName];
  25139. if (!renderPipeline) {
  25140. return;
  25141. }
  25142. renderPipeline._detachCameras(cameras);
  25143. };
  25144. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25145. var renderPipeline = this._renderPipelines[renderPipelineName];
  25146. if (!renderPipeline) {
  25147. return;
  25148. }
  25149. renderPipeline._enableEffect(renderEffectName, cameras);
  25150. };
  25151. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25152. var renderPipeline = this._renderPipelines[renderPipelineName];
  25153. if (!renderPipeline) {
  25154. return;
  25155. }
  25156. renderPipeline._disableEffect(renderEffectName, cameras);
  25157. };
  25158. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25159. var renderPipeline = this._renderPipelines[renderPipelineName];
  25160. if (!renderPipeline) {
  25161. return;
  25162. }
  25163. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25164. };
  25165. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25166. var renderPipeline = this._renderPipelines[renderPipelineName];
  25167. if (!renderPipeline) {
  25168. return;
  25169. }
  25170. renderPipeline._disableDisplayOnlyPass(cameras);
  25171. };
  25172. PostProcessRenderPipelineManager.prototype.update = function () {
  25173. for (var renderPipelineName in this._renderPipelines) {
  25174. var pipeline = this._renderPipelines[renderPipelineName];
  25175. if (!pipeline.isSupported) {
  25176. pipeline.dispose();
  25177. delete this._renderPipelines[renderPipelineName];
  25178. }
  25179. else {
  25180. pipeline._update();
  25181. }
  25182. }
  25183. };
  25184. return PostProcessRenderPipelineManager;
  25185. })();
  25186. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25187. })(BABYLON || (BABYLON = {}));
  25188. var BABYLON;
  25189. (function (BABYLON) {
  25190. var BoundingBoxRenderer = (function () {
  25191. function BoundingBoxRenderer(scene) {
  25192. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25193. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25194. this.showBackLines = true;
  25195. this.renderList = new BABYLON.SmartArray(32);
  25196. this._scene = scene;
  25197. }
  25198. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25199. if (this._colorShader) {
  25200. return;
  25201. }
  25202. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25203. attributes: ["position"],
  25204. uniforms: ["worldViewProjection", "color"]
  25205. });
  25206. var engine = this._scene.getEngine();
  25207. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25208. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25209. 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]);
  25210. };
  25211. BoundingBoxRenderer.prototype.reset = function () {
  25212. this.renderList.reset();
  25213. };
  25214. BoundingBoxRenderer.prototype.render = function () {
  25215. if (this.renderList.length === 0) {
  25216. return;
  25217. }
  25218. this._prepareRessources();
  25219. if (!this._colorShader.isReady()) {
  25220. return;
  25221. }
  25222. var engine = this._scene.getEngine();
  25223. engine.setDepthWrite(false);
  25224. this._colorShader._preBind();
  25225. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25226. var boundingBox = this.renderList.data[boundingBoxIndex];
  25227. var min = boundingBox.minimum;
  25228. var max = boundingBox.maximum;
  25229. var diff = max.subtract(min);
  25230. var median = min.add(diff.scale(0.5));
  25231. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25232. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25233. .multiply(boundingBox.getWorldMatrix());
  25234. // VBOs
  25235. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25236. if (this.showBackLines) {
  25237. // Back
  25238. engine.setDepthFunctionToGreaterOrEqual();
  25239. this._scene.resetCachedMaterial();
  25240. this._colorShader.setColor4("color", this.backColor.toColor4());
  25241. this._colorShader.bind(worldMatrix);
  25242. // Draw order
  25243. engine.draw(false, 0, 24);
  25244. }
  25245. // Front
  25246. engine.setDepthFunctionToLess();
  25247. this._scene.resetCachedMaterial();
  25248. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25249. this._colorShader.bind(worldMatrix);
  25250. // Draw order
  25251. engine.draw(false, 0, 24);
  25252. }
  25253. this._colorShader.unbind();
  25254. engine.setDepthFunctionToLessOrEqual();
  25255. engine.setDepthWrite(true);
  25256. };
  25257. BoundingBoxRenderer.prototype.dispose = function () {
  25258. if (!this._colorShader) {
  25259. return;
  25260. }
  25261. this._colorShader.dispose();
  25262. this._vb.dispose();
  25263. this._scene.getEngine()._releaseBuffer(this._ib);
  25264. };
  25265. return BoundingBoxRenderer;
  25266. })();
  25267. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25268. })(BABYLON || (BABYLON = {}));
  25269. var BABYLON;
  25270. (function (BABYLON) {
  25271. var Condition = (function () {
  25272. function Condition(actionManager) {
  25273. this._actionManager = actionManager;
  25274. }
  25275. Condition.prototype.isValid = function () {
  25276. return true;
  25277. };
  25278. Condition.prototype._getProperty = function (propertyPath) {
  25279. return this._actionManager._getProperty(propertyPath);
  25280. };
  25281. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25282. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25283. };
  25284. return Condition;
  25285. })();
  25286. BABYLON.Condition = Condition;
  25287. var ValueCondition = (function (_super) {
  25288. __extends(ValueCondition, _super);
  25289. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25290. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25291. _super.call(this, actionManager);
  25292. this.propertyPath = propertyPath;
  25293. this.value = value;
  25294. this.operator = operator;
  25295. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25296. this._property = this._getProperty(this.propertyPath);
  25297. }
  25298. Object.defineProperty(ValueCondition, "IsEqual", {
  25299. get: function () {
  25300. return ValueCondition._IsEqual;
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. Object.defineProperty(ValueCondition, "IsDifferent", {
  25306. get: function () {
  25307. return ValueCondition._IsDifferent;
  25308. },
  25309. enumerable: true,
  25310. configurable: true
  25311. });
  25312. Object.defineProperty(ValueCondition, "IsGreater", {
  25313. get: function () {
  25314. return ValueCondition._IsGreater;
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(ValueCondition, "IsLesser", {
  25320. get: function () {
  25321. return ValueCondition._IsLesser;
  25322. },
  25323. enumerable: true,
  25324. configurable: true
  25325. });
  25326. // Methods
  25327. ValueCondition.prototype.isValid = function () {
  25328. switch (this.operator) {
  25329. case ValueCondition.IsGreater:
  25330. return this._target[this._property] > this.value;
  25331. case ValueCondition.IsLesser:
  25332. return this._target[this._property] < this.value;
  25333. case ValueCondition.IsEqual:
  25334. case ValueCondition.IsDifferent:
  25335. var check;
  25336. if (this.value.equals) {
  25337. check = this.value.equals(this._target[this._property]);
  25338. }
  25339. else {
  25340. check = this.value === this._target[this._property];
  25341. }
  25342. return this.operator === ValueCondition.IsEqual ? check : !check;
  25343. }
  25344. return false;
  25345. };
  25346. // Statics
  25347. ValueCondition._IsEqual = 0;
  25348. ValueCondition._IsDifferent = 1;
  25349. ValueCondition._IsGreater = 2;
  25350. ValueCondition._IsLesser = 3;
  25351. return ValueCondition;
  25352. })(Condition);
  25353. BABYLON.ValueCondition = ValueCondition;
  25354. var PredicateCondition = (function (_super) {
  25355. __extends(PredicateCondition, _super);
  25356. function PredicateCondition(actionManager, predicate) {
  25357. _super.call(this, actionManager);
  25358. this.predicate = predicate;
  25359. }
  25360. PredicateCondition.prototype.isValid = function () {
  25361. return this.predicate();
  25362. };
  25363. return PredicateCondition;
  25364. })(Condition);
  25365. BABYLON.PredicateCondition = PredicateCondition;
  25366. var StateCondition = (function (_super) {
  25367. __extends(StateCondition, _super);
  25368. function StateCondition(actionManager, target, value) {
  25369. _super.call(this, actionManager);
  25370. this.value = value;
  25371. this._target = target;
  25372. }
  25373. // Methods
  25374. StateCondition.prototype.isValid = function () {
  25375. return this._target.state === this.value;
  25376. };
  25377. return StateCondition;
  25378. })(Condition);
  25379. BABYLON.StateCondition = StateCondition;
  25380. })(BABYLON || (BABYLON = {}));
  25381. var BABYLON;
  25382. (function (BABYLON) {
  25383. var Action = (function () {
  25384. function Action(triggerOptions, condition) {
  25385. this.triggerOptions = triggerOptions;
  25386. if (triggerOptions.parameter) {
  25387. this.trigger = triggerOptions.trigger;
  25388. this._triggerParameter = triggerOptions.parameter;
  25389. }
  25390. else {
  25391. this.trigger = triggerOptions;
  25392. }
  25393. this._nextActiveAction = this;
  25394. this._condition = condition;
  25395. }
  25396. // Methods
  25397. Action.prototype._prepare = function () {
  25398. };
  25399. Action.prototype.getTriggerParameter = function () {
  25400. return this._triggerParameter;
  25401. };
  25402. Action.prototype._executeCurrent = function (evt) {
  25403. if (this._nextActiveAction._condition) {
  25404. var condition = this._nextActiveAction._condition;
  25405. var currentRenderId = this._actionManager.getScene().getRenderId();
  25406. // We cache the current evaluation for the current frame
  25407. if (condition._evaluationId === currentRenderId) {
  25408. if (!condition._currentResult) {
  25409. return;
  25410. }
  25411. }
  25412. else {
  25413. condition._evaluationId = currentRenderId;
  25414. if (!condition.isValid()) {
  25415. condition._currentResult = false;
  25416. return;
  25417. }
  25418. condition._currentResult = true;
  25419. }
  25420. }
  25421. this._nextActiveAction.execute(evt);
  25422. this.skipToNextActiveAction();
  25423. };
  25424. Action.prototype.execute = function (evt) {
  25425. };
  25426. Action.prototype.skipToNextActiveAction = function () {
  25427. if (this._nextActiveAction._child) {
  25428. if (!this._nextActiveAction._child._actionManager) {
  25429. this._nextActiveAction._child._actionManager = this._actionManager;
  25430. }
  25431. this._nextActiveAction = this._nextActiveAction._child;
  25432. }
  25433. else {
  25434. this._nextActiveAction = this;
  25435. }
  25436. };
  25437. Action.prototype.then = function (action) {
  25438. this._child = action;
  25439. action._actionManager = this._actionManager;
  25440. action._prepare();
  25441. return action;
  25442. };
  25443. Action.prototype._getProperty = function (propertyPath) {
  25444. return this._actionManager._getProperty(propertyPath);
  25445. };
  25446. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25447. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25448. };
  25449. return Action;
  25450. })();
  25451. BABYLON.Action = Action;
  25452. })(BABYLON || (BABYLON = {}));
  25453. var BABYLON;
  25454. (function (BABYLON) {
  25455. /**
  25456. * ActionEvent is the event beint sent when an action is triggered.
  25457. */
  25458. var ActionEvent = (function () {
  25459. /**
  25460. * @constructor
  25461. * @param source The mesh or sprite that triggered the action.
  25462. * @param pointerX The X mouse cursor position at the time of the event
  25463. * @param pointerY The Y mouse cursor position at the time of the event
  25464. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25465. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25466. */
  25467. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25468. this.source = source;
  25469. this.pointerX = pointerX;
  25470. this.pointerY = pointerY;
  25471. this.meshUnderPointer = meshUnderPointer;
  25472. this.sourceEvent = sourceEvent;
  25473. this.additionalData = additionalData;
  25474. }
  25475. /**
  25476. * Helper function to auto-create an ActionEvent from a source mesh.
  25477. * @param source The source mesh that triggered the event
  25478. * @param evt {Event} The original (browser) event
  25479. */
  25480. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25481. var scene = source.getScene();
  25482. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25483. };
  25484. /**
  25485. * Helper function to auto-create an ActionEvent from a source mesh.
  25486. * @param source The source sprite that triggered the event
  25487. * @param scene Scene associated with the sprite
  25488. * @param evt {Event} The original (browser) event
  25489. */
  25490. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25491. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25492. };
  25493. /**
  25494. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25495. * @param scene the scene where the event occurred
  25496. * @param evt {Event} The original (browser) event
  25497. */
  25498. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25499. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25500. };
  25501. return ActionEvent;
  25502. })();
  25503. BABYLON.ActionEvent = ActionEvent;
  25504. /**
  25505. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25506. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25507. */
  25508. var ActionManager = (function () {
  25509. function ActionManager(scene) {
  25510. // Members
  25511. this.actions = new Array();
  25512. this._scene = scene;
  25513. scene._actionManagers.push(this);
  25514. }
  25515. Object.defineProperty(ActionManager, "NothingTrigger", {
  25516. get: function () {
  25517. return ActionManager._NothingTrigger;
  25518. },
  25519. enumerable: true,
  25520. configurable: true
  25521. });
  25522. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25523. get: function () {
  25524. return ActionManager._OnPickTrigger;
  25525. },
  25526. enumerable: true,
  25527. configurable: true
  25528. });
  25529. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25530. get: function () {
  25531. return ActionManager._OnLeftPickTrigger;
  25532. },
  25533. enumerable: true,
  25534. configurable: true
  25535. });
  25536. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25537. get: function () {
  25538. return ActionManager._OnRightPickTrigger;
  25539. },
  25540. enumerable: true,
  25541. configurable: true
  25542. });
  25543. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25544. get: function () {
  25545. return ActionManager._OnCenterPickTrigger;
  25546. },
  25547. enumerable: true,
  25548. configurable: true
  25549. });
  25550. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  25551. get: function () {
  25552. return ActionManager._OnPickDownTrigger;
  25553. },
  25554. enumerable: true,
  25555. configurable: true
  25556. });
  25557. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25558. get: function () {
  25559. return ActionManager._OnPickUpTrigger;
  25560. },
  25561. enumerable: true,
  25562. configurable: true
  25563. });
  25564. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  25565. get: function () {
  25566. return ActionManager._OnLongPressTrigger;
  25567. },
  25568. enumerable: true,
  25569. configurable: true
  25570. });
  25571. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25572. get: function () {
  25573. return ActionManager._OnPointerOverTrigger;
  25574. },
  25575. enumerable: true,
  25576. configurable: true
  25577. });
  25578. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25579. get: function () {
  25580. return ActionManager._OnPointerOutTrigger;
  25581. },
  25582. enumerable: true,
  25583. configurable: true
  25584. });
  25585. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25586. get: function () {
  25587. return ActionManager._OnEveryFrameTrigger;
  25588. },
  25589. enumerable: true,
  25590. configurable: true
  25591. });
  25592. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25593. get: function () {
  25594. return ActionManager._OnIntersectionEnterTrigger;
  25595. },
  25596. enumerable: true,
  25597. configurable: true
  25598. });
  25599. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25600. get: function () {
  25601. return ActionManager._OnIntersectionExitTrigger;
  25602. },
  25603. enumerable: true,
  25604. configurable: true
  25605. });
  25606. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25607. get: function () {
  25608. return ActionManager._OnKeyDownTrigger;
  25609. },
  25610. enumerable: true,
  25611. configurable: true
  25612. });
  25613. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25614. get: function () {
  25615. return ActionManager._OnKeyUpTrigger;
  25616. },
  25617. enumerable: true,
  25618. configurable: true
  25619. });
  25620. // Methods
  25621. ActionManager.prototype.dispose = function () {
  25622. var index = this._scene._actionManagers.indexOf(this);
  25623. if (index > -1) {
  25624. this._scene._actionManagers.splice(index, 1);
  25625. }
  25626. };
  25627. ActionManager.prototype.getScene = function () {
  25628. return this._scene;
  25629. };
  25630. /**
  25631. * Does this action manager handles actions of any of the given triggers
  25632. * @param {number[]} triggers - the triggers to be tested
  25633. * @return {boolean} whether one (or more) of the triggers is handeled
  25634. */
  25635. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25636. for (var index = 0; index < this.actions.length; index++) {
  25637. var action = this.actions[index];
  25638. if (triggers.indexOf(action.trigger) > -1) {
  25639. return true;
  25640. }
  25641. }
  25642. return false;
  25643. };
  25644. /**
  25645. * Does this action manager handles actions of a given trigger
  25646. * @param {number} trigger - the trigger to be tested
  25647. * @return {boolean} whether the trigger is handeled
  25648. */
  25649. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25650. for (var index = 0; index < this.actions.length; index++) {
  25651. var action = this.actions[index];
  25652. if (action.trigger === trigger) {
  25653. return true;
  25654. }
  25655. }
  25656. return false;
  25657. };
  25658. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25659. /**
  25660. * Does this action manager has pointer triggers
  25661. * @return {boolean} whether or not it has pointer triggers
  25662. */
  25663. get: function () {
  25664. for (var index = 0; index < this.actions.length; index++) {
  25665. var action = this.actions[index];
  25666. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25667. return true;
  25668. }
  25669. }
  25670. return false;
  25671. },
  25672. enumerable: true,
  25673. configurable: true
  25674. });
  25675. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25676. /**
  25677. * Does this action manager has pick triggers
  25678. * @return {boolean} whether or not it has pick triggers
  25679. */
  25680. get: function () {
  25681. for (var index = 0; index < this.actions.length; index++) {
  25682. var action = this.actions[index];
  25683. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  25684. return true;
  25685. }
  25686. }
  25687. return false;
  25688. },
  25689. enumerable: true,
  25690. configurable: true
  25691. });
  25692. /**
  25693. * Registers an action to this action manager
  25694. * @param {BABYLON.Action} action - the action to be registered
  25695. * @return {BABYLON.Action} the action amended (prepared) after registration
  25696. */
  25697. ActionManager.prototype.registerAction = function (action) {
  25698. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25699. if (this.getScene().actionManager !== this) {
  25700. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25701. return null;
  25702. }
  25703. }
  25704. this.actions.push(action);
  25705. action._actionManager = this;
  25706. action._prepare();
  25707. return action;
  25708. };
  25709. /**
  25710. * Process a specific trigger
  25711. * @param {number} trigger - the trigger to process
  25712. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25713. */
  25714. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25715. for (var index = 0; index < this.actions.length; index++) {
  25716. var action = this.actions[index];
  25717. if (action.trigger === trigger) {
  25718. if (trigger === ActionManager.OnKeyUpTrigger
  25719. || trigger === ActionManager.OnKeyDownTrigger) {
  25720. var parameter = action.getTriggerParameter();
  25721. if (parameter) {
  25722. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25723. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25724. if (actualkey !== parameter.toLowerCase()) {
  25725. continue;
  25726. }
  25727. }
  25728. }
  25729. action._executeCurrent(evt);
  25730. }
  25731. }
  25732. };
  25733. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25734. var properties = propertyPath.split(".");
  25735. for (var index = 0; index < properties.length - 1; index++) {
  25736. target = target[properties[index]];
  25737. }
  25738. return target;
  25739. };
  25740. ActionManager.prototype._getProperty = function (propertyPath) {
  25741. var properties = propertyPath.split(".");
  25742. return properties[properties.length - 1];
  25743. };
  25744. ActionManager.Parse = function (parsedActions, object, scene) {
  25745. var actionManager = new BABYLON.ActionManager(scene);
  25746. if (object === null)
  25747. scene.actionManager = actionManager;
  25748. else
  25749. object.actionManager = actionManager;
  25750. // instanciate a new object
  25751. var instanciate = function (name, params) {
  25752. var newInstance = Object.create(BABYLON[name].prototype);
  25753. newInstance.constructor.apply(newInstance, params);
  25754. return newInstance;
  25755. };
  25756. var parseParameter = function (name, value, target, propertyPath) {
  25757. if (propertyPath === null) {
  25758. // String, boolean or float
  25759. var floatValue = parseFloat(value);
  25760. if (value === "true" || value === "false")
  25761. return value === "true";
  25762. else
  25763. return isNaN(floatValue) ? value : floatValue;
  25764. }
  25765. var effectiveTarget = propertyPath.split(".");
  25766. var values = value.split(",");
  25767. // Get effective Target
  25768. for (var i = 0; i < effectiveTarget.length; i++) {
  25769. target = target[effectiveTarget[i]];
  25770. }
  25771. // Return appropriate value with its type
  25772. if (typeof (target) === "boolean")
  25773. return values[0] === "true";
  25774. if (typeof (target) === "string")
  25775. return values[0];
  25776. // Parameters with multiple values such as Vector3 etc.
  25777. var split = new Array();
  25778. for (var i = 0; i < values.length; i++)
  25779. split.push(parseFloat(values[i]));
  25780. if (target instanceof BABYLON.Vector3)
  25781. return BABYLON.Vector3.FromArray(split);
  25782. if (target instanceof BABYLON.Vector4)
  25783. return BABYLON.Vector4.FromArray(split);
  25784. if (target instanceof BABYLON.Color3)
  25785. return BABYLON.Color3.FromArray(split);
  25786. if (target instanceof BABYLON.Color4)
  25787. return BABYLON.Color4.FromArray(split);
  25788. return parseFloat(values[0]);
  25789. };
  25790. // traverse graph per trigger
  25791. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25792. if (combineArray === void 0) { combineArray = null; }
  25793. if (parsedAction.detached)
  25794. return;
  25795. var parameters = new Array();
  25796. var target = null;
  25797. var propertyPath = null;
  25798. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25799. // Parameters
  25800. if (parsedAction.type === 2)
  25801. parameters.push(actionManager);
  25802. else
  25803. parameters.push(trigger);
  25804. if (combine) {
  25805. var actions = new Array();
  25806. for (var j = 0; j < parsedAction.combine.length; j++) {
  25807. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25808. }
  25809. parameters.push(actions);
  25810. }
  25811. else {
  25812. for (var i = 0; i < parsedAction.properties.length; i++) {
  25813. var value = parsedAction.properties[i].value;
  25814. var name = parsedAction.properties[i].name;
  25815. var targetType = parsedAction.properties[i].targetType;
  25816. if (name === "target")
  25817. if (targetType !== null && targetType === "SceneProperties")
  25818. value = target = scene;
  25819. else
  25820. value = target = scene.getNodeByName(value);
  25821. else if (name === "parent")
  25822. value = scene.getNodeByName(value);
  25823. else if (name === "sound")
  25824. value = scene.getSoundByName(value);
  25825. else if (name !== "propertyPath") {
  25826. if (parsedAction.type === 2 && name === "operator")
  25827. value = BABYLON.ValueCondition[value];
  25828. else
  25829. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25830. }
  25831. else {
  25832. propertyPath = value;
  25833. }
  25834. parameters.push(value);
  25835. }
  25836. }
  25837. if (combineArray === null) {
  25838. parameters.push(condition);
  25839. }
  25840. else {
  25841. parameters.push(null);
  25842. }
  25843. // If interpolate value action
  25844. if (parsedAction.name === "InterpolateValueAction") {
  25845. var param = parameters[parameters.length - 2];
  25846. parameters[parameters.length - 1] = param;
  25847. parameters[parameters.length - 2] = condition;
  25848. }
  25849. // Action or condition(s) and not CombineAction
  25850. var newAction = instanciate(parsedAction.name, parameters);
  25851. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25852. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25853. if (action)
  25854. action.then(nothing);
  25855. else
  25856. actionManager.registerAction(nothing);
  25857. action = nothing;
  25858. }
  25859. if (combineArray === null) {
  25860. if (newAction instanceof BABYLON.Condition) {
  25861. condition = newAction;
  25862. newAction = action;
  25863. }
  25864. else {
  25865. condition = null;
  25866. if (action)
  25867. action.then(newAction);
  25868. else
  25869. actionManager.registerAction(newAction);
  25870. }
  25871. }
  25872. else {
  25873. combineArray.push(newAction);
  25874. }
  25875. for (var i = 0; i < parsedAction.children.length; i++)
  25876. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25877. };
  25878. // triggers
  25879. for (var i = 0; i < parsedActions.children.length; i++) {
  25880. var triggerParams;
  25881. var trigger = parsedActions.children[i];
  25882. if (trigger.properties.length > 0) {
  25883. var param = trigger.properties[0].value;
  25884. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25885. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25886. }
  25887. else
  25888. triggerParams = BABYLON.ActionManager[trigger.name];
  25889. for (var j = 0; j < trigger.children.length; j++) {
  25890. if (!trigger.detached)
  25891. traverse(trigger.children[j], triggerParams, null, null);
  25892. }
  25893. }
  25894. };
  25895. // Statics
  25896. ActionManager._NothingTrigger = 0;
  25897. ActionManager._OnPickTrigger = 1;
  25898. ActionManager._OnLeftPickTrigger = 2;
  25899. ActionManager._OnRightPickTrigger = 3;
  25900. ActionManager._OnCenterPickTrigger = 4;
  25901. ActionManager._OnPickDownTrigger = 5;
  25902. ActionManager._OnPickUpTrigger = 6;
  25903. ActionManager._OnLongPressTrigger = 7;
  25904. ActionManager._OnPointerOverTrigger = 8;
  25905. ActionManager._OnPointerOutTrigger = 9;
  25906. ActionManager._OnEveryFrameTrigger = 10;
  25907. ActionManager._OnIntersectionEnterTrigger = 11;
  25908. ActionManager._OnIntersectionExitTrigger = 12;
  25909. ActionManager._OnKeyDownTrigger = 13;
  25910. ActionManager._OnKeyUpTrigger = 14;
  25911. ActionManager.DragMovementThreshold = 10; // in pixels
  25912. ActionManager.LongPressDelay = 500; // in milliseconds
  25913. return ActionManager;
  25914. })();
  25915. BABYLON.ActionManager = ActionManager;
  25916. })(BABYLON || (BABYLON = {}));
  25917. var BABYLON;
  25918. (function (BABYLON) {
  25919. var InterpolateValueAction = (function (_super) {
  25920. __extends(InterpolateValueAction, _super);
  25921. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25922. if (duration === void 0) { duration = 1000; }
  25923. _super.call(this, triggerOptions, condition);
  25924. this.propertyPath = propertyPath;
  25925. this.value = value;
  25926. this.duration = duration;
  25927. this.stopOtherAnimations = stopOtherAnimations;
  25928. this.onInterpolationDone = onInterpolationDone;
  25929. this._target = target;
  25930. }
  25931. InterpolateValueAction.prototype._prepare = function () {
  25932. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25933. this._property = this._getProperty(this.propertyPath);
  25934. };
  25935. InterpolateValueAction.prototype.execute = function () {
  25936. var scene = this._actionManager.getScene();
  25937. var keys = [
  25938. {
  25939. frame: 0,
  25940. value: this._target[this._property]
  25941. }, {
  25942. frame: 100,
  25943. value: this.value
  25944. }
  25945. ];
  25946. var dataType;
  25947. if (typeof this.value === "number") {
  25948. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25949. }
  25950. else if (this.value instanceof BABYLON.Color3) {
  25951. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25952. }
  25953. else if (this.value instanceof BABYLON.Vector3) {
  25954. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25955. }
  25956. else if (this.value instanceof BABYLON.Matrix) {
  25957. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25958. }
  25959. else if (this.value instanceof BABYLON.Quaternion) {
  25960. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25961. }
  25962. else {
  25963. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25964. return;
  25965. }
  25966. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25967. animation.setKeys(keys);
  25968. if (this.stopOtherAnimations) {
  25969. scene.stopAnimation(this._target);
  25970. }
  25971. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25972. };
  25973. return InterpolateValueAction;
  25974. })(BABYLON.Action);
  25975. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25976. })(BABYLON || (BABYLON = {}));
  25977. var BABYLON;
  25978. (function (BABYLON) {
  25979. var SwitchBooleanAction = (function (_super) {
  25980. __extends(SwitchBooleanAction, _super);
  25981. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25982. _super.call(this, triggerOptions, condition);
  25983. this.propertyPath = propertyPath;
  25984. this._target = target;
  25985. }
  25986. SwitchBooleanAction.prototype._prepare = function () {
  25987. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25988. this._property = this._getProperty(this.propertyPath);
  25989. };
  25990. SwitchBooleanAction.prototype.execute = function () {
  25991. this._target[this._property] = !this._target[this._property];
  25992. };
  25993. return SwitchBooleanAction;
  25994. })(BABYLON.Action);
  25995. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25996. var SetStateAction = (function (_super) {
  25997. __extends(SetStateAction, _super);
  25998. function SetStateAction(triggerOptions, target, value, condition) {
  25999. _super.call(this, triggerOptions, condition);
  26000. this.value = value;
  26001. this._target = target;
  26002. }
  26003. SetStateAction.prototype.execute = function () {
  26004. this._target.state = this.value;
  26005. };
  26006. return SetStateAction;
  26007. })(BABYLON.Action);
  26008. BABYLON.SetStateAction = SetStateAction;
  26009. var SetValueAction = (function (_super) {
  26010. __extends(SetValueAction, _super);
  26011. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26012. _super.call(this, triggerOptions, condition);
  26013. this.propertyPath = propertyPath;
  26014. this.value = value;
  26015. this._target = target;
  26016. }
  26017. SetValueAction.prototype._prepare = function () {
  26018. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26019. this._property = this._getProperty(this.propertyPath);
  26020. };
  26021. SetValueAction.prototype.execute = function () {
  26022. this._target[this._property] = this.value;
  26023. };
  26024. return SetValueAction;
  26025. })(BABYLON.Action);
  26026. BABYLON.SetValueAction = SetValueAction;
  26027. var IncrementValueAction = (function (_super) {
  26028. __extends(IncrementValueAction, _super);
  26029. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26030. _super.call(this, triggerOptions, condition);
  26031. this.propertyPath = propertyPath;
  26032. this.value = value;
  26033. this._target = target;
  26034. }
  26035. IncrementValueAction.prototype._prepare = function () {
  26036. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26037. this._property = this._getProperty(this.propertyPath);
  26038. if (typeof this._target[this._property] !== "number") {
  26039. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26040. }
  26041. };
  26042. IncrementValueAction.prototype.execute = function () {
  26043. this._target[this._property] += this.value;
  26044. };
  26045. return IncrementValueAction;
  26046. })(BABYLON.Action);
  26047. BABYLON.IncrementValueAction = IncrementValueAction;
  26048. var PlayAnimationAction = (function (_super) {
  26049. __extends(PlayAnimationAction, _super);
  26050. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26051. _super.call(this, triggerOptions, condition);
  26052. this.from = from;
  26053. this.to = to;
  26054. this.loop = loop;
  26055. this._target = target;
  26056. }
  26057. PlayAnimationAction.prototype._prepare = function () {
  26058. };
  26059. PlayAnimationAction.prototype.execute = function () {
  26060. var scene = this._actionManager.getScene();
  26061. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26062. };
  26063. return PlayAnimationAction;
  26064. })(BABYLON.Action);
  26065. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26066. var StopAnimationAction = (function (_super) {
  26067. __extends(StopAnimationAction, _super);
  26068. function StopAnimationAction(triggerOptions, target, condition) {
  26069. _super.call(this, triggerOptions, condition);
  26070. this._target = target;
  26071. }
  26072. StopAnimationAction.prototype._prepare = function () {
  26073. };
  26074. StopAnimationAction.prototype.execute = function () {
  26075. var scene = this._actionManager.getScene();
  26076. scene.stopAnimation(this._target);
  26077. };
  26078. return StopAnimationAction;
  26079. })(BABYLON.Action);
  26080. BABYLON.StopAnimationAction = StopAnimationAction;
  26081. var DoNothingAction = (function (_super) {
  26082. __extends(DoNothingAction, _super);
  26083. function DoNothingAction(triggerOptions, condition) {
  26084. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26085. _super.call(this, triggerOptions, condition);
  26086. }
  26087. DoNothingAction.prototype.execute = function () {
  26088. };
  26089. return DoNothingAction;
  26090. })(BABYLON.Action);
  26091. BABYLON.DoNothingAction = DoNothingAction;
  26092. var CombineAction = (function (_super) {
  26093. __extends(CombineAction, _super);
  26094. function CombineAction(triggerOptions, children, condition) {
  26095. _super.call(this, triggerOptions, condition);
  26096. this.children = children;
  26097. }
  26098. CombineAction.prototype._prepare = function () {
  26099. for (var index = 0; index < this.children.length; index++) {
  26100. this.children[index]._actionManager = this._actionManager;
  26101. this.children[index]._prepare();
  26102. }
  26103. };
  26104. CombineAction.prototype.execute = function (evt) {
  26105. for (var index = 0; index < this.children.length; index++) {
  26106. this.children[index].execute(evt);
  26107. }
  26108. };
  26109. return CombineAction;
  26110. })(BABYLON.Action);
  26111. BABYLON.CombineAction = CombineAction;
  26112. var ExecuteCodeAction = (function (_super) {
  26113. __extends(ExecuteCodeAction, _super);
  26114. function ExecuteCodeAction(triggerOptions, func, condition) {
  26115. _super.call(this, triggerOptions, condition);
  26116. this.func = func;
  26117. }
  26118. ExecuteCodeAction.prototype.execute = function (evt) {
  26119. this.func(evt);
  26120. };
  26121. return ExecuteCodeAction;
  26122. })(BABYLON.Action);
  26123. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26124. var SetParentAction = (function (_super) {
  26125. __extends(SetParentAction, _super);
  26126. function SetParentAction(triggerOptions, target, parent, condition) {
  26127. _super.call(this, triggerOptions, condition);
  26128. this._target = target;
  26129. this._parent = parent;
  26130. }
  26131. SetParentAction.prototype._prepare = function () {
  26132. };
  26133. SetParentAction.prototype.execute = function () {
  26134. if (this._target.parent === this._parent) {
  26135. return;
  26136. }
  26137. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26138. invertParentWorldMatrix.invert();
  26139. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26140. this._target.parent = this._parent;
  26141. };
  26142. return SetParentAction;
  26143. })(BABYLON.Action);
  26144. BABYLON.SetParentAction = SetParentAction;
  26145. var PlaySoundAction = (function (_super) {
  26146. __extends(PlaySoundAction, _super);
  26147. function PlaySoundAction(triggerOptions, sound, condition) {
  26148. _super.call(this, triggerOptions, condition);
  26149. this._sound = sound;
  26150. }
  26151. PlaySoundAction.prototype._prepare = function () {
  26152. };
  26153. PlaySoundAction.prototype.execute = function () {
  26154. if (this._sound !== undefined)
  26155. this._sound.play();
  26156. };
  26157. return PlaySoundAction;
  26158. })(BABYLON.Action);
  26159. BABYLON.PlaySoundAction = PlaySoundAction;
  26160. var StopSoundAction = (function (_super) {
  26161. __extends(StopSoundAction, _super);
  26162. function StopSoundAction(triggerOptions, sound, condition) {
  26163. _super.call(this, triggerOptions, condition);
  26164. this._sound = sound;
  26165. }
  26166. StopSoundAction.prototype._prepare = function () {
  26167. };
  26168. StopSoundAction.prototype.execute = function () {
  26169. if (this._sound !== undefined)
  26170. this._sound.stop();
  26171. };
  26172. return StopSoundAction;
  26173. })(BABYLON.Action);
  26174. BABYLON.StopSoundAction = StopSoundAction;
  26175. })(BABYLON || (BABYLON = {}));
  26176. var BABYLON;
  26177. (function (BABYLON) {
  26178. var Geometry = (function () {
  26179. function Geometry(id, scene, vertexData, updatable, mesh) {
  26180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26181. this._totalVertices = 0;
  26182. this._isDisposed = false;
  26183. this.id = id;
  26184. this._engine = scene.getEngine();
  26185. this._meshes = [];
  26186. this._scene = scene;
  26187. //Init vertex buffer cache
  26188. this._vertexBuffers = {};
  26189. this._indices = [];
  26190. // vertexData
  26191. if (vertexData) {
  26192. this.setAllVerticesData(vertexData, updatable);
  26193. }
  26194. else {
  26195. this._totalVertices = 0;
  26196. this._indices = [];
  26197. }
  26198. // applyToMesh
  26199. if (mesh) {
  26200. this.applyToMesh(mesh);
  26201. mesh.computeWorldMatrix(true);
  26202. }
  26203. }
  26204. Object.defineProperty(Geometry.prototype, "extend", {
  26205. get: function () {
  26206. return this._extend;
  26207. },
  26208. enumerable: true,
  26209. configurable: true
  26210. });
  26211. Geometry.prototype.getScene = function () {
  26212. return this._scene;
  26213. };
  26214. Geometry.prototype.getEngine = function () {
  26215. return this._engine;
  26216. };
  26217. Geometry.prototype.isReady = function () {
  26218. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26219. };
  26220. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26221. vertexData.applyToGeometry(this, updatable);
  26222. this.notifyUpdate();
  26223. };
  26224. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26225. if (this._vertexBuffers[kind]) {
  26226. this._vertexBuffers[kind].dispose();
  26227. }
  26228. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26229. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26230. stride = this._vertexBuffers[kind].getStrideSize();
  26231. this._totalVertices = data.length / stride;
  26232. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26233. var meshes = this._meshes;
  26234. var numOfMeshes = meshes.length;
  26235. for (var index = 0; index < numOfMeshes; index++) {
  26236. var mesh = meshes[index];
  26237. mesh._resetPointsArrayCache();
  26238. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26239. mesh._createGlobalSubMesh();
  26240. mesh.computeWorldMatrix(true);
  26241. }
  26242. }
  26243. this.notifyUpdate(kind);
  26244. };
  26245. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26246. var vertexBuffer = this.getVertexBuffer(kind);
  26247. if (!vertexBuffer) {
  26248. return;
  26249. }
  26250. vertexBuffer.updateDirectly(data, offset);
  26251. this.notifyUpdate(kind);
  26252. };
  26253. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26254. var vertexBuffer = this.getVertexBuffer(kind);
  26255. if (!vertexBuffer) {
  26256. return;
  26257. }
  26258. vertexBuffer.update(data);
  26259. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26260. var stride = vertexBuffer.getStrideSize();
  26261. this._totalVertices = data.length / stride;
  26262. if (updateExtends) {
  26263. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26264. }
  26265. var meshes = this._meshes;
  26266. var numOfMeshes = meshes.length;
  26267. for (var index = 0; index < numOfMeshes; index++) {
  26268. var mesh = meshes[index];
  26269. mesh._resetPointsArrayCache();
  26270. if (updateExtends) {
  26271. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26272. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26273. var subMesh = mesh.subMeshes[subIndex];
  26274. subMesh.refreshBoundingInfo();
  26275. }
  26276. }
  26277. }
  26278. }
  26279. this.notifyUpdate(kind);
  26280. };
  26281. Geometry.prototype.getTotalVertices = function () {
  26282. if (!this.isReady()) {
  26283. return 0;
  26284. }
  26285. return this._totalVertices;
  26286. };
  26287. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26288. var vertexBuffer = this.getVertexBuffer(kind);
  26289. if (!vertexBuffer) {
  26290. return null;
  26291. }
  26292. var orig = vertexBuffer.getData();
  26293. if (!copyWhenShared || this._meshes.length === 1) {
  26294. return orig;
  26295. }
  26296. else {
  26297. var len = orig.length;
  26298. var copy = [];
  26299. for (var i = 0; i < len; i++) {
  26300. copy.push(orig[i]);
  26301. }
  26302. return copy;
  26303. }
  26304. };
  26305. Geometry.prototype.getVertexBuffer = function (kind) {
  26306. if (!this.isReady()) {
  26307. return null;
  26308. }
  26309. return this._vertexBuffers[kind];
  26310. };
  26311. Geometry.prototype.getVertexBuffers = function () {
  26312. if (!this.isReady()) {
  26313. return null;
  26314. }
  26315. return this._vertexBuffers;
  26316. };
  26317. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26318. if (!this._vertexBuffers) {
  26319. if (this._delayInfo) {
  26320. return this._delayInfo.indexOf(kind) !== -1;
  26321. }
  26322. return false;
  26323. }
  26324. return this._vertexBuffers[kind] !== undefined;
  26325. };
  26326. Geometry.prototype.getVerticesDataKinds = function () {
  26327. var result = [];
  26328. var kind;
  26329. if (!this._vertexBuffers && this._delayInfo) {
  26330. for (kind in this._delayInfo) {
  26331. result.push(kind);
  26332. }
  26333. }
  26334. else {
  26335. for (kind in this._vertexBuffers) {
  26336. result.push(kind);
  26337. }
  26338. }
  26339. return result;
  26340. };
  26341. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26342. if (this._indexBuffer) {
  26343. this._engine._releaseBuffer(this._indexBuffer);
  26344. }
  26345. this._indices = indices;
  26346. if (this._meshes.length !== 0 && this._indices) {
  26347. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26348. }
  26349. if (totalVertices !== undefined) {
  26350. this._totalVertices = totalVertices;
  26351. }
  26352. var meshes = this._meshes;
  26353. var numOfMeshes = meshes.length;
  26354. for (var index = 0; index < numOfMeshes; index++) {
  26355. meshes[index]._createGlobalSubMesh();
  26356. }
  26357. this.notifyUpdate();
  26358. };
  26359. Geometry.prototype.getTotalIndices = function () {
  26360. if (!this.isReady()) {
  26361. return 0;
  26362. }
  26363. return this._indices.length;
  26364. };
  26365. Geometry.prototype.getIndices = function (copyWhenShared) {
  26366. if (!this.isReady()) {
  26367. return null;
  26368. }
  26369. var orig = this._indices;
  26370. if (!copyWhenShared || this._meshes.length === 1) {
  26371. return orig;
  26372. }
  26373. else {
  26374. var len = orig.length;
  26375. var copy = [];
  26376. for (var i = 0; i < len; i++) {
  26377. copy.push(orig[i]);
  26378. }
  26379. return copy;
  26380. }
  26381. };
  26382. Geometry.prototype.getIndexBuffer = function () {
  26383. if (!this.isReady()) {
  26384. return null;
  26385. }
  26386. return this._indexBuffer;
  26387. };
  26388. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26389. var meshes = this._meshes;
  26390. var index = meshes.indexOf(mesh);
  26391. if (index === -1) {
  26392. return;
  26393. }
  26394. for (var kind in this._vertexBuffers) {
  26395. this._vertexBuffers[kind].dispose();
  26396. }
  26397. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26398. this._indexBuffer = null;
  26399. }
  26400. meshes.splice(index, 1);
  26401. mesh._geometry = null;
  26402. if (meshes.length === 0 && shouldDispose) {
  26403. this.dispose();
  26404. }
  26405. };
  26406. Geometry.prototype.applyToMesh = function (mesh) {
  26407. if (mesh._geometry === this) {
  26408. return;
  26409. }
  26410. var previousGeometry = mesh._geometry;
  26411. if (previousGeometry) {
  26412. previousGeometry.releaseForMesh(mesh);
  26413. }
  26414. var meshes = this._meshes;
  26415. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26416. mesh._geometry = this;
  26417. this._scene.pushGeometry(this);
  26418. meshes.push(mesh);
  26419. if (this.isReady()) {
  26420. this._applyToMesh(mesh);
  26421. }
  26422. else {
  26423. mesh._boundingInfo = this._boundingInfo;
  26424. }
  26425. };
  26426. Geometry.prototype._applyToMesh = function (mesh) {
  26427. var numOfMeshes = this._meshes.length;
  26428. // vertexBuffers
  26429. for (var kind in this._vertexBuffers) {
  26430. if (numOfMeshes === 1) {
  26431. this._vertexBuffers[kind].create();
  26432. }
  26433. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26434. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26435. mesh._resetPointsArrayCache();
  26436. if (!this._extend) {
  26437. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26438. }
  26439. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26440. mesh._createGlobalSubMesh();
  26441. //bounding info was just created again, world matrix should be applied again.
  26442. mesh._updateBoundingInfo();
  26443. }
  26444. }
  26445. // indexBuffer
  26446. if (numOfMeshes === 1 && this._indices) {
  26447. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26448. }
  26449. if (this._indexBuffer) {
  26450. this._indexBuffer.references = numOfMeshes;
  26451. }
  26452. };
  26453. Geometry.prototype.notifyUpdate = function (kind) {
  26454. if (this.onGeometryUpdated) {
  26455. this.onGeometryUpdated(this, kind);
  26456. }
  26457. };
  26458. Geometry.prototype.load = function (scene, onLoaded) {
  26459. var _this = this;
  26460. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26461. return;
  26462. }
  26463. if (this.isReady()) {
  26464. if (onLoaded) {
  26465. onLoaded();
  26466. }
  26467. return;
  26468. }
  26469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26470. scene._addPendingData(this);
  26471. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26472. _this._delayLoadingFunction(JSON.parse(data), _this);
  26473. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26474. _this._delayInfo = [];
  26475. scene._removePendingData(_this);
  26476. var meshes = _this._meshes;
  26477. var numOfMeshes = meshes.length;
  26478. for (var index = 0; index < numOfMeshes; index++) {
  26479. _this._applyToMesh(meshes[index]);
  26480. }
  26481. if (onLoaded) {
  26482. onLoaded();
  26483. }
  26484. }, function () { }, scene.database);
  26485. };
  26486. Geometry.prototype.isDisposed = function () {
  26487. return this._isDisposed;
  26488. };
  26489. Geometry.prototype.dispose = function () {
  26490. var meshes = this._meshes;
  26491. var numOfMeshes = meshes.length;
  26492. var index;
  26493. for (index = 0; index < numOfMeshes; index++) {
  26494. this.releaseForMesh(meshes[index]);
  26495. }
  26496. this._meshes = [];
  26497. for (var kind in this._vertexBuffers) {
  26498. this._vertexBuffers[kind].dispose();
  26499. }
  26500. this._vertexBuffers = [];
  26501. this._totalVertices = 0;
  26502. if (this._indexBuffer) {
  26503. this._engine._releaseBuffer(this._indexBuffer);
  26504. }
  26505. this._indexBuffer = null;
  26506. this._indices = [];
  26507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26508. this.delayLoadingFile = null;
  26509. this._delayLoadingFunction = null;
  26510. this._delayInfo = [];
  26511. this._boundingInfo = null;
  26512. this._scene.removeGeometry(this);
  26513. this._isDisposed = true;
  26514. };
  26515. Geometry.prototype.copy = function (id) {
  26516. var vertexData = new BABYLON.VertexData();
  26517. vertexData.indices = [];
  26518. var indices = this.getIndices();
  26519. for (var index = 0; index < indices.length; index++) {
  26520. vertexData.indices.push(indices[index]);
  26521. }
  26522. var updatable = false;
  26523. var stopChecking = false;
  26524. var kind;
  26525. for (kind in this._vertexBuffers) {
  26526. // using slice() to make a copy of the array and not just reference it
  26527. var data = this.getVerticesData(kind);
  26528. if (data instanceof Float32Array) {
  26529. vertexData.set(new Float32Array(data), kind);
  26530. }
  26531. else {
  26532. vertexData.set(data.slice(0), kind);
  26533. }
  26534. if (!stopChecking) {
  26535. updatable = this.getVertexBuffer(kind).isUpdatable();
  26536. stopChecking = !updatable;
  26537. }
  26538. }
  26539. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26540. geometry.delayLoadState = this.delayLoadState;
  26541. geometry.delayLoadingFile = this.delayLoadingFile;
  26542. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26543. for (kind in this._delayInfo) {
  26544. geometry._delayInfo = geometry._delayInfo || [];
  26545. geometry._delayInfo.push(kind);
  26546. }
  26547. // Bounding info
  26548. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26549. return geometry;
  26550. };
  26551. Geometry.prototype.serialize = function () {
  26552. var serializationObject = {};
  26553. serializationObject.id = this.id;
  26554. if (BABYLON.Tags.HasTags(this)) {
  26555. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26556. }
  26557. return serializationObject;
  26558. };
  26559. Geometry.prototype.serializeVerticeData = function () {
  26560. var serializationObject = this.serialize();
  26561. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26562. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26563. }
  26564. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26565. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26566. }
  26567. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26568. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26569. }
  26570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26571. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26572. }
  26573. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26574. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26575. }
  26576. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26577. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26578. }
  26579. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26580. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26581. }
  26582. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26583. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26584. }
  26585. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26586. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26587. }
  26588. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26589. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26590. serializationObject.matricesIndices._isExpanded = true;
  26591. }
  26592. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26593. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26594. }
  26595. serializationObject.indices = this.getIndices();
  26596. return serializationObject;
  26597. };
  26598. // Statics
  26599. Geometry.ExtractFromMesh = function (mesh, id) {
  26600. var geometry = mesh._geometry;
  26601. if (!geometry) {
  26602. return null;
  26603. }
  26604. return geometry.copy(id);
  26605. };
  26606. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26607. // be aware Math.random() could cause collisions
  26608. Geometry.RandomId = function () {
  26609. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26610. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26611. return v.toString(16);
  26612. });
  26613. };
  26614. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26615. var scene = mesh.getScene();
  26616. // Geometry
  26617. var geometryId = parsedGeometry.geometryId;
  26618. if (geometryId) {
  26619. var geometry = scene.getGeometryByID(geometryId);
  26620. if (geometry) {
  26621. geometry.applyToMesh(mesh);
  26622. }
  26623. }
  26624. else if (parsedGeometry instanceof ArrayBuffer) {
  26625. var binaryInfo = mesh._binaryInfo;
  26626. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26627. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26628. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26629. }
  26630. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26631. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26632. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26633. }
  26634. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26635. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26636. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26637. }
  26638. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26639. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26640. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26641. }
  26642. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26643. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26644. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26645. }
  26646. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26647. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26648. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26649. }
  26650. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26651. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26652. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26653. }
  26654. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26655. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26656. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26657. }
  26658. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26659. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26660. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26661. }
  26662. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26663. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26664. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26665. }
  26666. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26667. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26669. }
  26670. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26671. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26672. mesh.setIndices(indicesData);
  26673. }
  26674. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26675. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26676. mesh.subMeshes = [];
  26677. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26678. var materialIndex = subMeshesData[(i * 5) + 0];
  26679. var verticesStart = subMeshesData[(i * 5) + 1];
  26680. var verticesCount = subMeshesData[(i * 5) + 2];
  26681. var indexStart = subMeshesData[(i * 5) + 3];
  26682. var indexCount = subMeshesData[(i * 5) + 4];
  26683. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26684. }
  26685. }
  26686. }
  26687. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26688. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26690. if (parsedGeometry.uvs) {
  26691. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26692. }
  26693. if (parsedGeometry.uvs2) {
  26694. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26695. }
  26696. if (parsedGeometry.uvs3) {
  26697. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26698. }
  26699. if (parsedGeometry.uvs4) {
  26700. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26701. }
  26702. if (parsedGeometry.uvs5) {
  26703. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26704. }
  26705. if (parsedGeometry.uvs6) {
  26706. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26707. }
  26708. if (parsedGeometry.colors) {
  26709. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26710. }
  26711. if (parsedGeometry.matricesIndices) {
  26712. if (!parsedGeometry.matricesIndices._isExpanded) {
  26713. var floatIndices = [];
  26714. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26715. var matricesIndex = parsedGeometry.matricesIndices[i];
  26716. floatIndices.push(matricesIndex & 0x000000FF);
  26717. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26718. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26719. floatIndices.push(matricesIndex >> 24);
  26720. }
  26721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26722. }
  26723. else {
  26724. delete parsedGeometry.matricesIndices._isExpanded;
  26725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26726. }
  26727. }
  26728. if (parsedGeometry.matricesIndicesExtra) {
  26729. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26730. var floatIndices = [];
  26731. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26732. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26733. floatIndices.push(matricesIndex & 0x000000FF);
  26734. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26735. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26736. floatIndices.push(matricesIndex >> 24);
  26737. }
  26738. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26739. }
  26740. else {
  26741. delete parsedGeometry.matricesIndices._isExpanded;
  26742. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26743. }
  26744. }
  26745. if (parsedGeometry.matricesWeights) {
  26746. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26747. }
  26748. if (parsedGeometry.matricesWeightsExtra) {
  26749. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26750. }
  26751. mesh.setIndices(parsedGeometry.indices);
  26752. }
  26753. // SubMeshes
  26754. if (parsedGeometry.subMeshes) {
  26755. mesh.subMeshes = [];
  26756. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26757. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26758. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26759. }
  26760. }
  26761. // Flat shading
  26762. if (mesh._shouldGenerateFlatShading) {
  26763. mesh.convertToFlatShadedMesh();
  26764. delete mesh._shouldGenerateFlatShading;
  26765. }
  26766. // Update
  26767. mesh.computeWorldMatrix(true);
  26768. // Octree
  26769. if (scene['_selectionOctree']) {
  26770. scene['_selectionOctree'].addMesh(mesh);
  26771. }
  26772. };
  26773. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26774. if (scene.getGeometryByID(parsedVertexData.id)) {
  26775. return null; // null since geometry could be something else than a box...
  26776. }
  26777. var geometry = new Geometry(parsedVertexData.id, scene);
  26778. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26779. if (parsedVertexData.delayLoadingFile) {
  26780. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26781. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26782. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26783. geometry._delayInfo = [];
  26784. if (parsedVertexData.hasUVs) {
  26785. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26786. }
  26787. if (parsedVertexData.hasUVs2) {
  26788. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26789. }
  26790. if (parsedVertexData.hasUVs3) {
  26791. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26792. }
  26793. if (parsedVertexData.hasUVs4) {
  26794. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26795. }
  26796. if (parsedVertexData.hasUVs5) {
  26797. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26798. }
  26799. if (parsedVertexData.hasUVs6) {
  26800. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26801. }
  26802. if (parsedVertexData.hasColors) {
  26803. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26804. }
  26805. if (parsedVertexData.hasMatricesIndices) {
  26806. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26807. }
  26808. if (parsedVertexData.hasMatricesWeights) {
  26809. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26810. }
  26811. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26812. }
  26813. else {
  26814. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26815. }
  26816. scene.pushGeometry(geometry, true);
  26817. return geometry;
  26818. };
  26819. return Geometry;
  26820. })();
  26821. BABYLON.Geometry = Geometry;
  26822. /////// Primitives //////////////////////////////////////////////
  26823. var Geometry;
  26824. (function (Geometry) {
  26825. var Primitives;
  26826. (function (Primitives) {
  26827. /// Abstract class
  26828. var _Primitive = (function (_super) {
  26829. __extends(_Primitive, _super);
  26830. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26831. this._beingRegenerated = true;
  26832. this._canBeRegenerated = canBeRegenerated;
  26833. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26834. this._beingRegenerated = false;
  26835. }
  26836. _Primitive.prototype.canBeRegenerated = function () {
  26837. return this._canBeRegenerated;
  26838. };
  26839. _Primitive.prototype.regenerate = function () {
  26840. if (!this._canBeRegenerated) {
  26841. return;
  26842. }
  26843. this._beingRegenerated = true;
  26844. this.setAllVerticesData(this._regenerateVertexData(), false);
  26845. this._beingRegenerated = false;
  26846. };
  26847. _Primitive.prototype.asNewGeometry = function (id) {
  26848. return _super.prototype.copy.call(this, id);
  26849. };
  26850. // overrides
  26851. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26852. if (!this._beingRegenerated) {
  26853. return;
  26854. }
  26855. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26856. };
  26857. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26858. if (!this._beingRegenerated) {
  26859. return;
  26860. }
  26861. _super.prototype.setVerticesData.call(this, kind, data, false);
  26862. };
  26863. // to override
  26864. // protected
  26865. _Primitive.prototype._regenerateVertexData = function () {
  26866. throw new Error("Abstract method");
  26867. };
  26868. _Primitive.prototype.copy = function (id) {
  26869. throw new Error("Must be overriden in sub-classes.");
  26870. };
  26871. _Primitive.prototype.serialize = function () {
  26872. var serializationObject = _super.prototype.serialize.call(this);
  26873. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26874. return serializationObject;
  26875. };
  26876. return _Primitive;
  26877. })(Geometry);
  26878. Primitives._Primitive = _Primitive;
  26879. var Ribbon = (function (_super) {
  26880. __extends(Ribbon, _super);
  26881. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26882. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26883. this.pathArray = pathArray;
  26884. this.closeArray = closeArray;
  26885. this.closePath = closePath;
  26886. this.offset = offset;
  26887. this.side = side;
  26888. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26889. }
  26890. Ribbon.prototype._regenerateVertexData = function () {
  26891. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26892. };
  26893. Ribbon.prototype.copy = function (id) {
  26894. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26895. };
  26896. return Ribbon;
  26897. })(_Primitive);
  26898. Primitives.Ribbon = Ribbon;
  26899. var Box = (function (_super) {
  26900. __extends(Box, _super);
  26901. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26902. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26903. this.size = size;
  26904. this.side = side;
  26905. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26906. }
  26907. Box.prototype._regenerateVertexData = function () {
  26908. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26909. };
  26910. Box.prototype.copy = function (id) {
  26911. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26912. };
  26913. Box.prototype.serialize = function () {
  26914. var serializationObject = _super.prototype.serialize.call(this);
  26915. serializationObject.size = this.size;
  26916. return serializationObject;
  26917. };
  26918. Box.Parse = function (parsedBox, scene) {
  26919. if (scene.getGeometryByID(parsedBox.id)) {
  26920. return null; // null since geometry could be something else than a box...
  26921. }
  26922. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26923. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26924. scene.pushGeometry(box, true);
  26925. return box;
  26926. };
  26927. return Box;
  26928. })(_Primitive);
  26929. Primitives.Box = Box;
  26930. var Sphere = (function (_super) {
  26931. __extends(Sphere, _super);
  26932. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26934. this.segments = segments;
  26935. this.diameter = diameter;
  26936. this.side = side;
  26937. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26938. }
  26939. Sphere.prototype._regenerateVertexData = function () {
  26940. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26941. };
  26942. Sphere.prototype.copy = function (id) {
  26943. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26944. };
  26945. Sphere.prototype.serialize = function () {
  26946. var serializationObject = _super.prototype.serialize.call(this);
  26947. serializationObject.segments = this.segments;
  26948. serializationObject.diameter = this.diameter;
  26949. return serializationObject;
  26950. };
  26951. Sphere.Parse = function (parsedSphere, scene) {
  26952. if (scene.getGeometryByID(parsedSphere.id)) {
  26953. return null; // null since geometry could be something else than a sphere...
  26954. }
  26955. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26956. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26957. scene.pushGeometry(sphere, true);
  26958. return sphere;
  26959. };
  26960. return Sphere;
  26961. })(_Primitive);
  26962. Primitives.Sphere = Sphere;
  26963. var Disc = (function (_super) {
  26964. __extends(Disc, _super);
  26965. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26966. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26967. this.radius = radius;
  26968. this.tessellation = tessellation;
  26969. this.side = side;
  26970. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26971. }
  26972. Disc.prototype._regenerateVertexData = function () {
  26973. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26974. };
  26975. Disc.prototype.copy = function (id) {
  26976. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26977. };
  26978. return Disc;
  26979. })(_Primitive);
  26980. Primitives.Disc = Disc;
  26981. var Cylinder = (function (_super) {
  26982. __extends(Cylinder, _super);
  26983. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26984. if (subdivisions === void 0) { subdivisions = 1; }
  26985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26986. this.height = height;
  26987. this.diameterTop = diameterTop;
  26988. this.diameterBottom = diameterBottom;
  26989. this.tessellation = tessellation;
  26990. this.subdivisions = subdivisions;
  26991. this.side = side;
  26992. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26993. }
  26994. Cylinder.prototype._regenerateVertexData = function () {
  26995. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26996. };
  26997. Cylinder.prototype.copy = function (id) {
  26998. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26999. };
  27000. Cylinder.prototype.serialize = function () {
  27001. var serializationObject = _super.prototype.serialize.call(this);
  27002. serializationObject.height = this.height;
  27003. serializationObject.diameterTop = this.diameterTop;
  27004. serializationObject.diameterBottom = this.diameterBottom;
  27005. serializationObject.tessellation = this.tessellation;
  27006. return serializationObject;
  27007. };
  27008. Cylinder.Parse = function (parsedCylinder, scene) {
  27009. if (scene.getGeometryByID(parsedCylinder.id)) {
  27010. return null; // null since geometry could be something else than a cylinder...
  27011. }
  27012. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27013. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27014. scene.pushGeometry(cylinder, true);
  27015. return cylinder;
  27016. };
  27017. return Cylinder;
  27018. })(_Primitive);
  27019. Primitives.Cylinder = Cylinder;
  27020. var Torus = (function (_super) {
  27021. __extends(Torus, _super);
  27022. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27023. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27024. this.diameter = diameter;
  27025. this.thickness = thickness;
  27026. this.tessellation = tessellation;
  27027. this.side = side;
  27028. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27029. }
  27030. Torus.prototype._regenerateVertexData = function () {
  27031. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27032. };
  27033. Torus.prototype.copy = function (id) {
  27034. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27035. };
  27036. Torus.prototype.serialize = function () {
  27037. var serializationObject = _super.prototype.serialize.call(this);
  27038. serializationObject.diameter = this.diameter;
  27039. serializationObject.thickness = this.thickness;
  27040. serializationObject.tessellation = this.tessellation;
  27041. return serializationObject;
  27042. };
  27043. Torus.Parse = function (parsedTorus, scene) {
  27044. if (scene.getGeometryByID(parsedTorus.id)) {
  27045. return null; // null since geometry could be something else than a torus...
  27046. }
  27047. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27048. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27049. scene.pushGeometry(torus, true);
  27050. return torus;
  27051. };
  27052. return Torus;
  27053. })(_Primitive);
  27054. Primitives.Torus = Torus;
  27055. var Ground = (function (_super) {
  27056. __extends(Ground, _super);
  27057. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27058. this.width = width;
  27059. this.height = height;
  27060. this.subdivisions = subdivisions;
  27061. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27062. }
  27063. Ground.prototype._regenerateVertexData = function () {
  27064. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27065. };
  27066. Ground.prototype.copy = function (id) {
  27067. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27068. };
  27069. Ground.prototype.serialize = function () {
  27070. var serializationObject = _super.prototype.serialize.call(this);
  27071. serializationObject.width = this.width;
  27072. serializationObject.height = this.height;
  27073. serializationObject.subdivisions = this.subdivisions;
  27074. return serializationObject;
  27075. };
  27076. Ground.Parse = function (parsedGround, scene) {
  27077. if (scene.getGeometryByID(parsedGround.id)) {
  27078. return null; // null since geometry could be something else than a ground...
  27079. }
  27080. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27081. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27082. scene.pushGeometry(ground, true);
  27083. return ground;
  27084. };
  27085. return Ground;
  27086. })(_Primitive);
  27087. Primitives.Ground = Ground;
  27088. var TiledGround = (function (_super) {
  27089. __extends(TiledGround, _super);
  27090. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27091. this.xmin = xmin;
  27092. this.zmin = zmin;
  27093. this.xmax = xmax;
  27094. this.zmax = zmax;
  27095. this.subdivisions = subdivisions;
  27096. this.precision = precision;
  27097. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27098. }
  27099. TiledGround.prototype._regenerateVertexData = function () {
  27100. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27101. };
  27102. TiledGround.prototype.copy = function (id) {
  27103. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27104. };
  27105. return TiledGround;
  27106. })(_Primitive);
  27107. Primitives.TiledGround = TiledGround;
  27108. var Plane = (function (_super) {
  27109. __extends(Plane, _super);
  27110. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27112. this.size = size;
  27113. this.side = side;
  27114. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27115. }
  27116. Plane.prototype._regenerateVertexData = function () {
  27117. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27118. };
  27119. Plane.prototype.copy = function (id) {
  27120. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27121. };
  27122. Plane.prototype.serialize = function () {
  27123. var serializationObject = _super.prototype.serialize.call(this);
  27124. serializationObject.size = this.size;
  27125. return serializationObject;
  27126. };
  27127. Plane.Parse = function (parsedPlane, scene) {
  27128. if (scene.getGeometryByID(parsedPlane.id)) {
  27129. return null; // null since geometry could be something else than a ground...
  27130. }
  27131. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27132. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27133. scene.pushGeometry(plane, true);
  27134. return plane;
  27135. };
  27136. return Plane;
  27137. })(_Primitive);
  27138. Primitives.Plane = Plane;
  27139. var TorusKnot = (function (_super) {
  27140. __extends(TorusKnot, _super);
  27141. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27142. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27143. this.radius = radius;
  27144. this.tube = tube;
  27145. this.radialSegments = radialSegments;
  27146. this.tubularSegments = tubularSegments;
  27147. this.p = p;
  27148. this.q = q;
  27149. this.side = side;
  27150. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27151. }
  27152. TorusKnot.prototype._regenerateVertexData = function () {
  27153. 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 });
  27154. };
  27155. TorusKnot.prototype.copy = function (id) {
  27156. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27157. };
  27158. TorusKnot.prototype.serialize = function () {
  27159. var serializationObject = _super.prototype.serialize.call(this);
  27160. serializationObject.radius = this.radius;
  27161. serializationObject.tube = this.tube;
  27162. serializationObject.radialSegments = this.radialSegments;
  27163. serializationObject.tubularSegments = this.tubularSegments;
  27164. serializationObject.p = this.p;
  27165. serializationObject.q = this.q;
  27166. return serializationObject;
  27167. };
  27168. ;
  27169. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27170. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27171. return null; // null since geometry could be something else than a ground...
  27172. }
  27173. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27174. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27175. scene.pushGeometry(torusKnot, true);
  27176. return torusKnot;
  27177. };
  27178. return TorusKnot;
  27179. })(_Primitive);
  27180. Primitives.TorusKnot = TorusKnot;
  27181. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27182. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27183. })(BABYLON || (BABYLON = {}));
  27184. var BABYLON;
  27185. (function (BABYLON) {
  27186. var GroundMesh = (function (_super) {
  27187. __extends(GroundMesh, _super);
  27188. function GroundMesh(name, scene) {
  27189. _super.call(this, name, scene);
  27190. this.generateOctree = false;
  27191. this._worldInverse = new BABYLON.Matrix();
  27192. }
  27193. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27194. get: function () {
  27195. return this._subdivisions;
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27201. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27202. this._subdivisions = chunksCount;
  27203. this.subdivide(this._subdivisions);
  27204. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27205. };
  27206. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27207. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27208. return 0;
  27209. }
  27210. if (!this._heightQuads || this._heightQuads.length == 0) {
  27211. this._computeHeightQuads();
  27212. }
  27213. var facet = this._getFacetAt(x, z);
  27214. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27215. return y;
  27216. };
  27217. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27218. var normal = new BABYLON.Vector3(0, 1, 0);
  27219. this.getNormalAtCoordinatesToRef(x, z, normal);
  27220. return normal;
  27221. };
  27222. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27223. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27224. return;
  27225. }
  27226. if (!this._heightQuads || this._heightQuads.length == 0) {
  27227. this._computeHeightQuads();
  27228. }
  27229. var facet = this._getFacetAt(x, z);
  27230. ref.x = facet.x;
  27231. ref.y = facet.y;
  27232. ref.z = facet.z;
  27233. };
  27234. GroundMesh.prototype._getFacetAt = function (x, z) {
  27235. // retrieve col and row from x, z coordinates
  27236. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27237. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27238. var quad = this._heightQuads[row * this._subdivisions + col];
  27239. var facet;
  27240. if (z < quad.slope.x * x + quad.slope.y) {
  27241. facet = quad.facet1;
  27242. }
  27243. else {
  27244. facet = quad.facet2;
  27245. }
  27246. return facet;
  27247. };
  27248. GroundMesh.prototype._computeHeightQuads = function () {
  27249. this._heightQuads = new Array();
  27250. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27251. var v1 = BABYLON.Vector3.Zero();
  27252. var v2 = BABYLON.Vector3.Zero();
  27253. var v3 = BABYLON.Vector3.Zero();
  27254. var v4 = BABYLON.Vector3.Zero();
  27255. var v1v2 = BABYLON.Vector3.Zero();
  27256. var v1v3 = BABYLON.Vector3.Zero();
  27257. var v1v4 = BABYLON.Vector3.Zero();
  27258. var norm1 = BABYLON.Vector3.Zero();
  27259. var norm2 = BABYLON.Vector3.Zero();
  27260. var i = 0;
  27261. var j = 0;
  27262. var k = 0;
  27263. var cd = 0; // 2D slope coefficient : z = cd * x + h
  27264. var h = 0;
  27265. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  27266. var d2 = 0;
  27267. for (var row = 0; row < this._subdivisions; row++) {
  27268. for (var col = 0; col < this._subdivisions; col++) {
  27269. i = col * 3;
  27270. j = row * (this._subdivisions + 1) * 3;
  27271. k = (row + 1) * (this._subdivisions + 1) * 3;
  27272. v1.x = positions[j + i];
  27273. v1.y = positions[j + i + 1];
  27274. v1.z = positions[j + i + 2];
  27275. v2.x = positions[j + i + 3];
  27276. v2.y = positions[j + i + 4];
  27277. v2.z = positions[j + i + 5];
  27278. v3.x = positions[k + i];
  27279. v3.y = positions[k + i + 1];
  27280. v3.z = positions[k + i + 2];
  27281. v4.x = positions[k + i + 3];
  27282. v4.y = positions[k + i + 4];
  27283. v4.z = positions[k + i + 5];
  27284. // 2D slope V1V4
  27285. cd = (v4.z - v1.z) / (v4.x - v1.x);
  27286. h = v1.z - cd * v1.x; // v1 belongs to the slope
  27287. var slope = new BABYLON.Vector2(cd, h);
  27288. // facet equations :
  27289. // we compute each facet normal vector
  27290. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  27291. // we compute the value d by applying the equation to v1 which belongs to the plane
  27292. // then we store the facet equation in a Vector4
  27293. v2.subtractToRef(v1, v1v2);
  27294. v3.subtractToRef(v1, v1v3);
  27295. v4.subtractToRef(v1, v1v4);
  27296. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  27297. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  27298. norm1.normalize();
  27299. norm2.normalize();
  27300. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  27301. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  27302. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  27303. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  27304. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  27305. this._heightQuads.push(quad);
  27306. }
  27307. }
  27308. };
  27309. return GroundMesh;
  27310. })(BABYLON.Mesh);
  27311. BABYLON.GroundMesh = GroundMesh;
  27312. })(BABYLON || (BABYLON = {}));
  27313. var BABYLON;
  27314. (function (BABYLON) {
  27315. var LinesMesh = (function (_super) {
  27316. __extends(LinesMesh, _super);
  27317. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27318. if (parent === void 0) { parent = null; }
  27319. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27320. this.color = new BABYLON.Color3(1, 1, 1);
  27321. this.alpha = 1;
  27322. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27323. attributes: ["position"],
  27324. uniforms: ["worldViewProjection", "color"],
  27325. needAlphaBlending: true
  27326. });
  27327. }
  27328. Object.defineProperty(LinesMesh.prototype, "material", {
  27329. get: function () {
  27330. return this._colorShader;
  27331. },
  27332. enumerable: true,
  27333. configurable: true
  27334. });
  27335. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27336. get: function () {
  27337. return false;
  27338. },
  27339. enumerable: true,
  27340. configurable: true
  27341. });
  27342. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27343. get: function () {
  27344. return false;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27350. var engine = this.getScene().getEngine();
  27351. var indexToBind = this._geometry.getIndexBuffer();
  27352. // VBOs
  27353. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27354. // Color
  27355. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27356. };
  27357. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27358. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27359. return;
  27360. }
  27361. var engine = this.getScene().getEngine();
  27362. // Draw order
  27363. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27364. };
  27365. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27366. return null;
  27367. };
  27368. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27369. this._colorShader.dispose();
  27370. _super.prototype.dispose.call(this, doNotRecurse);
  27371. };
  27372. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27373. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27374. };
  27375. return LinesMesh;
  27376. })(BABYLON.Mesh);
  27377. BABYLON.LinesMesh = LinesMesh;
  27378. })(BABYLON || (BABYLON = {}));
  27379. var BABYLON;
  27380. (function (BABYLON) {
  27381. var DebugLayer = (function () {
  27382. function DebugLayer(scene) {
  27383. var _this = this;
  27384. this._transformationMatrix = BABYLON.Matrix.Identity();
  27385. this._enabled = false;
  27386. this._labelsEnabled = false;
  27387. this._displayStatistics = true;
  27388. this._displayTree = false;
  27389. this._displayLogs = false;
  27390. this._identityMatrix = BABYLON.Matrix.Identity();
  27391. this.axisRatio = 0.02;
  27392. this.accentColor = "orange";
  27393. this._scene = scene;
  27394. this._syncPositions = function () {
  27395. var engine = _this._scene.getEngine();
  27396. var canvasRect = engine.getRenderingCanvasClientRect();
  27397. if (_this._showUI) {
  27398. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27399. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27400. _this._statsDiv.style.width = "400px";
  27401. _this._statsDiv.style.height = "auto";
  27402. _this._statsSubsetDiv.style.maxHeight = "240px";
  27403. _this._optionsDiv.style.left = "0px";
  27404. _this._optionsDiv.style.top = "10px";
  27405. _this._optionsDiv.style.width = "200px";
  27406. _this._optionsDiv.style.height = "auto";
  27407. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27408. _this._logDiv.style.left = "0px";
  27409. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27410. _this._logDiv.style.width = "600px";
  27411. _this._logDiv.style.height = "160px";
  27412. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27413. _this._treeDiv.style.top = "10px";
  27414. _this._treeDiv.style.width = "300px";
  27415. _this._treeDiv.style.height = "auto";
  27416. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27417. }
  27418. _this._globalDiv.style.left = canvasRect.left + "px";
  27419. _this._globalDiv.style.top = canvasRect.top + "px";
  27420. _this._drawingCanvas.style.left = "0px";
  27421. _this._drawingCanvas.style.top = "0px";
  27422. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27423. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27424. var devicePixelRatio = window.devicePixelRatio || 1;
  27425. var context = _this._drawingContext;
  27426. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27427. context.mozBackingStorePixelRatio ||
  27428. context.msBackingStorePixelRatio ||
  27429. context.oBackingStorePixelRatio ||
  27430. context.backingStorePixelRatio || 1;
  27431. _this._ratio = devicePixelRatio / backingStoreRatio;
  27432. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27433. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27434. };
  27435. this._onCanvasClick = function (evt) {
  27436. _this._clickPosition = {
  27437. x: evt.clientX * _this._ratio,
  27438. y: evt.clientY * _this._ratio
  27439. };
  27440. };
  27441. this._syncUI = function () {
  27442. if (_this._showUI) {
  27443. if (_this._displayStatistics) {
  27444. _this._displayStats();
  27445. _this._statsDiv.style.display = "";
  27446. }
  27447. else {
  27448. _this._statsDiv.style.display = "none";
  27449. }
  27450. if (_this._displayLogs) {
  27451. _this._logDiv.style.display = "";
  27452. }
  27453. else {
  27454. _this._logDiv.style.display = "none";
  27455. }
  27456. if (_this._displayTree) {
  27457. _this._treeDiv.style.display = "";
  27458. if (_this._needToRefreshMeshesTree) {
  27459. _this._needToRefreshMeshesTree = false;
  27460. _this._refreshMeshesTreeContent();
  27461. }
  27462. }
  27463. else {
  27464. _this._treeDiv.style.display = "none";
  27465. }
  27466. }
  27467. };
  27468. this._syncData = function () {
  27469. if (_this._labelsEnabled || !_this._showUI) {
  27470. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27471. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27472. var engine = _this._scene.getEngine();
  27473. var viewport = _this._camera.viewport;
  27474. var globalViewport = viewport.toGlobal(engine);
  27475. // Meshes
  27476. var meshes = _this._camera.getActiveMeshes();
  27477. var index;
  27478. var projectedPosition;
  27479. for (index = 0; index < meshes.length; index++) {
  27480. var mesh = meshes.data[index];
  27481. var position = mesh.getBoundingInfo().boundingSphere.center;
  27482. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27483. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27484. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27485. }
  27486. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27487. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27488. }
  27489. }
  27490. // Cameras
  27491. var cameras = _this._scene.cameras;
  27492. for (index = 0; index < cameras.length; index++) {
  27493. var camera = cameras[index];
  27494. if (camera === _this._camera) {
  27495. continue;
  27496. }
  27497. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27498. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27499. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27500. _this._camera.detachControl(engine.getRenderingCanvas());
  27501. _this._camera = camera;
  27502. _this._camera.attachControl(engine.getRenderingCanvas());
  27503. }, function () { return "purple"; });
  27504. }
  27505. }
  27506. // Lights
  27507. var lights = _this._scene.lights;
  27508. for (index = 0; index < lights.length; index++) {
  27509. var light = lights[index];
  27510. if (light.position) {
  27511. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27512. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27513. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27514. light.setEnabled(!light.isEnabled());
  27515. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27516. }
  27517. }
  27518. }
  27519. }
  27520. _this._clickPosition = undefined;
  27521. };
  27522. }
  27523. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27524. while (this._treeSubsetDiv.hasChildNodes()) {
  27525. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27526. }
  27527. // Add meshes
  27528. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27529. sortedArray.sort(function (a, b) {
  27530. if (a.name === b.name) {
  27531. return 0;
  27532. }
  27533. return (a.name > b.name) ? 1 : -1;
  27534. });
  27535. for (var index = 0; index < sortedArray.length; index++) {
  27536. var mesh = sortedArray[index];
  27537. if (!mesh.isEnabled()) {
  27538. continue;
  27539. }
  27540. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27541. m.isVisible = element.checked;
  27542. }, mesh);
  27543. }
  27544. };
  27545. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27546. this._drawingContext.beginPath();
  27547. this._drawingContext.moveTo(zero.x, zero.y);
  27548. this._drawingContext.lineTo(unit.x, unit.y);
  27549. this._drawingContext.strokeStyle = color;
  27550. this._drawingContext.lineWidth = 4;
  27551. this._drawingContext.stroke();
  27552. this._drawingContext.font = "normal 14px Segoe UI";
  27553. this._drawingContext.fillStyle = color;
  27554. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27555. };
  27556. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27557. var position = mesh.getBoundingInfo().boundingSphere.center;
  27558. var worldMatrix = mesh.getWorldMatrix();
  27559. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27560. var unit = (unprojectedVector.subtract(position)).length();
  27561. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27562. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27563. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27564. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27565. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27566. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27567. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27568. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27569. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27570. };
  27571. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27572. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27573. this._drawingContext.font = "normal 12px Segoe UI";
  27574. var textMetrics = this._drawingContext.measureText(text);
  27575. var centerX = projectedPosition.x - textMetrics.width / 2;
  27576. var centerY = projectedPosition.y;
  27577. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27578. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27579. onClick();
  27580. }
  27581. this._drawingContext.beginPath();
  27582. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27583. this._drawingContext.fillStyle = getFillStyle();
  27584. this._drawingContext.globalAlpha = 0.5;
  27585. this._drawingContext.fill();
  27586. this._drawingContext.globalAlpha = 1.0;
  27587. this._drawingContext.strokeStyle = '#FFFFFF';
  27588. this._drawingContext.lineWidth = 1;
  27589. this._drawingContext.stroke();
  27590. this._drawingContext.fillStyle = "#FFFFFF";
  27591. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27592. this._drawingContext.beginPath();
  27593. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27594. this._drawingContext.fill();
  27595. }
  27596. };
  27597. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27598. if (!this._clickPosition) {
  27599. return false;
  27600. }
  27601. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27602. return false;
  27603. }
  27604. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27605. return false;
  27606. }
  27607. return true;
  27608. };
  27609. DebugLayer.prototype.isVisible = function () {
  27610. return this._enabled;
  27611. };
  27612. DebugLayer.prototype.hide = function () {
  27613. if (!this._enabled) {
  27614. return;
  27615. }
  27616. this._enabled = false;
  27617. var engine = this._scene.getEngine();
  27618. this._scene.unregisterBeforeRender(this._syncData);
  27619. this._scene.unregisterAfterRender(this._syncUI);
  27620. this._rootElement.removeChild(this._globalDiv);
  27621. this._scene.forceShowBoundingBoxes = false;
  27622. this._scene.forceWireframe = false;
  27623. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27624. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27625. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27626. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27627. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27628. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27629. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27630. BABYLON.StandardMaterial.LightmapEnabled = true;
  27631. this._scene.shadowsEnabled = true;
  27632. this._scene.particlesEnabled = true;
  27633. this._scene.postProcessesEnabled = true;
  27634. this._scene.collisionsEnabled = true;
  27635. this._scene.lightsEnabled = true;
  27636. this._scene.texturesEnabled = true;
  27637. this._scene.lensFlaresEnabled = true;
  27638. this._scene.proceduralTexturesEnabled = true;
  27639. this._scene.renderTargetsEnabled = true;
  27640. this._scene.probesEnabled = true;
  27641. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27642. };
  27643. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27644. if (showUI === void 0) { showUI = true; }
  27645. if (camera === void 0) { camera = null; }
  27646. if (rootElement === void 0) { rootElement = null; }
  27647. if (this._enabled) {
  27648. return;
  27649. }
  27650. this._enabled = true;
  27651. if (camera) {
  27652. this._camera = camera;
  27653. }
  27654. else {
  27655. this._camera = this._scene.activeCamera;
  27656. }
  27657. this._showUI = showUI;
  27658. var engine = this._scene.getEngine();
  27659. this._globalDiv = document.createElement("div");
  27660. this._rootElement = rootElement || document.body;
  27661. this._rootElement.appendChild(this._globalDiv);
  27662. this._generateDOMelements();
  27663. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27664. this._syncPositions();
  27665. this._scene.registerBeforeRender(this._syncData);
  27666. this._scene.registerAfterRender(this._syncUI);
  27667. };
  27668. DebugLayer.prototype._clearLabels = function () {
  27669. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27670. for (var index = 0; index < this._scene.meshes.length; index++) {
  27671. var mesh = this._scene.meshes[index];
  27672. mesh.renderOverlay = false;
  27673. }
  27674. };
  27675. DebugLayer.prototype._generateheader = function (root, text) {
  27676. var header = document.createElement("div");
  27677. header.innerHTML = text + "&nbsp;";
  27678. header.style.textAlign = "right";
  27679. header.style.width = "100%";
  27680. header.style.color = "white";
  27681. header.style.backgroundColor = "Black";
  27682. header.style.padding = "5px 5px 4px 0px";
  27683. header.style.marginLeft = "-5px";
  27684. header.style.fontWeight = "bold";
  27685. root.appendChild(header);
  27686. };
  27687. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27688. var label = document.createElement("label");
  27689. label.innerHTML = title;
  27690. label.style.color = color;
  27691. root.appendChild(label);
  27692. root.appendChild(document.createElement("br"));
  27693. };
  27694. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27695. if (tag === void 0) { tag = null; }
  27696. var label = document.createElement("label");
  27697. var boundingBoxesCheckbox = document.createElement("input");
  27698. boundingBoxesCheckbox.type = "checkbox";
  27699. boundingBoxesCheckbox.checked = initialState;
  27700. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27701. task(evt.target, tag);
  27702. });
  27703. label.appendChild(boundingBoxesCheckbox);
  27704. var container = document.createElement("span");
  27705. var leftPart = document.createElement("span");
  27706. var rightPart = document.createElement("span");
  27707. rightPart.style.cssFloat = "right";
  27708. leftPart.innerHTML = leftTitle;
  27709. rightPart.innerHTML = rightTitle;
  27710. rightPart.style.fontSize = "12px";
  27711. rightPart.style.maxWidth = "200px";
  27712. container.appendChild(leftPart);
  27713. container.appendChild(rightPart);
  27714. label.appendChild(container);
  27715. root.appendChild(label);
  27716. root.appendChild(document.createElement("br"));
  27717. };
  27718. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27719. if (tag === void 0) { tag = null; }
  27720. var label = document.createElement("label");
  27721. var checkBox = document.createElement("input");
  27722. checkBox.type = "checkbox";
  27723. checkBox.checked = initialState;
  27724. checkBox.addEventListener("change", function (evt) {
  27725. task(evt.target, tag);
  27726. });
  27727. label.appendChild(checkBox);
  27728. label.appendChild(document.createTextNode(title));
  27729. root.appendChild(label);
  27730. root.appendChild(document.createElement("br"));
  27731. };
  27732. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27733. if (tag === void 0) { tag = null; }
  27734. var button = document.createElement("button");
  27735. button.innerHTML = title;
  27736. button.style.height = "24px";
  27737. button.style.width = "150px";
  27738. button.style.marginBottom = "5px";
  27739. button.style.color = "#444444";
  27740. button.style.border = "1px solid white";
  27741. button.className = "debugLayerButton";
  27742. button.addEventListener("click", function (evt) {
  27743. task(evt.target, tag);
  27744. });
  27745. root.appendChild(button);
  27746. root.appendChild(document.createElement("br"));
  27747. };
  27748. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27749. if (tag === void 0) { tag = null; }
  27750. var label = document.createElement("label");
  27751. var boundingBoxesRadio = document.createElement("input");
  27752. boundingBoxesRadio.type = "radio";
  27753. boundingBoxesRadio.name = name;
  27754. boundingBoxesRadio.checked = initialState;
  27755. boundingBoxesRadio.addEventListener("change", function (evt) {
  27756. task(evt.target, tag);
  27757. });
  27758. label.appendChild(boundingBoxesRadio);
  27759. label.appendChild(document.createTextNode(title));
  27760. root.appendChild(label);
  27761. root.appendChild(document.createElement("br"));
  27762. };
  27763. DebugLayer.prototype._generateDOMelements = function () {
  27764. var _this = this;
  27765. this._globalDiv.id = "DebugLayer";
  27766. this._globalDiv.style.position = "absolute";
  27767. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27768. this._globalDiv.style.fontSize = "14px";
  27769. this._globalDiv.style.color = "white";
  27770. // Drawing canvas
  27771. this._drawingCanvas = document.createElement("canvas");
  27772. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27773. this._drawingCanvas.style.position = "absolute";
  27774. this._drawingCanvas.style.pointerEvents = "none";
  27775. this._drawingCanvas.style.backgroundColor = "transparent";
  27776. this._drawingContext = this._drawingCanvas.getContext("2d");
  27777. this._globalDiv.appendChild(this._drawingCanvas);
  27778. if (this._showUI) {
  27779. var background = "rgba(128, 128, 128, 0.4)";
  27780. var border = "rgb(180, 180, 180) solid 1px";
  27781. // Stats
  27782. this._statsDiv = document.createElement("div");
  27783. this._statsDiv.id = "DebugLayerStats";
  27784. this._statsDiv.style.border = border;
  27785. this._statsDiv.style.position = "absolute";
  27786. this._statsDiv.style.background = background;
  27787. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27788. this._generateheader(this._statsDiv, "STATISTICS");
  27789. this._statsSubsetDiv = document.createElement("div");
  27790. this._statsSubsetDiv.style.paddingTop = "5px";
  27791. this._statsSubsetDiv.style.paddingBottom = "5px";
  27792. this._statsSubsetDiv.style.overflowY = "auto";
  27793. this._statsDiv.appendChild(this._statsSubsetDiv);
  27794. // Tree
  27795. this._treeDiv = document.createElement("div");
  27796. this._treeDiv.id = "DebugLayerTree";
  27797. this._treeDiv.style.border = border;
  27798. this._treeDiv.style.position = "absolute";
  27799. this._treeDiv.style.background = background;
  27800. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27801. this._treeDiv.style.display = "none";
  27802. this._generateheader(this._treeDiv, "MESHES TREE");
  27803. this._treeSubsetDiv = document.createElement("div");
  27804. this._treeSubsetDiv.style.paddingTop = "5px";
  27805. this._treeSubsetDiv.style.paddingRight = "5px";
  27806. this._treeSubsetDiv.style.overflowY = "auto";
  27807. this._treeSubsetDiv.style.maxHeight = "300px";
  27808. this._treeDiv.appendChild(this._treeSubsetDiv);
  27809. this._needToRefreshMeshesTree = true;
  27810. // Logs
  27811. this._logDiv = document.createElement("div");
  27812. this._logDiv.style.border = border;
  27813. this._logDiv.id = "DebugLayerLogs";
  27814. this._logDiv.style.position = "absolute";
  27815. this._logDiv.style.background = background;
  27816. this._logDiv.style.padding = "0px 0px 0px 5px";
  27817. this._logDiv.style.display = "none";
  27818. this._generateheader(this._logDiv, "LOGS");
  27819. this._logSubsetDiv = document.createElement("div");
  27820. this._logSubsetDiv.style.height = "127px";
  27821. this._logSubsetDiv.style.paddingTop = "5px";
  27822. this._logSubsetDiv.style.overflowY = "auto";
  27823. this._logSubsetDiv.style.fontSize = "12px";
  27824. this._logSubsetDiv.style.fontFamily = "consolas";
  27825. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27826. this._logDiv.appendChild(this._logSubsetDiv);
  27827. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27828. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27829. };
  27830. // Options
  27831. this._optionsDiv = document.createElement("div");
  27832. this._optionsDiv.id = "DebugLayerOptions";
  27833. this._optionsDiv.style.border = border;
  27834. this._optionsDiv.style.position = "absolute";
  27835. this._optionsDiv.style.background = background;
  27836. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27837. this._optionsDiv.style.overflowY = "auto";
  27838. this._generateheader(this._optionsDiv, "OPTIONS");
  27839. this._optionsSubsetDiv = document.createElement("div");
  27840. this._optionsSubsetDiv.style.paddingTop = "5px";
  27841. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27842. this._optionsSubsetDiv.style.overflowY = "auto";
  27843. this._optionsSubsetDiv.style.maxHeight = "200px";
  27844. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27845. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27846. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27847. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27848. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27849. _this._displayTree = element.checked;
  27850. _this._needToRefreshMeshesTree = true;
  27851. });
  27852. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27853. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27854. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27855. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27856. _this._labelsEnabled = element.checked;
  27857. if (!_this._labelsEnabled) {
  27858. _this._clearLabels();
  27859. }
  27860. });
  27861. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27862. if (element.checked) {
  27863. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27864. }
  27865. else {
  27866. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27867. }
  27868. });
  27869. ;
  27870. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27871. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27872. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27873. if (element.checked) {
  27874. _this._scene.forceWireframe = false;
  27875. _this._scene.forcePointsCloud = false;
  27876. }
  27877. });
  27878. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27879. if (element.checked) {
  27880. _this._scene.forceWireframe = true;
  27881. _this._scene.forcePointsCloud = false;
  27882. }
  27883. });
  27884. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27885. if (element.checked) {
  27886. _this._scene.forceWireframe = false;
  27887. _this._scene.forcePointsCloud = true;
  27888. }
  27889. });
  27890. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27891. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27892. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27893. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27894. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27895. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27896. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27897. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27898. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27899. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27900. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27901. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27902. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27903. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27904. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27905. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27906. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27907. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27908. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27909. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27910. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27911. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27912. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27913. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27914. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27915. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27916. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27917. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27918. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27919. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27920. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27921. if (element.checked) {
  27922. _this._scene.headphone = true;
  27923. }
  27924. });
  27925. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27926. if (element.checked) {
  27927. _this._scene.headphone = false;
  27928. }
  27929. });
  27930. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27931. _this._scene.audioEnabled = !element.checked;
  27932. });
  27933. }
  27934. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27935. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27936. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27937. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27938. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27939. if (_this._camera) {
  27940. console.log(_this._camera);
  27941. }
  27942. else {
  27943. console.warn("No camera defined, or debug layer created before camera creation!");
  27944. }
  27945. });
  27946. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27947. this._globalDiv.appendChild(this._statsDiv);
  27948. this._globalDiv.appendChild(this._logDiv);
  27949. this._globalDiv.appendChild(this._optionsDiv);
  27950. this._globalDiv.appendChild(this._treeDiv);
  27951. }
  27952. };
  27953. DebugLayer.prototype._displayStats = function () {
  27954. var scene = this._scene;
  27955. var engine = scene.getEngine();
  27956. var glInfo = engine.getGlInfo();
  27957. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27958. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27959. + "<b>Count</b><br>"
  27960. + "Total meshes: " + scene.meshes.length + "<br>"
  27961. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27962. + "Total materials: " + scene.materials.length + "<br>"
  27963. + "Total textures: " + scene.textures.length + "<br>"
  27964. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27965. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27966. + "Active bones: " + scene.getActiveBones() + "<br>"
  27967. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27968. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27969. + "<b>Duration</b><br>"
  27970. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27971. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27972. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27973. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27974. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27975. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27976. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27977. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  27978. + "</div>"
  27979. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27980. + "<b>Extensions</b><br>"
  27981. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27982. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27983. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27984. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27985. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27986. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27987. + "<b>Caps.</b><br>"
  27988. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27989. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27990. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27991. + "</div><br>"
  27992. + "<b>Info</b><br>"
  27993. + glInfo.version + "<br>"
  27994. + glInfo.renderer + "<br>";
  27995. if (this.customStatsFunction) {
  27996. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27997. }
  27998. };
  27999. return DebugLayer;
  28000. })();
  28001. BABYLON.DebugLayer = DebugLayer;
  28002. })(BABYLON || (BABYLON = {}));
  28003. var BABYLON;
  28004. (function (BABYLON) {
  28005. var DefaultLoadingScreen = (function () {
  28006. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28007. var _this = this;
  28008. if (_loadingText === void 0) { _loadingText = ""; }
  28009. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28010. this._renderingCanvas = _renderingCanvas;
  28011. this._loadingText = _loadingText;
  28012. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28013. // Resize
  28014. this._resizeLoadingUI = function () {
  28015. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28016. _this._loadingDiv.style.position = "absolute";
  28017. _this._loadingDiv.style.left = canvasRect.left + "px";
  28018. _this._loadingDiv.style.top = canvasRect.top + "px";
  28019. _this._loadingDiv.style.width = canvasRect.width + "px";
  28020. _this._loadingDiv.style.height = canvasRect.height + "px";
  28021. };
  28022. }
  28023. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28024. var _this = this;
  28025. this._loadingDiv = document.createElement("div");
  28026. this._loadingDiv.id = "babylonjsLoadingDiv";
  28027. this._loadingDiv.style.opacity = "0";
  28028. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28029. // Loading text
  28030. this._loadingTextDiv = document.createElement("div");
  28031. this._loadingTextDiv.style.position = "absolute";
  28032. this._loadingTextDiv.style.left = "0";
  28033. this._loadingTextDiv.style.top = "50%";
  28034. this._loadingTextDiv.style.marginTop = "80px";
  28035. this._loadingTextDiv.style.width = "100%";
  28036. this._loadingTextDiv.style.height = "20px";
  28037. this._loadingTextDiv.style.fontFamily = "Arial";
  28038. this._loadingTextDiv.style.fontSize = "14px";
  28039. this._loadingTextDiv.style.color = "white";
  28040. this._loadingTextDiv.style.textAlign = "center";
  28041. this._loadingTextDiv.innerHTML = "Loading";
  28042. this._loadingDiv.appendChild(this._loadingTextDiv);
  28043. //set the predefined text
  28044. this._loadingTextDiv.innerHTML = this._loadingText;
  28045. // Loading img
  28046. var imgBack = new Image();
  28047. 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==";
  28048. imgBack.style.position = "absolute";
  28049. imgBack.style.left = "50%";
  28050. imgBack.style.top = "50%";
  28051. imgBack.style.marginLeft = "-50px";
  28052. imgBack.style.marginTop = "-50px";
  28053. imgBack.style.transition = "transform 1.0s ease";
  28054. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28055. var deg = 360;
  28056. var onTransitionEnd = function () {
  28057. deg += 360;
  28058. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28059. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28060. };
  28061. imgBack.addEventListener("transitionend", onTransitionEnd);
  28062. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28063. this._loadingDiv.appendChild(imgBack);
  28064. // front image
  28065. var imgFront = new Image();
  28066. 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=";
  28067. imgFront.style.position = "absolute";
  28068. imgFront.style.left = "50%";
  28069. imgFront.style.top = "50%";
  28070. imgFront.style.marginLeft = "-50px";
  28071. imgFront.style.marginTop = "-50px";
  28072. this._loadingDiv.appendChild(imgFront);
  28073. this._resizeLoadingUI();
  28074. window.addEventListener("resize", this._resizeLoadingUI);
  28075. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28076. document.body.appendChild(this._loadingDiv);
  28077. setTimeout(function () {
  28078. _this._loadingDiv.style.opacity = "1";
  28079. imgBack.style.transform = "rotateZ(360deg)";
  28080. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28081. }, 0);
  28082. };
  28083. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28084. var _this = this;
  28085. if (!this._loadingDiv) {
  28086. return;
  28087. }
  28088. var onTransitionEnd = function () {
  28089. if (!_this._loadingDiv) {
  28090. return;
  28091. }
  28092. document.body.removeChild(_this._loadingDiv);
  28093. window.removeEventListener("resize", _this._resizeLoadingUI);
  28094. _this._loadingDiv = null;
  28095. };
  28096. this._loadingDiv.style.opacity = "0";
  28097. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28098. };
  28099. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28100. set: function (text) {
  28101. this._loadingText = text;
  28102. if (this._loadingTextDiv) {
  28103. this._loadingTextDiv.innerHTML = this._loadingText;
  28104. }
  28105. },
  28106. enumerable: true,
  28107. configurable: true
  28108. });
  28109. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28110. get: function () {
  28111. return this._loadingDivBackgroundColor;
  28112. },
  28113. set: function (color) {
  28114. this._loadingDivBackgroundColor = color;
  28115. if (!this._loadingDiv) {
  28116. return;
  28117. }
  28118. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28119. },
  28120. enumerable: true,
  28121. configurable: true
  28122. });
  28123. return DefaultLoadingScreen;
  28124. })();
  28125. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28126. })(BABYLON || (BABYLON = {}));
  28127. var BABYLON;
  28128. (function (BABYLON) {
  28129. var SIMDVector3 = (function () {
  28130. function SIMDVector3() {
  28131. }
  28132. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28133. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28134. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28135. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28136. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28137. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28138. 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));
  28139. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28140. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28141. };
  28142. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28143. var v0 = SIMD.float32x4.splat(x);
  28144. var v1 = SIMD.float32x4.splat(y);
  28145. var v2 = SIMD.float32x4.splat(z);
  28146. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28147. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28148. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28149. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28150. 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));
  28151. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28152. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28153. };
  28154. return SIMDVector3;
  28155. })();
  28156. BABYLON.SIMDVector3 = SIMDVector3;
  28157. var SIMDMatrix = (function () {
  28158. function SIMDMatrix() {
  28159. }
  28160. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28161. if (offset === void 0) { offset = 0; }
  28162. var tm = this.m;
  28163. var om = other.m;
  28164. var om0 = SIMD.float32x4.load(om, 0);
  28165. var om1 = SIMD.float32x4.load(om, 4);
  28166. var om2 = SIMD.float32x4.load(om, 8);
  28167. var om3 = SIMD.float32x4.load(om, 12);
  28168. var tm0 = SIMD.float32x4.load(tm, 0);
  28169. 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)))));
  28170. var tm1 = SIMD.float32x4.load(tm, 4);
  28171. 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)))));
  28172. var tm2 = SIMD.float32x4.load(tm, 8);
  28173. 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)))));
  28174. var tm3 = SIMD.float32x4.load(tm, 12);
  28175. 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)))));
  28176. };
  28177. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28178. var src = this.m;
  28179. var dest = other.m;
  28180. var row0, row1, row2, row3;
  28181. var tmp1;
  28182. var minor0, minor1, minor2, minor3;
  28183. var det;
  28184. // Load the 4 rows
  28185. var src0 = SIMD.float32x4.load(src, 0);
  28186. var src1 = SIMD.float32x4.load(src, 4);
  28187. var src2 = SIMD.float32x4.load(src, 8);
  28188. var src3 = SIMD.float32x4.load(src, 12);
  28189. // Transpose the source matrix. Sort of. Not a true transpose operation
  28190. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28191. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28192. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28193. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28194. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28195. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28196. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28197. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28198. // This is a true transposition, but it will lead to an incorrect result
  28199. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28200. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28201. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28202. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28203. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28204. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28205. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28206. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28207. // ----
  28208. tmp1 = SIMD.float32x4.mul(row2, row3);
  28209. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28210. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28211. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28212. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28213. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28214. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28215. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28216. // ----
  28217. tmp1 = SIMD.float32x4.mul(row1, row2);
  28218. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28219. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28220. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28221. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28222. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28223. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28224. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28225. // ----
  28226. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28227. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28228. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28229. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28230. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28231. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28232. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28233. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28234. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28235. // ----
  28236. tmp1 = SIMD.float32x4.mul(row0, row1);
  28237. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28238. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28239. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28240. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28241. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28242. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28243. // ----
  28244. tmp1 = SIMD.float32x4.mul(row0, row3);
  28245. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28246. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28247. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28248. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28249. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28250. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28251. // ----
  28252. tmp1 = SIMD.float32x4.mul(row0, row2);
  28253. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28254. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28255. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28256. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28257. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28258. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28259. // Compute determinant
  28260. det = SIMD.float32x4.mul(row0, minor0);
  28261. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28262. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28263. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28264. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28265. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28266. // These shuffles aren't necessary if the faulty transposition is done
  28267. // up at the top of this function.
  28268. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28269. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28270. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28271. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28272. // Compute final values by multiplying with 1/det
  28273. minor0 = SIMD.float32x4.mul(det, minor0);
  28274. minor1 = SIMD.float32x4.mul(det, minor1);
  28275. minor2 = SIMD.float32x4.mul(det, minor2);
  28276. minor3 = SIMD.float32x4.mul(det, minor3);
  28277. SIMD.float32x4.store(dest, 0, minor0);
  28278. SIMD.float32x4.store(dest, 4, minor1);
  28279. SIMD.float32x4.store(dest, 8, minor2);
  28280. SIMD.float32x4.store(dest, 12, minor3);
  28281. return this;
  28282. };
  28283. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28284. var out = result.m;
  28285. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28286. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28287. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28288. // cc.kmVec3Subtract(f, pCenter, pEye);
  28289. var f = SIMD.float32x4.sub(center, eye);
  28290. // cc.kmVec3Normalize(f, f);
  28291. var tmp = SIMD.float32x4.mul(f, f);
  28292. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28293. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28294. // cc.kmVec3Assign(up, pUp);
  28295. // cc.kmVec3Normalize(up, up);
  28296. tmp = SIMD.float32x4.mul(up, up);
  28297. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28298. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28299. // cc.kmVec3Cross(s, f, up);
  28300. 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)));
  28301. // cc.kmVec3Normalize(s, s);
  28302. tmp = SIMD.float32x4.mul(s, s);
  28303. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28304. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28305. // cc.kmVec3Cross(u, s, f);
  28306. 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)));
  28307. // cc.kmVec3Normalize(s, s);
  28308. tmp = SIMD.float32x4.mul(s, s);
  28309. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28310. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28311. var zero = SIMD.float32x4.splat(0.0);
  28312. s = SIMD.float32x4.neg(s);
  28313. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28314. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28315. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28316. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28317. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28318. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28319. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28320. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28321. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28322. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28323. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28324. var b3 = SIMD.float32x4.neg(eye);
  28325. b3 = SIMD.float32x4.withW(b3, 1.0);
  28326. 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)))));
  28327. 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)))));
  28328. 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)))));
  28329. 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)))));
  28330. };
  28331. return SIMDMatrix;
  28332. })();
  28333. BABYLON.SIMDMatrix = SIMDMatrix;
  28334. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28335. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28336. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28337. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28338. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28339. var SIMDHelper = (function () {
  28340. function SIMDHelper() {
  28341. }
  28342. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28343. get: function () {
  28344. return SIMDHelper._isEnabled;
  28345. },
  28346. enumerable: true,
  28347. configurable: true
  28348. });
  28349. SIMDHelper.DisableSIMD = function () {
  28350. // Replace functions
  28351. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28352. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28353. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28354. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28356. SIMDHelper._isEnabled = false;
  28357. };
  28358. SIMDHelper.EnableSIMD = function () {
  28359. if (window.SIMD === undefined) {
  28360. return;
  28361. }
  28362. // Replace functions
  28363. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28364. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28365. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28366. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28367. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28368. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28369. get: function () { return this._data[0]; },
  28370. set: function (value) {
  28371. if (!this._data) {
  28372. this._data = new Float32Array(3);
  28373. }
  28374. this._data[0] = value;
  28375. }
  28376. });
  28377. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28378. get: function () { return this._data[1]; },
  28379. set: function (value) {
  28380. this._data[1] = value;
  28381. }
  28382. });
  28383. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28384. get: function () { return this._data[2]; },
  28385. set: function (value) {
  28386. this._data[2] = value;
  28387. }
  28388. });
  28389. SIMDHelper._isEnabled = true;
  28390. };
  28391. SIMDHelper._isEnabled = false;
  28392. return SIMDHelper;
  28393. })();
  28394. BABYLON.SIMDHelper = SIMDHelper;
  28395. })(BABYLON || (BABYLON = {}));
  28396. var BABYLON;
  28397. (function (BABYLON) {
  28398. var ShaderMaterial = (function (_super) {
  28399. __extends(ShaderMaterial, _super);
  28400. function ShaderMaterial(name, scene, shaderPath, options) {
  28401. _super.call(this, name, scene);
  28402. this._textures = {};
  28403. this._floats = {};
  28404. this._floatsArrays = {};
  28405. this._colors3 = {};
  28406. this._colors4 = {};
  28407. this._vectors2 = {};
  28408. this._vectors3 = {};
  28409. this._vectors4 = {};
  28410. this._matrices = {};
  28411. this._matrices3x3 = {};
  28412. this._matrices2x2 = {};
  28413. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28414. this._shaderPath = shaderPath;
  28415. options.needAlphaBlending = options.needAlphaBlending || false;
  28416. options.needAlphaTesting = options.needAlphaTesting || false;
  28417. options.attributes = options.attributes || ["position", "normal", "uv"];
  28418. options.uniforms = options.uniforms || ["worldViewProjection"];
  28419. options.samplers = options.samplers || [];
  28420. options.defines = options.defines || [];
  28421. this._options = options;
  28422. }
  28423. ShaderMaterial.prototype.needAlphaBlending = function () {
  28424. return this._options.needAlphaBlending;
  28425. };
  28426. ShaderMaterial.prototype.needAlphaTesting = function () {
  28427. return this._options.needAlphaTesting;
  28428. };
  28429. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28430. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28431. this._options.uniforms.push(uniformName);
  28432. }
  28433. };
  28434. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28435. if (this._options.samplers.indexOf(name) === -1) {
  28436. this._options.samplers.push(name);
  28437. }
  28438. this._textures[name] = texture;
  28439. return this;
  28440. };
  28441. ShaderMaterial.prototype.setFloat = function (name, value) {
  28442. this._checkUniform(name);
  28443. this._floats[name] = value;
  28444. return this;
  28445. };
  28446. ShaderMaterial.prototype.setFloats = function (name, value) {
  28447. this._checkUniform(name);
  28448. this._floatsArrays[name] = value;
  28449. return this;
  28450. };
  28451. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28452. this._checkUniform(name);
  28453. this._colors3[name] = value;
  28454. return this;
  28455. };
  28456. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28457. this._checkUniform(name);
  28458. this._colors4[name] = value;
  28459. return this;
  28460. };
  28461. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28462. this._checkUniform(name);
  28463. this._vectors2[name] = value;
  28464. return this;
  28465. };
  28466. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28467. this._checkUniform(name);
  28468. this._vectors3[name] = value;
  28469. return this;
  28470. };
  28471. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28472. this._checkUniform(name);
  28473. this._vectors4[name] = value;
  28474. return this;
  28475. };
  28476. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28477. this._checkUniform(name);
  28478. this._matrices[name] = value;
  28479. return this;
  28480. };
  28481. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28482. this._checkUniform(name);
  28483. this._matrices3x3[name] = value;
  28484. return this;
  28485. };
  28486. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28487. this._checkUniform(name);
  28488. this._matrices2x2[name] = value;
  28489. return this;
  28490. };
  28491. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28492. var scene = this.getScene();
  28493. var engine = scene.getEngine();
  28494. if (!this.checkReadyOnEveryCall) {
  28495. if (this._renderId === scene.getRenderId()) {
  28496. return true;
  28497. }
  28498. }
  28499. // Instances
  28500. var defines = [];
  28501. var fallbacks = new BABYLON.EffectFallbacks();
  28502. if (useInstances) {
  28503. defines.push("#define INSTANCES");
  28504. }
  28505. for (var index = 0; index < this._options.defines.length; index++) {
  28506. defines.push(this._options.defines[index]);
  28507. }
  28508. // Bones
  28509. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28512. fallbacks.addCPUSkinningFallback(0, mesh);
  28513. }
  28514. // Alpha test
  28515. if (engine.getAlphaTesting()) {
  28516. defines.push("#define ALPHATEST");
  28517. }
  28518. var previousEffect = this._effect;
  28519. var join = defines.join("\n");
  28520. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28521. if (!this._effect.isReady()) {
  28522. return false;
  28523. }
  28524. if (previousEffect !== this._effect) {
  28525. scene.resetCachedMaterial();
  28526. }
  28527. this._renderId = scene.getRenderId();
  28528. return true;
  28529. };
  28530. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28531. var scene = this.getScene();
  28532. if (this._options.uniforms.indexOf("world") !== -1) {
  28533. this._effect.setMatrix("world", world);
  28534. }
  28535. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28536. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28537. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28538. }
  28539. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28540. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28541. }
  28542. };
  28543. ShaderMaterial.prototype.bind = function (world, mesh) {
  28544. // Std values
  28545. this.bindOnlyWorldMatrix(world);
  28546. if (this.getScene().getCachedMaterial() !== this) {
  28547. if (this._options.uniforms.indexOf("view") !== -1) {
  28548. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28549. }
  28550. if (this._options.uniforms.indexOf("projection") !== -1) {
  28551. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28552. }
  28553. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28554. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28555. }
  28556. // Bones
  28557. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28558. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28559. }
  28560. // Texture
  28561. for (var name in this._textures) {
  28562. this._effect.setTexture(name, this._textures[name]);
  28563. }
  28564. // Float
  28565. for (name in this._floats) {
  28566. this._effect.setFloat(name, this._floats[name]);
  28567. }
  28568. // Float s
  28569. for (name in this._floatsArrays) {
  28570. this._effect.setArray(name, this._floatsArrays[name]);
  28571. }
  28572. // Color3
  28573. for (name in this._colors3) {
  28574. this._effect.setColor3(name, this._colors3[name]);
  28575. }
  28576. // Color4
  28577. for (name in this._colors4) {
  28578. var color = this._colors4[name];
  28579. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28580. }
  28581. // Vector2
  28582. for (name in this._vectors2) {
  28583. this._effect.setVector2(name, this._vectors2[name]);
  28584. }
  28585. // Vector3
  28586. for (name in this._vectors3) {
  28587. this._effect.setVector3(name, this._vectors3[name]);
  28588. }
  28589. // Vector4
  28590. for (name in this._vectors4) {
  28591. this._effect.setVector4(name, this._vectors4[name]);
  28592. }
  28593. // Matrix
  28594. for (name in this._matrices) {
  28595. this._effect.setMatrix(name, this._matrices[name]);
  28596. }
  28597. // Matrix 3x3
  28598. for (name in this._matrices3x3) {
  28599. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28600. }
  28601. // Matrix 2x2
  28602. for (name in this._matrices2x2) {
  28603. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28604. }
  28605. }
  28606. _super.prototype.bind.call(this, world, mesh);
  28607. };
  28608. ShaderMaterial.prototype.clone = function (name) {
  28609. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28610. return newShaderMaterial;
  28611. };
  28612. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28613. for (var name in this._textures) {
  28614. this._textures[name].dispose();
  28615. }
  28616. this._textures = {};
  28617. _super.prototype.dispose.call(this, forceDisposeEffect);
  28618. };
  28619. ShaderMaterial.prototype.serialize = function () {
  28620. var serializationObject = _super.prototype.serialize.call(this);
  28621. serializationObject.options = this._options;
  28622. serializationObject.shaderPath = this._shaderPath;
  28623. serializationObject.customType = "BABYLON.ShaderMaterial";
  28624. // Texture
  28625. serializationObject.textures = {};
  28626. for (var name in this._textures) {
  28627. serializationObject.textures[name] = this._textures[name].serialize();
  28628. }
  28629. // Float
  28630. serializationObject.floats = {};
  28631. for (name in this._floats) {
  28632. serializationObject.floats[name] = this._floats[name];
  28633. }
  28634. // Float s
  28635. serializationObject.floatArrays = {};
  28636. for (name in this._floatsArrays) {
  28637. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28638. }
  28639. // Color3
  28640. serializationObject.colors3 = {};
  28641. for (name in this._colors3) {
  28642. serializationObject.colors3[name] = this._colors3[name].asArray();
  28643. }
  28644. // Color4
  28645. serializationObject.colors4 = {};
  28646. for (name in this._colors4) {
  28647. serializationObject.colors4[name] = this._colors4[name].asArray();
  28648. }
  28649. // Vector2
  28650. serializationObject.vectors2 = {};
  28651. for (name in this._vectors2) {
  28652. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28653. }
  28654. // Vector3
  28655. serializationObject.vectors3 = {};
  28656. for (name in this._vectors3) {
  28657. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28658. }
  28659. // Vector4
  28660. serializationObject.vectors4 = {};
  28661. for (name in this._vectors4) {
  28662. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28663. }
  28664. // Matrix
  28665. serializationObject.matrices = {};
  28666. for (name in this._matrices) {
  28667. serializationObject.matrices[name] = this._matrices[name].asArray();
  28668. }
  28669. // Matrix 3x3
  28670. serializationObject.matrices3x3 = {};
  28671. for (name in this._matrices3x3) {
  28672. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28673. }
  28674. // Matrix 2x2
  28675. serializationObject.matrices2x2 = {};
  28676. for (name in this._matrices2x2) {
  28677. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28678. }
  28679. return serializationObject;
  28680. };
  28681. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28682. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28683. // Texture
  28684. for (var name in source.textures) {
  28685. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28686. }
  28687. // Float
  28688. for (name in source.floats) {
  28689. material.setFloat(name, source.floats[name]);
  28690. }
  28691. // Float s
  28692. for (name in source.floatsArrays) {
  28693. material.setFloats(name, source.floatsArrays[name]);
  28694. }
  28695. // Color3
  28696. for (name in source.colors3) {
  28697. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28698. }
  28699. // Color4
  28700. for (name in source.colors4) {
  28701. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28702. }
  28703. // Vector2
  28704. for (name in source.vectors2) {
  28705. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28706. }
  28707. // Vector3
  28708. for (name in source.vectors3) {
  28709. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28710. }
  28711. // Vector4
  28712. for (name in source.vectors4) {
  28713. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28714. }
  28715. // Matrix
  28716. for (name in source.matrices) {
  28717. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28718. }
  28719. // Matrix 3x3
  28720. for (name in source.matrices3x3) {
  28721. material.setMatrix3x3(name, source.matrices3x3[name]);
  28722. }
  28723. // Matrix 2x2
  28724. for (name in source.matrices2x2) {
  28725. material.setMatrix2x2(name, source.matrices2x2[name]);
  28726. }
  28727. return material;
  28728. };
  28729. return ShaderMaterial;
  28730. })(BABYLON.Material);
  28731. BABYLON.ShaderMaterial = ShaderMaterial;
  28732. })(BABYLON || (BABYLON = {}));
  28733. var BABYLON;
  28734. (function (BABYLON) {
  28735. var Internals;
  28736. (function (Internals) {
  28737. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28738. // All values and structures referenced from:
  28739. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28740. var DDS_MAGIC = 0x20534444;
  28741. 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;
  28742. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28743. 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;
  28744. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28745. function FourCCToInt32(value) {
  28746. return value.charCodeAt(0) +
  28747. (value.charCodeAt(1) << 8) +
  28748. (value.charCodeAt(2) << 16) +
  28749. (value.charCodeAt(3) << 24);
  28750. }
  28751. function Int32ToFourCC(value) {
  28752. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28753. }
  28754. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28755. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28756. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28757. var headerLengthInt = 31; // The header length in 32 bit ints
  28758. // Offsets into the header array
  28759. var off_magic = 0;
  28760. var off_size = 1;
  28761. var off_flags = 2;
  28762. var off_height = 3;
  28763. var off_width = 4;
  28764. var off_mipmapCount = 7;
  28765. var off_pfFlags = 20;
  28766. var off_pfFourCC = 21;
  28767. var off_RGBbpp = 22;
  28768. var off_RMask = 23;
  28769. var off_GMask = 24;
  28770. var off_BMask = 25;
  28771. var off_AMask = 26;
  28772. var off_caps1 = 27;
  28773. var off_caps2 = 28;
  28774. ;
  28775. var DDSTools = (function () {
  28776. function DDSTools() {
  28777. }
  28778. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28779. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28780. var mipmapCount = 1;
  28781. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28782. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28783. }
  28784. return {
  28785. width: header[off_width],
  28786. height: header[off_height],
  28787. mipmapCount: mipmapCount,
  28788. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28789. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28790. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28791. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28792. };
  28793. };
  28794. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28795. var byteArray = new Uint8Array(dataLength);
  28796. var srcData = new Uint8Array(arrayBuffer);
  28797. var index = 0;
  28798. for (var y = height - 1; y >= 0; y--) {
  28799. for (var x = 0; x < width; x++) {
  28800. var srcPos = dataOffset + (x + y * width) * 4;
  28801. byteArray[index + 2] = srcData[srcPos];
  28802. byteArray[index + 1] = srcData[srcPos + 1];
  28803. byteArray[index] = srcData[srcPos + 2];
  28804. byteArray[index + 3] = srcData[srcPos + 3];
  28805. index += 4;
  28806. }
  28807. }
  28808. return byteArray;
  28809. };
  28810. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28811. var byteArray = new Uint8Array(dataLength);
  28812. var srcData = new Uint8Array(arrayBuffer);
  28813. var index = 0;
  28814. for (var y = height - 1; y >= 0; y--) {
  28815. for (var x = 0; x < width; x++) {
  28816. var srcPos = dataOffset + (x + y * width) * 3;
  28817. byteArray[index + 2] = srcData[srcPos];
  28818. byteArray[index + 1] = srcData[srcPos + 1];
  28819. byteArray[index] = srcData[srcPos + 2];
  28820. index += 3;
  28821. }
  28822. }
  28823. return byteArray;
  28824. };
  28825. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28826. var byteArray = new Uint8Array(dataLength);
  28827. var srcData = new Uint8Array(arrayBuffer);
  28828. var index = 0;
  28829. for (var y = height - 1; y >= 0; y--) {
  28830. for (var x = 0; x < width; x++) {
  28831. var srcPos = dataOffset + (x + y * width);
  28832. byteArray[index] = srcData[srcPos];
  28833. index++;
  28834. }
  28835. }
  28836. return byteArray;
  28837. };
  28838. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28839. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28840. if (header[off_magic] != DDS_MAGIC) {
  28841. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28842. return;
  28843. }
  28844. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28845. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28846. return;
  28847. }
  28848. if (info.isFourCC) {
  28849. fourCC = header[off_pfFourCC];
  28850. switch (fourCC) {
  28851. case FOURCC_DXT1:
  28852. blockBytes = 8;
  28853. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28854. break;
  28855. case FOURCC_DXT3:
  28856. blockBytes = 16;
  28857. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28858. break;
  28859. case FOURCC_DXT5:
  28860. blockBytes = 16;
  28861. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28862. break;
  28863. default:
  28864. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28865. return;
  28866. }
  28867. }
  28868. mipmapCount = 1;
  28869. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28870. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28871. }
  28872. var bpp = header[off_RGBbpp];
  28873. for (var face = 0; face < faces; face++) {
  28874. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28875. width = header[off_width];
  28876. height = header[off_height];
  28877. dataOffset = header[off_size] + 4;
  28878. for (i = 0; i < mipmapCount; ++i) {
  28879. if (info.isRGB) {
  28880. if (bpp === 24) {
  28881. dataLength = width * height * 3;
  28882. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28883. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28884. }
  28885. else {
  28886. dataLength = width * height * 4;
  28887. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28888. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28889. }
  28890. }
  28891. else if (info.isLuminance) {
  28892. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28893. var unpaddedRowSize = width;
  28894. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28895. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28896. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28897. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28898. }
  28899. else {
  28900. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28901. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28902. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28903. }
  28904. dataOffset += dataLength;
  28905. width *= 0.5;
  28906. height *= 0.5;
  28907. width = Math.max(1.0, width);
  28908. height = Math.max(1.0, height);
  28909. }
  28910. }
  28911. };
  28912. return DDSTools;
  28913. })();
  28914. Internals.DDSTools = DDSTools;
  28915. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28916. })(BABYLON || (BABYLON = {}));
  28917. var BABYLON;
  28918. (function (BABYLON) {
  28919. var CannonJSPlugin = (function () {
  28920. function CannonJSPlugin() {
  28921. this._registeredMeshes = [];
  28922. this._physicsMaterials = [];
  28923. this.name = "cannon";
  28924. this.updateBodyPosition = function (mesh) {
  28925. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28926. var registeredMesh = this._registeredMeshes[index];
  28927. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28928. var body = registeredMesh.body;
  28929. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28930. body.quaternion.copy(mesh.rotationQuaternion);
  28931. if (registeredMesh.deltaRotation) {
  28932. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28933. body.quaternion = body.quaternion.mult(tmpQ);
  28934. }
  28935. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  28936. //calculate the correct body position:
  28937. var rotationQuaternion = mesh.rotationQuaternion;
  28938. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28939. mesh.computeWorldMatrix(true);
  28940. //get original center with no rotation
  28941. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28942. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28943. //rotation is back
  28944. mesh.rotationQuaternion = rotationQuaternion;
  28945. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28946. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28947. mesh.setPivotMatrix(p);
  28948. mesh.computeWorldMatrix(true);
  28949. //calculate the translation
  28950. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28951. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28952. //add it inverted to the delta
  28953. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28954. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28955. mesh.setPivotMatrix(oldPivot);
  28956. mesh.computeWorldMatrix(true);
  28957. }
  28958. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  28959. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  28960. }
  28961. body.position.set(center.x, center.y, center.z);
  28962. return;
  28963. }
  28964. }
  28965. };
  28966. }
  28967. CannonJSPlugin.prototype.initialize = function (iterations) {
  28968. if (iterations === void 0) { iterations = 10; }
  28969. this._world = new CANNON.World();
  28970. this._world.broadphase = new CANNON.NaiveBroadphase();
  28971. this._world.solver.iterations = iterations;
  28972. };
  28973. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28974. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28975. };
  28976. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28977. var _this = this;
  28978. this._world.step(delta);
  28979. this._registeredMeshes.forEach(function (registeredMesh) {
  28980. // Body position
  28981. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28982. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28983. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28984. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28985. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28986. if (registeredMesh.deltaRotation) {
  28987. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28988. }
  28989. //is the physics collision callback is set?
  28990. if (registeredMesh.mesh.onPhysicsCollide) {
  28991. if (!registeredMesh.collisionFunction) {
  28992. registeredMesh.collisionFunction = function (e) {
  28993. //find the mesh that collided with the registered mesh
  28994. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28995. if (_this._registeredMeshes[idx].body == e.body) {
  28996. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  28997. }
  28998. }
  28999. };
  29000. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29001. }
  29002. }
  29003. else {
  29004. //unregister, in case the function was removed for some reason
  29005. if (registeredMesh.collisionFunction) {
  29006. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29007. }
  29008. }
  29009. });
  29010. };
  29011. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29012. this._gravity = gravity;
  29013. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29014. };
  29015. CannonJSPlugin.prototype.getGravity = function () {
  29016. return this._gravity;
  29017. };
  29018. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29019. this.unregisterMesh(mesh);
  29020. if (!mesh.rotationQuaternion) {
  29021. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29022. }
  29023. mesh.computeWorldMatrix(true);
  29024. var shape = this._createShape(mesh, impostor);
  29025. return this._createRigidBodyFromShape(shape, mesh, options);
  29026. };
  29027. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29028. //get the correct bounding box
  29029. var oldQuaternion = mesh.rotationQuaternion;
  29030. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29031. mesh.computeWorldMatrix(true);
  29032. var returnValue;
  29033. switch (impostor) {
  29034. case BABYLON.PhysicsEngine.SphereImpostor:
  29035. var bbox = mesh.getBoundingInfo().boundingBox;
  29036. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29037. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29038. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29039. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29040. break;
  29041. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29042. case BABYLON.PhysicsEngine.CylinderImpostor:
  29043. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29044. case BABYLON.PhysicsEngine.BoxImpostor:
  29045. bbox = mesh.getBoundingInfo().boundingBox;
  29046. var min = bbox.minimumWorld;
  29047. var max = bbox.maximumWorld;
  29048. var box = max.subtract(min).scale(0.5);
  29049. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29050. break;
  29051. case BABYLON.PhysicsEngine.PlaneImpostor:
  29052. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29053. returnValue = new CANNON.Plane();
  29054. break;
  29055. case BABYLON.PhysicsEngine.MeshImpostor:
  29056. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29057. var rawFaces = mesh.getIndices();
  29058. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29059. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29060. break;
  29061. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29062. returnValue = this._createHeightmap(mesh);
  29063. break;
  29064. }
  29065. mesh.rotationQuaternion = oldQuaternion;
  29066. return returnValue;
  29067. };
  29068. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29069. var verts = [], faces = [];
  29070. mesh.computeWorldMatrix(true);
  29071. //reuse this variable
  29072. var transformed = BABYLON.Vector3.Zero();
  29073. // Get vertices
  29074. for (var i = 0; i < rawVerts.length; i += 3) {
  29075. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29076. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29077. }
  29078. // Get faces
  29079. for (var j = 0; j < rawFaces.length; j += 3) {
  29080. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29081. }
  29082. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29083. return shape;
  29084. };
  29085. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29086. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29087. var matrix = [];
  29088. //For now pointDepth will not be used and will be automatically calculated.
  29089. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29090. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29091. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29092. var elementSize = dim * 2 / arraySize;
  29093. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29094. for (var i = 0; i < pos.length; i = i + 3) {
  29095. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29096. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29097. var y = pos[i + 1] + minY;
  29098. if (!matrix[x]) {
  29099. matrix[x] = [];
  29100. }
  29101. if (!matrix[x][z]) {
  29102. matrix[x][z] = y;
  29103. }
  29104. matrix[x][z] = Math.max(y, matrix[x][z]);
  29105. }
  29106. for (var x = 0; x <= arraySize; ++x) {
  29107. if (!matrix[x]) {
  29108. var loc = 1;
  29109. while (!matrix[(x + loc) % arraySize]) {
  29110. loc++;
  29111. }
  29112. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29113. }
  29114. for (var z = 0; z <= arraySize; ++z) {
  29115. if (!matrix[x][z]) {
  29116. var loc = 1;
  29117. var newValue;
  29118. while (newValue === undefined) {
  29119. newValue = matrix[x][(z + loc++) % arraySize];
  29120. }
  29121. matrix[x][z] = newValue;
  29122. }
  29123. }
  29124. }
  29125. var shape = new CANNON.Heightfield(matrix, {
  29126. elementSize: elementSize
  29127. });
  29128. //For future reference, needed for body transformation
  29129. shape.minY = minY;
  29130. return shape;
  29131. };
  29132. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29133. var index;
  29134. var mat;
  29135. for (index = 0; index < this._physicsMaterials.length; index++) {
  29136. mat = this._physicsMaterials[index];
  29137. if (mat.friction === friction && mat.restitution === restitution) {
  29138. return mat;
  29139. }
  29140. }
  29141. var currentMat = new CANNON.Material("mat");
  29142. this._physicsMaterials.push(currentMat);
  29143. for (index = 0; index < this._physicsMaterials.length; index++) {
  29144. mat = this._physicsMaterials[index];
  29145. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29146. this._world.addContactMaterial(contactMaterial);
  29147. }
  29148. return currentMat;
  29149. };
  29150. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29151. if (!mesh.rotationQuaternion) {
  29152. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29153. }
  29154. // The delta between the mesh position and the mesh bounding box center
  29155. var bbox = mesh.getBoundingInfo().boundingBox;
  29156. var deltaPosition = mesh.position.subtract(bbox.center);
  29157. var deltaRotation;
  29158. var material = this._addMaterial(options.friction, options.restitution);
  29159. var body = new CANNON.Body({
  29160. mass: options.mass,
  29161. material: material,
  29162. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29163. });
  29164. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29165. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29166. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29167. //-90 DEG in X, precalculated
  29168. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29169. body.quaternion = body.quaternion.mult(tmpQ);
  29170. //Invert! (Precalculated, 90 deg in X)
  29171. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29172. }
  29173. //If it is a heightfield, if should be centered.
  29174. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29175. //calculate the correct body position:
  29176. var rotationQuaternion = mesh.rotationQuaternion;
  29177. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29178. mesh.computeWorldMatrix(true);
  29179. //get original center with no rotation
  29180. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29181. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29182. //rotation is back
  29183. mesh.rotationQuaternion = rotationQuaternion;
  29184. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29185. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29186. mesh.setPivotMatrix(p);
  29187. mesh.computeWorldMatrix(true);
  29188. //calculate the translation
  29189. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29190. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29191. //add it inverted to the delta
  29192. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29193. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29194. mesh.setPivotMatrix(oldPivot);
  29195. mesh.computeWorldMatrix(true);
  29196. }
  29197. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29198. deltaPosition = BABYLON.Vector3.Zero();
  29199. }
  29200. //add the shape
  29201. body.addShape(shape);
  29202. this._world.add(body);
  29203. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29204. return body;
  29205. };
  29206. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29207. var initialMesh = parts[0].mesh;
  29208. this.unregisterMesh(initialMesh);
  29209. initialMesh.computeWorldMatrix(true);
  29210. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29211. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29212. for (var index = 1; index < parts.length; index++) {
  29213. var mesh = parts[index].mesh;
  29214. mesh.computeWorldMatrix(true);
  29215. var shape = this._createShape(mesh, parts[index].impostor);
  29216. var localPosition = mesh.position;
  29217. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29218. }
  29219. return body;
  29220. };
  29221. CannonJSPlugin.prototype._unbindBody = function (body) {
  29222. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29223. var registeredMesh = this._registeredMeshes[index];
  29224. if (registeredMesh.body === body) {
  29225. this._world.remove(registeredMesh.body);
  29226. registeredMesh.body = null;
  29227. registeredMesh.delta = null;
  29228. registeredMesh.deltaRotation = null;
  29229. }
  29230. }
  29231. };
  29232. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29233. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29234. var registeredMesh = this._registeredMeshes[index];
  29235. if (registeredMesh.mesh === mesh) {
  29236. // Remove body
  29237. if (registeredMesh.body) {
  29238. this._unbindBody(registeredMesh.body);
  29239. }
  29240. this._registeredMeshes.splice(index, 1);
  29241. return;
  29242. }
  29243. }
  29244. };
  29245. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29246. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29247. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29248. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29249. var registeredMesh = this._registeredMeshes[index];
  29250. if (registeredMesh.mesh === mesh) {
  29251. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29252. return;
  29253. }
  29254. }
  29255. };
  29256. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29257. var body1 = null, body2 = null;
  29258. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29259. var registeredMesh = this._registeredMeshes[index];
  29260. if (registeredMesh.mesh === mesh1) {
  29261. body1 = registeredMesh.body;
  29262. }
  29263. else if (registeredMesh.mesh === mesh2) {
  29264. body2 = registeredMesh.body;
  29265. }
  29266. }
  29267. if (!body1 || !body2) {
  29268. return false;
  29269. }
  29270. 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));
  29271. this._world.addConstraint(constraint);
  29272. return true;
  29273. };
  29274. CannonJSPlugin.prototype.dispose = function () {
  29275. while (this._registeredMeshes.length) {
  29276. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29277. }
  29278. };
  29279. CannonJSPlugin.prototype.isSupported = function () {
  29280. return window.CANNON !== undefined;
  29281. };
  29282. CannonJSPlugin.prototype.getWorldObject = function () {
  29283. return this._world;
  29284. };
  29285. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29286. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29287. var registeredMesh = this._registeredMeshes[index];
  29288. if (registeredMesh.mesh === mesh) {
  29289. return registeredMesh.body;
  29290. }
  29291. }
  29292. return null;
  29293. };
  29294. return CannonJSPlugin;
  29295. })();
  29296. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29297. })(BABYLON || (BABYLON = {}));
  29298. var BABYLON;
  29299. (function (BABYLON) {
  29300. var OimoJSPlugin = (function () {
  29301. function OimoJSPlugin() {
  29302. this._registeredMeshes = [];
  29303. this.name = "oimo";
  29304. /**
  29305. * Update the body position according to the mesh position
  29306. * @param mesh
  29307. */
  29308. this.updateBodyPosition = function (mesh) {
  29309. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29310. var registeredMesh = this._registeredMeshes[index];
  29311. var body = registeredMesh.body.body;
  29312. var updated = false;
  29313. var newPosition;
  29314. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29315. mesh.computeWorldMatrix(true);
  29316. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29317. updated = true;
  29318. }
  29319. else if (registeredMesh.mesh.parent === mesh) {
  29320. mesh.computeWorldMatrix(true);
  29321. registeredMesh.mesh.computeWorldMatrix(true);
  29322. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29323. updated = true;
  29324. }
  29325. if (updated) {
  29326. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29327. body.setQuaternion(mesh.rotationQuaternion);
  29328. body.sleeping = false;
  29329. //force Oimo to update the body's position
  29330. body.updatePosition(1);
  29331. }
  29332. }
  29333. };
  29334. }
  29335. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29336. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29337. };
  29338. OimoJSPlugin.prototype.initialize = function (iterations) {
  29339. this._world = new OIMO.World(null, null, iterations);
  29340. this._world.clear();
  29341. };
  29342. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29343. this._gravity = this._world.gravity = gravity;
  29344. };
  29345. OimoJSPlugin.prototype.getGravity = function () {
  29346. return this._gravity;
  29347. };
  29348. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29349. this.unregisterMesh(mesh);
  29350. if (!mesh.rotationQuaternion) {
  29351. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29352. }
  29353. mesh.computeWorldMatrix(true);
  29354. var bbox = mesh.getBoundingInfo().boundingBox;
  29355. // The delta between the mesh position and the mesh bounding box center
  29356. var deltaPosition = mesh.position.subtract(bbox.center);
  29357. //calculate rotation to fit Oimo's needs (Euler...)
  29358. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29359. //get the correct bounding box
  29360. var oldQuaternion = mesh.rotationQuaternion;
  29361. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29362. mesh.computeWorldMatrix(true);
  29363. var bodyConfig = {
  29364. name: mesh.uniqueId,
  29365. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29366. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29367. move: options.mass != 0,
  29368. config: [options.mass, options.friction, options.restitution],
  29369. world: this._world
  29370. };
  29371. // register mesh
  29372. switch (impostor) {
  29373. case BABYLON.PhysicsEngine.SphereImpostor:
  29374. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29375. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29376. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29377. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29378. bodyConfig.type = 'sphere';
  29379. bodyConfig.size = [size];
  29380. break;
  29381. case BABYLON.PhysicsEngine.PlaneImpostor:
  29382. //Oimo "fakes" a cylinder as a box, so why don't we!
  29383. case BABYLON.PhysicsEngine.CylinderImpostor:
  29384. case BABYLON.PhysicsEngine.BoxImpostor:
  29385. var min = bbox.minimumWorld;
  29386. var max = bbox.maximumWorld;
  29387. var box = max.subtract(min);
  29388. var sizeX = this._checkWithEpsilon(box.x);
  29389. var sizeY = this._checkWithEpsilon(box.y);
  29390. var sizeZ = this._checkWithEpsilon(box.z);
  29391. bodyConfig.type = 'box';
  29392. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29393. break;
  29394. }
  29395. var body = new OIMO.Body(bodyConfig);
  29396. //We have to access the rigid body's properties to set the quaternion.
  29397. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29398. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29399. //TEST
  29400. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29401. //update the internal rotation matrix
  29402. //body.body.syncShapes();
  29403. this._registeredMeshes.push({
  29404. mesh: mesh,
  29405. body: body,
  29406. delta: deltaPosition
  29407. });
  29408. //for the sake of consistency.
  29409. mesh.rotationQuaternion = oldQuaternion;
  29410. return body;
  29411. };
  29412. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29413. var types = [], sizes = [], positions = [], rotations = [];
  29414. var initialMesh = parts[0].mesh;
  29415. for (var index = 0; index < parts.length; index++) {
  29416. var part = parts[index];
  29417. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29418. types.push(bodyParameters.type);
  29419. sizes.push.apply(sizes, bodyParameters.size);
  29420. positions.push.apply(positions, bodyParameters.pos);
  29421. rotations.push.apply(rotations, bodyParameters.rot);
  29422. }
  29423. var body = new OIMO.Body({
  29424. name: initialMesh.uniqueId,
  29425. type: types,
  29426. size: sizes,
  29427. pos: positions,
  29428. rot: rotations,
  29429. move: options.mass != 0,
  29430. config: [options.mass, options.friction, options.restitution],
  29431. world: this._world
  29432. });
  29433. //Reset the body's rotation to be of the initial mesh's.
  29434. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29435. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29436. this._registeredMeshes.push({
  29437. mesh: initialMesh,
  29438. body: body
  29439. });
  29440. return body;
  29441. };
  29442. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29443. var mesh = part.mesh;
  29444. if (!mesh.rotationQuaternion) {
  29445. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29446. }
  29447. // We need the bounding box/sphere info to compute the physics body
  29448. mesh.computeWorldMatrix(true);
  29449. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29450. var bodyParameters = {
  29451. name: mesh.uniqueId,
  29452. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29453. //A bug in Oimo (Body class) prevents us from using rot directly.
  29454. rot: [0, 0, 0],
  29455. //For future reference, if the bug will ever be fixed.
  29456. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29457. };
  29458. var oldQuaternion = mesh.rotationQuaternion;
  29459. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29460. mesh.computeWorldMatrix(true);
  29461. switch (part.impostor) {
  29462. case BABYLON.PhysicsEngine.SphereImpostor:
  29463. var bbox = mesh.getBoundingInfo().boundingBox;
  29464. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29465. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29466. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29467. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29468. bodyParameters.type = 'sphere';
  29469. bodyParameters.size = [size, size, size];
  29470. break;
  29471. case BABYLON.PhysicsEngine.PlaneImpostor:
  29472. case BABYLON.PhysicsEngine.CylinderImpostor:
  29473. case BABYLON.PhysicsEngine.BoxImpostor:
  29474. bbox = mesh.getBoundingInfo().boundingBox;
  29475. var min = bbox.minimumWorld;
  29476. var max = bbox.maximumWorld;
  29477. var box = max.subtract(min);
  29478. var sizeX = this._checkWithEpsilon(box.x);
  29479. var sizeY = this._checkWithEpsilon(box.y);
  29480. var sizeZ = this._checkWithEpsilon(box.z);
  29481. bodyParameters.type = 'box';
  29482. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29483. break;
  29484. }
  29485. mesh.rotationQuaternion = oldQuaternion;
  29486. return bodyParameters;
  29487. };
  29488. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29489. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29490. var registeredMesh = this._registeredMeshes[index];
  29491. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29492. if (registeredMesh.body) {
  29493. this._world.removeRigidBody(registeredMesh.body.body);
  29494. this._unbindBody(registeredMesh.body);
  29495. }
  29496. this._registeredMeshes.splice(index, 1);
  29497. return;
  29498. }
  29499. }
  29500. };
  29501. OimoJSPlugin.prototype._unbindBody = function (body) {
  29502. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29503. var registeredMesh = this._registeredMeshes[index];
  29504. if (registeredMesh.body === body) {
  29505. registeredMesh.body = null;
  29506. }
  29507. }
  29508. };
  29509. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29510. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29511. var registeredMesh = this._registeredMeshes[index];
  29512. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29513. // Get object mass to have a behaviour similar to cannon.js
  29514. var mass = registeredMesh.body.body.massInfo.mass;
  29515. // The force is scaled with the mass of object
  29516. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29517. return;
  29518. }
  29519. }
  29520. };
  29521. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29522. var body1 = null, body2 = null;
  29523. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29524. var registeredMesh = this._registeredMeshes[index];
  29525. if (registeredMesh.mesh === mesh1) {
  29526. body1 = registeredMesh.body.body;
  29527. }
  29528. else if (registeredMesh.mesh === mesh2) {
  29529. body2 = registeredMesh.body.body;
  29530. }
  29531. }
  29532. if (!body1 || !body2) {
  29533. return false;
  29534. }
  29535. if (!options) {
  29536. options = {};
  29537. }
  29538. new OIMO.Link({
  29539. type: options.type,
  29540. body1: body1,
  29541. body2: body2,
  29542. min: options.min,
  29543. max: options.max,
  29544. axe1: options.axe1,
  29545. axe2: options.axe2,
  29546. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29547. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29548. collision: options.collision,
  29549. spring: options.spring,
  29550. world: this._world
  29551. });
  29552. return true;
  29553. };
  29554. OimoJSPlugin.prototype.dispose = function () {
  29555. this._world.clear();
  29556. while (this._registeredMeshes.length) {
  29557. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29558. }
  29559. };
  29560. OimoJSPlugin.prototype.isSupported = function () {
  29561. return OIMO !== undefined;
  29562. };
  29563. OimoJSPlugin.prototype.getWorldObject = function () {
  29564. return this._world;
  29565. };
  29566. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29567. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29568. var registeredMesh = this._registeredMeshes[index];
  29569. if (registeredMesh.mesh === mesh) {
  29570. return registeredMesh.body;
  29571. }
  29572. }
  29573. return null;
  29574. };
  29575. OimoJSPlugin.prototype._getLastShape = function (body) {
  29576. var lastShape = body.shapes;
  29577. while (lastShape.next) {
  29578. lastShape = lastShape.next;
  29579. }
  29580. return lastShape;
  29581. };
  29582. OimoJSPlugin.prototype.runOneStep = function (time) {
  29583. this._world.step();
  29584. // Update the position of all registered meshes
  29585. var i = this._registeredMeshes.length;
  29586. var m;
  29587. while (i--) {
  29588. var body = this._registeredMeshes[i].body.body;
  29589. var mesh = this._registeredMeshes[i].mesh;
  29590. if (!this._registeredMeshes[i].delta) {
  29591. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29592. }
  29593. if (!body.sleeping) {
  29594. //TODO check that
  29595. if (body.shapes.next) {
  29596. var parentShape = this._getLastShape(body);
  29597. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29598. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29599. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29600. }
  29601. else {
  29602. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29603. }
  29604. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29605. mesh.computeWorldMatrix();
  29606. }
  29607. //check if the collide callback is set.
  29608. if (mesh.onPhysicsCollide) {
  29609. var meshUniqueName = mesh.uniqueId;
  29610. var contact = this._world.contacts;
  29611. while (contact !== null) {
  29612. //is this body colliding with any other?
  29613. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29614. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29615. //get the mesh and execute the callback
  29616. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29617. if (otherMesh)
  29618. mesh.onPhysicsCollide(otherMesh, contact);
  29619. }
  29620. contact = contact.next;
  29621. }
  29622. }
  29623. }
  29624. };
  29625. return OimoJSPlugin;
  29626. })();
  29627. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29628. })(BABYLON || (BABYLON = {}));
  29629. var BABYLON;
  29630. (function (BABYLON) {
  29631. var DisplayPassPostProcess = (function (_super) {
  29632. __extends(DisplayPassPostProcess, _super);
  29633. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29634. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29635. }
  29636. return DisplayPassPostProcess;
  29637. })(BABYLON.PostProcess);
  29638. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29639. })(BABYLON || (BABYLON = {}));
  29640. var BABYLON;
  29641. (function (BABYLON) {
  29642. var SimplificationSettings = (function () {
  29643. function SimplificationSettings(quality, distance, optimizeMesh) {
  29644. this.quality = quality;
  29645. this.distance = distance;
  29646. this.optimizeMesh = optimizeMesh;
  29647. }
  29648. return SimplificationSettings;
  29649. })();
  29650. BABYLON.SimplificationSettings = SimplificationSettings;
  29651. var SimplificationQueue = (function () {
  29652. function SimplificationQueue() {
  29653. this.running = false;
  29654. this._simplificationArray = [];
  29655. }
  29656. SimplificationQueue.prototype.addTask = function (task) {
  29657. this._simplificationArray.push(task);
  29658. };
  29659. SimplificationQueue.prototype.executeNext = function () {
  29660. var task = this._simplificationArray.pop();
  29661. if (task) {
  29662. this.running = true;
  29663. this.runSimplification(task);
  29664. }
  29665. else {
  29666. this.running = false;
  29667. }
  29668. };
  29669. SimplificationQueue.prototype.runSimplification = function (task) {
  29670. var _this = this;
  29671. if (task.parallelProcessing) {
  29672. //parallel simplifier
  29673. task.settings.forEach(function (setting) {
  29674. var simplifier = _this.getSimplifier(task);
  29675. simplifier.simplify(setting, function (newMesh) {
  29676. task.mesh.addLODLevel(setting.distance, newMesh);
  29677. newMesh.isVisible = true;
  29678. //check if it is the last
  29679. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29680. //all done, run the success callback.
  29681. task.successCallback();
  29682. }
  29683. _this.executeNext();
  29684. });
  29685. });
  29686. }
  29687. else {
  29688. //single simplifier.
  29689. var simplifier = this.getSimplifier(task);
  29690. var runDecimation = function (setting, callback) {
  29691. simplifier.simplify(setting, function (newMesh) {
  29692. task.mesh.addLODLevel(setting.distance, newMesh);
  29693. newMesh.isVisible = true;
  29694. //run the next quality level
  29695. callback();
  29696. });
  29697. };
  29698. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29699. runDecimation(task.settings[loop.index], function () {
  29700. loop.executeNext();
  29701. });
  29702. }, function () {
  29703. //execution ended, run the success callback.
  29704. if (task.successCallback) {
  29705. task.successCallback();
  29706. }
  29707. _this.executeNext();
  29708. });
  29709. }
  29710. };
  29711. SimplificationQueue.prototype.getSimplifier = function (task) {
  29712. switch (task.simplificationType) {
  29713. case SimplificationType.QUADRATIC:
  29714. default:
  29715. return new QuadraticErrorSimplification(task.mesh);
  29716. }
  29717. };
  29718. return SimplificationQueue;
  29719. })();
  29720. BABYLON.SimplificationQueue = SimplificationQueue;
  29721. /**
  29722. * The implemented types of simplification.
  29723. * At the moment only Quadratic Error Decimation is implemented.
  29724. */
  29725. (function (SimplificationType) {
  29726. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29727. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29728. var SimplificationType = BABYLON.SimplificationType;
  29729. var DecimationTriangle = (function () {
  29730. function DecimationTriangle(vertices) {
  29731. this.vertices = vertices;
  29732. this.error = new Array(4);
  29733. this.deleted = false;
  29734. this.isDirty = false;
  29735. this.deletePending = false;
  29736. this.borderFactor = 0;
  29737. }
  29738. return DecimationTriangle;
  29739. })();
  29740. BABYLON.DecimationTriangle = DecimationTriangle;
  29741. var DecimationVertex = (function () {
  29742. function DecimationVertex(position, id) {
  29743. this.position = position;
  29744. this.id = id;
  29745. this.isBorder = true;
  29746. this.q = new QuadraticMatrix();
  29747. this.triangleCount = 0;
  29748. this.triangleStart = 0;
  29749. this.originalOffsets = [];
  29750. }
  29751. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29752. this.position.copyFrom(newPosition);
  29753. };
  29754. return DecimationVertex;
  29755. })();
  29756. BABYLON.DecimationVertex = DecimationVertex;
  29757. var QuadraticMatrix = (function () {
  29758. function QuadraticMatrix(data) {
  29759. this.data = new Array(10);
  29760. for (var i = 0; i < 10; ++i) {
  29761. if (data && data[i]) {
  29762. this.data[i] = data[i];
  29763. }
  29764. else {
  29765. this.data[i] = 0;
  29766. }
  29767. }
  29768. }
  29769. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29770. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29771. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29772. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29773. return det;
  29774. };
  29775. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29776. for (var i = 0; i < 10; ++i) {
  29777. this.data[i] += matrix.data[i];
  29778. }
  29779. };
  29780. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29781. for (var i = 0; i < 10; ++i) {
  29782. this.data[i] += data[i];
  29783. }
  29784. };
  29785. QuadraticMatrix.prototype.add = function (matrix) {
  29786. var m = new QuadraticMatrix();
  29787. for (var i = 0; i < 10; ++i) {
  29788. m.data[i] = this.data[i] + matrix.data[i];
  29789. }
  29790. return m;
  29791. };
  29792. QuadraticMatrix.FromData = function (a, b, c, d) {
  29793. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29794. };
  29795. //returning an array to avoid garbage collection
  29796. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29797. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29798. };
  29799. return QuadraticMatrix;
  29800. })();
  29801. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29802. var Reference = (function () {
  29803. function Reference(vertexId, triangleId) {
  29804. this.vertexId = vertexId;
  29805. this.triangleId = triangleId;
  29806. }
  29807. return Reference;
  29808. })();
  29809. BABYLON.Reference = Reference;
  29810. /**
  29811. * An implementation of the Quadratic Error simplification algorithm.
  29812. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29813. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29814. * @author RaananW
  29815. */
  29816. var QuadraticErrorSimplification = (function () {
  29817. function QuadraticErrorSimplification(_mesh) {
  29818. this._mesh = _mesh;
  29819. this.initialized = false;
  29820. this.syncIterations = 5000;
  29821. this.aggressiveness = 7;
  29822. this.decimationIterations = 100;
  29823. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29824. }
  29825. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29826. var _this = this;
  29827. this.initDecimatedMesh();
  29828. //iterating through the submeshes array, one after the other.
  29829. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29830. _this.initWithMesh(loop.index, function () {
  29831. _this.runDecimation(settings, loop.index, function () {
  29832. loop.executeNext();
  29833. });
  29834. }, settings.optimizeMesh);
  29835. }, function () {
  29836. setTimeout(function () {
  29837. successCallback(_this._reconstructedMesh);
  29838. }, 0);
  29839. });
  29840. };
  29841. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29842. var _this = this;
  29843. var gCount = 0;
  29844. triangle.vertices.forEach(function (vertex) {
  29845. var count = 0;
  29846. var vPos = vertex.position;
  29847. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29848. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29849. ++count;
  29850. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29851. ++count;
  29852. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29853. ++count;
  29854. if (count > 1) {
  29855. ++gCount;
  29856. }
  29857. ;
  29858. });
  29859. if (gCount > 1) {
  29860. console.log(triangle, gCount);
  29861. }
  29862. return gCount > 1;
  29863. };
  29864. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29865. var _this = this;
  29866. var targetCount = ~~(this.triangles.length * settings.quality);
  29867. var deletedTriangles = 0;
  29868. var triangleCount = this.triangles.length;
  29869. var iterationFunction = function (iteration, callback) {
  29870. setTimeout(function () {
  29871. if (iteration % 5 === 0) {
  29872. _this.updateMesh(iteration === 0);
  29873. }
  29874. for (var i = 0; i < _this.triangles.length; ++i) {
  29875. _this.triangles[i].isDirty = false;
  29876. }
  29877. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29878. var trianglesIterator = function (i) {
  29879. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29880. var t = _this.triangles[tIdx];
  29881. if (!t)
  29882. return;
  29883. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29884. return;
  29885. }
  29886. for (var j = 0; j < 3; ++j) {
  29887. if (t.error[j] < threshold) {
  29888. var deleted0 = [];
  29889. var deleted1 = [];
  29890. var v0 = t.vertices[j];
  29891. var v1 = t.vertices[(j + 1) % 3];
  29892. if (v0.isBorder !== v1.isBorder)
  29893. continue;
  29894. var p = BABYLON.Vector3.Zero();
  29895. var n = BABYLON.Vector3.Zero();
  29896. var uv = BABYLON.Vector2.Zero();
  29897. var color = new BABYLON.Color4(0, 0, 0, 1);
  29898. _this.calculateError(v0, v1, p, n, uv, color);
  29899. var delTr = [];
  29900. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29901. continue;
  29902. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29903. continue;
  29904. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29905. continue;
  29906. var uniqueArray = [];
  29907. delTr.forEach(function (deletedT) {
  29908. if (uniqueArray.indexOf(deletedT) === -1) {
  29909. deletedT.deletePending = true;
  29910. uniqueArray.push(deletedT);
  29911. }
  29912. });
  29913. if (uniqueArray.length % 2 !== 0) {
  29914. continue;
  29915. }
  29916. v0.q = v1.q.add(v0.q);
  29917. v0.updatePosition(p);
  29918. var tStart = _this.references.length;
  29919. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29920. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29921. var tCount = _this.references.length - tStart;
  29922. if (tCount <= v0.triangleCount) {
  29923. if (tCount) {
  29924. for (var c = 0; c < tCount; c++) {
  29925. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29926. }
  29927. }
  29928. }
  29929. else {
  29930. v0.triangleStart = tStart;
  29931. }
  29932. v0.triangleCount = tCount;
  29933. break;
  29934. }
  29935. }
  29936. };
  29937. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29938. }, 0);
  29939. };
  29940. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29941. if (triangleCount - deletedTriangles <= targetCount)
  29942. loop.breakLoop();
  29943. else {
  29944. iterationFunction(loop.index, function () {
  29945. loop.executeNext();
  29946. });
  29947. }
  29948. }, function () {
  29949. setTimeout(function () {
  29950. //reconstruct this part of the mesh
  29951. _this.reconstructMesh(submeshIndex);
  29952. successCallback();
  29953. }, 0);
  29954. });
  29955. };
  29956. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29957. var _this = this;
  29958. this.vertices = [];
  29959. this.triangles = [];
  29960. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29961. var indices = this._mesh.getIndices();
  29962. var submesh = this._mesh.subMeshes[submeshIndex];
  29963. var findInVertices = function (positionToSearch) {
  29964. if (optimizeMesh) {
  29965. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29966. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29967. return _this.vertices[ii];
  29968. }
  29969. }
  29970. }
  29971. return null;
  29972. };
  29973. var vertexReferences = [];
  29974. var vertexInit = function (i) {
  29975. var offset = i + submesh.verticesStart;
  29976. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29977. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29978. vertex.originalOffsets.push(offset);
  29979. if (vertex.id === _this.vertices.length) {
  29980. _this.vertices.push(vertex);
  29981. }
  29982. vertexReferences.push(vertex.id);
  29983. };
  29984. //var totalVertices = mesh.getTotalVertices();
  29985. var totalVertices = submesh.verticesCount;
  29986. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29987. var indicesInit = function (i) {
  29988. var offset = (submesh.indexStart / 3) + i;
  29989. var pos = (offset * 3);
  29990. var i0 = indices[pos + 0];
  29991. var i1 = indices[pos + 1];
  29992. var i2 = indices[pos + 2];
  29993. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29994. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29995. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29996. var triangle = new DecimationTriangle([v0, v1, v2]);
  29997. triangle.originalOffset = pos;
  29998. _this.triangles.push(triangle);
  29999. };
  30000. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30001. _this.init(callback);
  30002. });
  30003. });
  30004. };
  30005. QuadraticErrorSimplification.prototype.init = function (callback) {
  30006. var _this = this;
  30007. var triangleInit1 = function (i) {
  30008. var t = _this.triangles[i];
  30009. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30010. for (var j = 0; j < 3; j++) {
  30011. 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))));
  30012. }
  30013. };
  30014. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30015. var triangleInit2 = function (i) {
  30016. var t = _this.triangles[i];
  30017. for (var j = 0; j < 3; ++j) {
  30018. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30019. }
  30020. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30021. };
  30022. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30023. _this.initialized = true;
  30024. callback();
  30025. });
  30026. });
  30027. };
  30028. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30029. var newTriangles = [];
  30030. var i;
  30031. for (i = 0; i < this.vertices.length; ++i) {
  30032. this.vertices[i].triangleCount = 0;
  30033. }
  30034. var t;
  30035. var j;
  30036. for (i = 0; i < this.triangles.length; ++i) {
  30037. if (!this.triangles[i].deleted) {
  30038. t = this.triangles[i];
  30039. for (j = 0; j < 3; ++j) {
  30040. t.vertices[j].triangleCount = 1;
  30041. }
  30042. newTriangles.push(t);
  30043. }
  30044. }
  30045. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30046. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30047. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30048. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30049. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30050. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30051. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30052. var vertexCount = 0;
  30053. for (i = 0; i < this.vertices.length; ++i) {
  30054. var vertex = this.vertices[i];
  30055. vertex.id = vertexCount;
  30056. if (vertex.triangleCount) {
  30057. vertex.originalOffsets.forEach(function (originalOffset) {
  30058. newPositionData.push(vertex.position.x);
  30059. newPositionData.push(vertex.position.y);
  30060. newPositionData.push(vertex.position.z);
  30061. newNormalData.push(normalData[originalOffset * 3]);
  30062. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30063. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30064. if (uvs && uvs.length) {
  30065. newUVsData.push(uvs[(originalOffset * 2)]);
  30066. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30067. }
  30068. else if (colorsData && colorsData.length) {
  30069. newColorsData.push(colorsData[(originalOffset * 4)]);
  30070. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30071. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30072. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30073. }
  30074. ++vertexCount;
  30075. });
  30076. }
  30077. }
  30078. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30079. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30080. var submeshesArray = this._reconstructedMesh.subMeshes;
  30081. this._reconstructedMesh.subMeshes = [];
  30082. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30083. var originalIndices = this._mesh.getIndices();
  30084. for (i = 0; i < newTriangles.length; ++i) {
  30085. t = newTriangles[i]; //now get the new referencing point for each vertex
  30086. [0, 1, 2].forEach(function (idx) {
  30087. var id = originalIndices[t.originalOffset + idx];
  30088. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30089. if (offset < 0)
  30090. offset = 0;
  30091. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30092. });
  30093. }
  30094. //overwriting the old vertex buffers and indices.
  30095. this._reconstructedMesh.setIndices(newIndicesArray);
  30096. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30097. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30098. if (newUVsData.length > 0)
  30099. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30100. if (newColorsData.length > 0)
  30101. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30102. //create submesh
  30103. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30104. if (submeshIndex > 0) {
  30105. this._reconstructedMesh.subMeshes = [];
  30106. submeshesArray.forEach(function (submesh) {
  30107. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30108. });
  30109. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30110. }
  30111. };
  30112. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30113. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30114. this._reconstructedMesh.material = this._mesh.material;
  30115. this._reconstructedMesh.parent = this._mesh.parent;
  30116. this._reconstructedMesh.isVisible = false;
  30117. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30118. };
  30119. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30120. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30121. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30122. if (t.deleted)
  30123. continue;
  30124. var s = this.references[vertex1.triangleStart + i].vertexId;
  30125. var v1 = t.vertices[(s + 1) % 3];
  30126. var v2 = t.vertices[(s + 2) % 3];
  30127. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30128. deletedArray[i] = true;
  30129. delTr.push(t);
  30130. continue;
  30131. }
  30132. var d1 = v1.position.subtract(point);
  30133. d1 = d1.normalize();
  30134. var d2 = v2.position.subtract(point);
  30135. d2 = d2.normalize();
  30136. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30137. return true;
  30138. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30139. deletedArray[i] = false;
  30140. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30141. return true;
  30142. }
  30143. return false;
  30144. };
  30145. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30146. var newDeleted = deletedTriangles;
  30147. for (var i = 0; i < vertex.triangleCount; ++i) {
  30148. var ref = this.references[vertex.triangleStart + i];
  30149. var t = this.triangles[ref.triangleId];
  30150. if (t.deleted)
  30151. continue;
  30152. if (deletedArray[i] && t.deletePending) {
  30153. t.deleted = true;
  30154. newDeleted++;
  30155. continue;
  30156. }
  30157. t.vertices[ref.vertexId] = origVertex;
  30158. t.isDirty = true;
  30159. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30160. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30161. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30162. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30163. this.references.push(ref);
  30164. }
  30165. return newDeleted;
  30166. };
  30167. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30168. for (var i = 0; i < this.vertices.length; ++i) {
  30169. var vCount = [];
  30170. var vId = [];
  30171. var v = this.vertices[i];
  30172. var j;
  30173. for (j = 0; j < v.triangleCount; ++j) {
  30174. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30175. for (var ii = 0; ii < 3; ii++) {
  30176. var ofs = 0;
  30177. var vv = triangle.vertices[ii];
  30178. while (ofs < vCount.length) {
  30179. if (vId[ofs] === vv.id)
  30180. break;
  30181. ++ofs;
  30182. }
  30183. if (ofs === vCount.length) {
  30184. vCount.push(1);
  30185. vId.push(vv.id);
  30186. }
  30187. else {
  30188. vCount[ofs]++;
  30189. }
  30190. }
  30191. }
  30192. for (j = 0; j < vCount.length; ++j) {
  30193. if (vCount[j] === 1) {
  30194. this.vertices[vId[j]].isBorder = true;
  30195. }
  30196. else {
  30197. this.vertices[vId[j]].isBorder = false;
  30198. }
  30199. }
  30200. }
  30201. };
  30202. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30203. if (identifyBorders === void 0) { identifyBorders = false; }
  30204. var i;
  30205. if (!identifyBorders) {
  30206. var newTrianglesVector = [];
  30207. for (i = 0; i < this.triangles.length; ++i) {
  30208. if (!this.triangles[i].deleted) {
  30209. newTrianglesVector.push(this.triangles[i]);
  30210. }
  30211. }
  30212. this.triangles = newTrianglesVector;
  30213. }
  30214. for (i = 0; i < this.vertices.length; ++i) {
  30215. this.vertices[i].triangleCount = 0;
  30216. this.vertices[i].triangleStart = 0;
  30217. }
  30218. var t;
  30219. var j;
  30220. var v;
  30221. for (i = 0; i < this.triangles.length; ++i) {
  30222. t = this.triangles[i];
  30223. for (j = 0; j < 3; ++j) {
  30224. v = t.vertices[j];
  30225. v.triangleCount++;
  30226. }
  30227. }
  30228. var tStart = 0;
  30229. for (i = 0; i < this.vertices.length; ++i) {
  30230. this.vertices[i].triangleStart = tStart;
  30231. tStart += this.vertices[i].triangleCount;
  30232. this.vertices[i].triangleCount = 0;
  30233. }
  30234. var newReferences = new Array(this.triangles.length * 3);
  30235. for (i = 0; i < this.triangles.length; ++i) {
  30236. t = this.triangles[i];
  30237. for (j = 0; j < 3; ++j) {
  30238. v = t.vertices[j];
  30239. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30240. v.triangleCount++;
  30241. }
  30242. }
  30243. this.references = newReferences;
  30244. if (identifyBorders) {
  30245. this.identifyBorder();
  30246. }
  30247. };
  30248. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30249. var x = point.x;
  30250. var y = point.y;
  30251. var z = point.z;
  30252. 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
  30253. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30254. };
  30255. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30256. var q = vertex1.q.add(vertex2.q);
  30257. var border = vertex1.isBorder && vertex2.isBorder;
  30258. var error = 0;
  30259. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30260. if (qDet !== 0 && !border) {
  30261. if (!pointResult) {
  30262. pointResult = BABYLON.Vector3.Zero();
  30263. }
  30264. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30265. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30266. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30267. error = this.vertexError(q, pointResult);
  30268. }
  30269. else {
  30270. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30271. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30272. var error1 = this.vertexError(q, vertex1.position);
  30273. var error2 = this.vertexError(q, vertex2.position);
  30274. var error3 = this.vertexError(q, p3);
  30275. error = Math.min(error1, error2, error3);
  30276. if (error === error1) {
  30277. if (pointResult) {
  30278. pointResult.copyFrom(vertex1.position);
  30279. }
  30280. }
  30281. else if (error === error2) {
  30282. if (pointResult) {
  30283. pointResult.copyFrom(vertex2.position);
  30284. }
  30285. }
  30286. else {
  30287. if (pointResult) {
  30288. pointResult.copyFrom(p3);
  30289. }
  30290. }
  30291. }
  30292. return error;
  30293. };
  30294. return QuadraticErrorSimplification;
  30295. })();
  30296. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30297. })(BABYLON || (BABYLON = {}));
  30298. var BABYLON;
  30299. (function (BABYLON) {
  30300. var serializedGeometries = [];
  30301. var serializeGeometry = function (geometry, serializationGeometries) {
  30302. if (serializedGeometries[geometry.id]) {
  30303. return;
  30304. }
  30305. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30306. serializationGeometries.boxes.push(geometry.serialize());
  30307. }
  30308. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30309. serializationGeometries.spheres.push(geometry.serialize());
  30310. }
  30311. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30312. serializationGeometries.cylinders.push(geometry.serialize());
  30313. }
  30314. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30315. serializationGeometries.toruses.push(geometry.serialize());
  30316. }
  30317. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30318. serializationGeometries.grounds.push(geometry.serialize());
  30319. }
  30320. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30321. serializationGeometries.planes.push(geometry.serialize());
  30322. }
  30323. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30324. serializationGeometries.torusKnots.push(geometry.serialize());
  30325. }
  30326. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30327. throw new Error("Unknown primitive type");
  30328. }
  30329. else {
  30330. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30331. }
  30332. serializedGeometries[geometry.id] = true;
  30333. };
  30334. var serializeMesh = function (mesh, serializationScene) {
  30335. var serializationObject = {};
  30336. serializationObject.name = mesh.name;
  30337. serializationObject.id = mesh.id;
  30338. if (BABYLON.Tags.HasTags(mesh)) {
  30339. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30340. }
  30341. serializationObject.position = mesh.position.asArray();
  30342. if (mesh.rotationQuaternion) {
  30343. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30344. }
  30345. else if (mesh.rotation) {
  30346. serializationObject.rotation = mesh.rotation.asArray();
  30347. }
  30348. serializationObject.scaling = mesh.scaling.asArray();
  30349. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30350. serializationObject.isEnabled = mesh.isEnabled();
  30351. serializationObject.isVisible = mesh.isVisible;
  30352. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30353. serializationObject.pickable = mesh.isPickable;
  30354. serializationObject.receiveShadows = mesh.receiveShadows;
  30355. serializationObject.billboardMode = mesh.billboardMode;
  30356. serializationObject.visibility = mesh.visibility;
  30357. serializationObject.checkCollisions = mesh.checkCollisions;
  30358. // Parent
  30359. if (mesh.parent) {
  30360. serializationObject.parentId = mesh.parent.id;
  30361. }
  30362. // Geometry
  30363. var geometry = mesh._geometry;
  30364. if (geometry) {
  30365. var geometryId = geometry.id;
  30366. serializationObject.geometryId = geometryId;
  30367. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30368. // 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
  30369. serializeGeometry(geometry, serializationScene.geometries);
  30370. }
  30371. // SubMeshes
  30372. serializationObject.subMeshes = [];
  30373. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30374. var subMesh = mesh.subMeshes[subIndex];
  30375. serializationObject.subMeshes.push({
  30376. materialIndex: subMesh.materialIndex,
  30377. verticesStart: subMesh.verticesStart,
  30378. verticesCount: subMesh.verticesCount,
  30379. indexStart: subMesh.indexStart,
  30380. indexCount: subMesh.indexCount
  30381. });
  30382. }
  30383. }
  30384. // Material
  30385. if (mesh.material) {
  30386. serializationObject.materialId = mesh.material.id;
  30387. }
  30388. else {
  30389. mesh.material = null;
  30390. }
  30391. // Skeleton
  30392. if (mesh.skeleton) {
  30393. serializationObject.skeletonId = mesh.skeleton.id;
  30394. }
  30395. // Physics
  30396. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30397. serializationObject.physicsMass = mesh.getPhysicsMass();
  30398. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30399. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30400. switch (mesh.getPhysicsImpostor()) {
  30401. case BABYLON.PhysicsEngine.BoxImpostor:
  30402. serializationObject.physicsImpostor = 1;
  30403. break;
  30404. case BABYLON.PhysicsEngine.SphereImpostor:
  30405. serializationObject.physicsImpostor = 2;
  30406. break;
  30407. }
  30408. }
  30409. // Instances
  30410. serializationObject.instances = [];
  30411. for (var index = 0; index < mesh.instances.length; index++) {
  30412. var instance = mesh.instances[index];
  30413. var serializationInstance = {
  30414. name: instance.name,
  30415. position: instance.position.asArray(),
  30416. scaling: instance.scaling.asArray()
  30417. };
  30418. if (instance.rotationQuaternion) {
  30419. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30420. }
  30421. else if (instance.rotation) {
  30422. serializationInstance.rotation = instance.rotation.asArray();
  30423. }
  30424. serializationObject.instances.push(serializationInstance);
  30425. // Animations
  30426. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30427. }
  30428. // Animations
  30429. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30430. // Layer mask
  30431. serializationObject.layerMask = mesh.layerMask;
  30432. return serializationObject;
  30433. };
  30434. var finalizeSingleMesh = function (mesh, serializationObject) {
  30435. //only works if the mesh is already loaded
  30436. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30437. //serialize material
  30438. if (mesh.material) {
  30439. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30440. serializationObject.materials = serializationObject.materials || [];
  30441. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30442. serializationObject.materials.push(mesh.material.serialize());
  30443. }
  30444. }
  30445. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30446. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30447. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30448. serializationObject.multiMaterials.push(mesh.material.serialize());
  30449. }
  30450. }
  30451. }
  30452. //serialize geometry
  30453. var geometry = mesh._geometry;
  30454. if (geometry) {
  30455. if (!serializationObject.geometries) {
  30456. serializationObject.geometries = {};
  30457. serializationObject.geometries.boxes = [];
  30458. serializationObject.geometries.spheres = [];
  30459. serializationObject.geometries.cylinders = [];
  30460. serializationObject.geometries.toruses = [];
  30461. serializationObject.geometries.grounds = [];
  30462. serializationObject.geometries.planes = [];
  30463. serializationObject.geometries.torusKnots = [];
  30464. serializationObject.geometries.vertexData = [];
  30465. }
  30466. serializeGeometry(geometry, serializationObject.geometries);
  30467. }
  30468. // Skeletons
  30469. if (mesh.skeleton) {
  30470. serializationObject.skeletons = serializationObject.skeletons || [];
  30471. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30472. }
  30473. //serialize the actual mesh
  30474. serializationObject.meshes = serializationObject.meshes || [];
  30475. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30476. }
  30477. };
  30478. var SceneSerializer = (function () {
  30479. function SceneSerializer() {
  30480. }
  30481. SceneSerializer.Serialize = function (scene) {
  30482. var serializationObject = {};
  30483. // Scene
  30484. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30485. serializationObject.autoClear = scene.autoClear;
  30486. serializationObject.clearColor = scene.clearColor.asArray();
  30487. serializationObject.ambientColor = scene.ambientColor.asArray();
  30488. serializationObject.gravity = scene.gravity.asArray();
  30489. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30490. serializationObject.workerCollisions = scene.workerCollisions;
  30491. // Fog
  30492. if (scene.fogMode && scene.fogMode !== 0) {
  30493. serializationObject.fogMode = scene.fogMode;
  30494. serializationObject.fogColor = scene.fogColor.asArray();
  30495. serializationObject.fogStart = scene.fogStart;
  30496. serializationObject.fogEnd = scene.fogEnd;
  30497. serializationObject.fogDensity = scene.fogDensity;
  30498. }
  30499. //Physics
  30500. if (scene.isPhysicsEnabled()) {
  30501. serializationObject.physicsEnabled = true;
  30502. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30503. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30504. }
  30505. // Lights
  30506. serializationObject.lights = [];
  30507. var index;
  30508. var light;
  30509. for (index = 0; index < scene.lights.length; index++) {
  30510. light = scene.lights[index];
  30511. serializationObject.lights.push(light.serialize());
  30512. }
  30513. // Cameras
  30514. serializationObject.cameras = [];
  30515. for (index = 0; index < scene.cameras.length; index++) {
  30516. var camera = scene.cameras[index];
  30517. serializationObject.cameras.push(camera.serialize());
  30518. }
  30519. if (scene.activeCamera) {
  30520. serializationObject.activeCameraID = scene.activeCamera.id;
  30521. }
  30522. // Materials
  30523. serializationObject.materials = [];
  30524. serializationObject.multiMaterials = [];
  30525. var material;
  30526. for (index = 0; index < scene.materials.length; index++) {
  30527. material = scene.materials[index];
  30528. serializationObject.materials.push(material.serialize());
  30529. }
  30530. // MultiMaterials
  30531. serializationObject.multiMaterials = [];
  30532. for (index = 0; index < scene.multiMaterials.length; index++) {
  30533. var multiMaterial = scene.multiMaterials[index];
  30534. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30535. }
  30536. // Skeletons
  30537. serializationObject.skeletons = [];
  30538. for (index = 0; index < scene.skeletons.length; index++) {
  30539. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30540. }
  30541. // Geometries
  30542. serializationObject.geometries = {};
  30543. serializationObject.geometries.boxes = [];
  30544. serializationObject.geometries.spheres = [];
  30545. serializationObject.geometries.cylinders = [];
  30546. serializationObject.geometries.toruses = [];
  30547. serializationObject.geometries.grounds = [];
  30548. serializationObject.geometries.planes = [];
  30549. serializationObject.geometries.torusKnots = [];
  30550. serializationObject.geometries.vertexData = [];
  30551. serializedGeometries = [];
  30552. var geometries = scene.getGeometries();
  30553. for (index = 0; index < geometries.length; index++) {
  30554. var geometry = geometries[index];
  30555. if (geometry.isReady()) {
  30556. serializeGeometry(geometry, serializationObject.geometries);
  30557. }
  30558. }
  30559. // Meshes
  30560. serializationObject.meshes = [];
  30561. for (index = 0; index < scene.meshes.length; index++) {
  30562. var abstractMesh = scene.meshes[index];
  30563. if (abstractMesh instanceof BABYLON.Mesh) {
  30564. var mesh = abstractMesh;
  30565. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30566. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30567. }
  30568. }
  30569. }
  30570. // Particles Systems
  30571. serializationObject.particleSystems = [];
  30572. for (index = 0; index < scene.particleSystems.length; index++) {
  30573. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30574. }
  30575. // Lens flares
  30576. serializationObject.lensFlareSystems = [];
  30577. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30578. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30579. }
  30580. // Shadows
  30581. serializationObject.shadowGenerators = [];
  30582. for (index = 0; index < scene.lights.length; index++) {
  30583. light = scene.lights[index];
  30584. if (light.getShadowGenerator()) {
  30585. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30586. }
  30587. }
  30588. return serializationObject;
  30589. };
  30590. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30591. if (withParents === void 0) { withParents = false; }
  30592. if (withChildren === void 0) { withChildren = false; }
  30593. var serializationObject = {};
  30594. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30595. if (withParents || withChildren) {
  30596. //deliberate for loop! not for each, appended should be processed as well.
  30597. for (var i = 0; i < toSerialize.length; ++i) {
  30598. if (withChildren) {
  30599. toSerialize[i].getDescendants().forEach(function (node) {
  30600. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30601. toSerialize.push(node);
  30602. }
  30603. });
  30604. }
  30605. //make sure the array doesn't contain the object already
  30606. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30607. toSerialize.push(toSerialize[i].parent);
  30608. }
  30609. }
  30610. }
  30611. toSerialize.forEach(function (mesh) {
  30612. finalizeSingleMesh(mesh, serializationObject);
  30613. });
  30614. return serializationObject;
  30615. };
  30616. return SceneSerializer;
  30617. })();
  30618. BABYLON.SceneSerializer = SceneSerializer;
  30619. })(BABYLON || (BABYLON = {}));
  30620. var BABYLON;
  30621. (function (BABYLON) {
  30622. // Unique ID when we import meshes from Babylon to CSG
  30623. var currentCSGMeshId = 0;
  30624. // # class Vertex
  30625. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30626. // one to provide additional features like texture coordinates and vertex
  30627. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30628. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30629. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30630. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30631. // is not used anywhere else.
  30632. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30633. var Vertex = (function () {
  30634. function Vertex(pos, normal, uv) {
  30635. this.pos = pos;
  30636. this.normal = normal;
  30637. this.uv = uv;
  30638. }
  30639. Vertex.prototype.clone = function () {
  30640. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30641. };
  30642. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30643. // orientation of a polygon is flipped.
  30644. Vertex.prototype.flip = function () {
  30645. this.normal = this.normal.scale(-1);
  30646. };
  30647. // Create a new vertex between this vertex and `other` by linearly
  30648. // interpolating all properties using a parameter of `t`. Subclasses should
  30649. // override this to interpolate additional properties.
  30650. Vertex.prototype.interpolate = function (other, t) {
  30651. 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));
  30652. };
  30653. return Vertex;
  30654. })();
  30655. // # class Plane
  30656. // Represents a plane in 3D space.
  30657. var Plane = (function () {
  30658. function Plane(normal, w) {
  30659. this.normal = normal;
  30660. this.w = w;
  30661. }
  30662. Plane.FromPoints = function (a, b, c) {
  30663. var v0 = c.subtract(a);
  30664. var v1 = b.subtract(a);
  30665. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30666. return null;
  30667. }
  30668. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30669. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30670. };
  30671. Plane.prototype.clone = function () {
  30672. return new Plane(this.normal.clone(), this.w);
  30673. };
  30674. Plane.prototype.flip = function () {
  30675. this.normal.scaleInPlace(-1);
  30676. this.w = -this.w;
  30677. };
  30678. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30679. // fragments in the appropriate lists. Coplanar polygons go into either
  30680. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30681. // respect to this plane. Polygons in front or in back of this plane go into
  30682. // either `front` or `back`.
  30683. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30684. var COPLANAR = 0;
  30685. var FRONT = 1;
  30686. var BACK = 2;
  30687. var SPANNING = 3;
  30688. // Classify each point as well as the entire polygon into one of the above
  30689. // four classes.
  30690. var polygonType = 0;
  30691. var types = [];
  30692. var i;
  30693. var t;
  30694. for (i = 0; i < polygon.vertices.length; i++) {
  30695. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30696. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30697. polygonType |= type;
  30698. types.push(type);
  30699. }
  30700. // Put the polygon in the correct list, splitting it when necessary.
  30701. switch (polygonType) {
  30702. case COPLANAR:
  30703. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30704. break;
  30705. case FRONT:
  30706. front.push(polygon);
  30707. break;
  30708. case BACK:
  30709. back.push(polygon);
  30710. break;
  30711. case SPANNING:
  30712. var f = [], b = [];
  30713. for (i = 0; i < polygon.vertices.length; i++) {
  30714. var j = (i + 1) % polygon.vertices.length;
  30715. var ti = types[i], tj = types[j];
  30716. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30717. if (ti !== BACK)
  30718. f.push(vi);
  30719. if (ti !== FRONT)
  30720. b.push(ti !== BACK ? vi.clone() : vi);
  30721. if ((ti | tj) === SPANNING) {
  30722. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30723. var v = vi.interpolate(vj, t);
  30724. f.push(v);
  30725. b.push(v.clone());
  30726. }
  30727. }
  30728. var poly;
  30729. if (f.length >= 3) {
  30730. poly = new Polygon(f, polygon.shared);
  30731. if (poly.plane)
  30732. front.push(poly);
  30733. }
  30734. if (b.length >= 3) {
  30735. poly = new Polygon(b, polygon.shared);
  30736. if (poly.plane)
  30737. back.push(poly);
  30738. }
  30739. break;
  30740. }
  30741. };
  30742. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30743. // point is on the plane.
  30744. Plane.EPSILON = 1e-5;
  30745. return Plane;
  30746. })();
  30747. // # class Polygon
  30748. // Represents a convex polygon. The vertices used to initialize a polygon must
  30749. // be coplanar and form a convex loop.
  30750. //
  30751. // Each convex polygon has a `shared` property, which is shared between all
  30752. // polygons that are clones of each other or were split from the same polygon.
  30753. // This can be used to define per-polygon properties (such as surface color).
  30754. var Polygon = (function () {
  30755. function Polygon(vertices, shared) {
  30756. this.vertices = vertices;
  30757. this.shared = shared;
  30758. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30759. }
  30760. Polygon.prototype.clone = function () {
  30761. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30762. return new Polygon(vertices, this.shared);
  30763. };
  30764. Polygon.prototype.flip = function () {
  30765. this.vertices.reverse().map(function (v) { v.flip(); });
  30766. this.plane.flip();
  30767. };
  30768. return Polygon;
  30769. })();
  30770. // # class Node
  30771. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30772. // by picking a polygon to split along. That polygon (and all other coplanar
  30773. // polygons) are added directly to that node and the other polygons are added to
  30774. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30775. // no distinction between internal and leaf nodes.
  30776. var Node = (function () {
  30777. function Node(polygons) {
  30778. this.plane = null;
  30779. this.front = null;
  30780. this.back = null;
  30781. this.polygons = [];
  30782. if (polygons) {
  30783. this.build(polygons);
  30784. }
  30785. }
  30786. Node.prototype.clone = function () {
  30787. var node = new Node();
  30788. node.plane = this.plane && this.plane.clone();
  30789. node.front = this.front && this.front.clone();
  30790. node.back = this.back && this.back.clone();
  30791. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30792. return node;
  30793. };
  30794. // Convert solid space to empty space and empty space to solid space.
  30795. Node.prototype.invert = function () {
  30796. for (var i = 0; i < this.polygons.length; i++) {
  30797. this.polygons[i].flip();
  30798. }
  30799. if (this.plane) {
  30800. this.plane.flip();
  30801. }
  30802. if (this.front) {
  30803. this.front.invert();
  30804. }
  30805. if (this.back) {
  30806. this.back.invert();
  30807. }
  30808. var temp = this.front;
  30809. this.front = this.back;
  30810. this.back = temp;
  30811. };
  30812. // Recursively remove all polygons in `polygons` that are inside this BSP
  30813. // tree.
  30814. Node.prototype.clipPolygons = function (polygons) {
  30815. if (!this.plane)
  30816. return polygons.slice();
  30817. var front = [], back = [];
  30818. for (var i = 0; i < polygons.length; i++) {
  30819. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30820. }
  30821. if (this.front) {
  30822. front = this.front.clipPolygons(front);
  30823. }
  30824. if (this.back) {
  30825. back = this.back.clipPolygons(back);
  30826. }
  30827. else {
  30828. back = [];
  30829. }
  30830. return front.concat(back);
  30831. };
  30832. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30833. // `bsp`.
  30834. Node.prototype.clipTo = function (bsp) {
  30835. this.polygons = bsp.clipPolygons(this.polygons);
  30836. if (this.front)
  30837. this.front.clipTo(bsp);
  30838. if (this.back)
  30839. this.back.clipTo(bsp);
  30840. };
  30841. // Return a list of all polygons in this BSP tree.
  30842. Node.prototype.allPolygons = function () {
  30843. var polygons = this.polygons.slice();
  30844. if (this.front)
  30845. polygons = polygons.concat(this.front.allPolygons());
  30846. if (this.back)
  30847. polygons = polygons.concat(this.back.allPolygons());
  30848. return polygons;
  30849. };
  30850. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30851. // new polygons are filtered down to the bottom of the tree and become new
  30852. // nodes there. Each set of polygons is partitioned using the first polygon
  30853. // (no heuristic is used to pick a good split).
  30854. Node.prototype.build = function (polygons) {
  30855. if (!polygons.length)
  30856. return;
  30857. if (!this.plane)
  30858. this.plane = polygons[0].plane.clone();
  30859. var front = [], back = [];
  30860. for (var i = 0; i < polygons.length; i++) {
  30861. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30862. }
  30863. if (front.length) {
  30864. if (!this.front)
  30865. this.front = new Node();
  30866. this.front.build(front);
  30867. }
  30868. if (back.length) {
  30869. if (!this.back)
  30870. this.back = new Node();
  30871. this.back.build(back);
  30872. }
  30873. };
  30874. return Node;
  30875. })();
  30876. var CSG = (function () {
  30877. function CSG() {
  30878. this.polygons = new Array();
  30879. }
  30880. // Convert BABYLON.Mesh to BABYLON.CSG
  30881. CSG.FromMesh = function (mesh) {
  30882. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30883. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30884. if (mesh instanceof BABYLON.Mesh) {
  30885. mesh.computeWorldMatrix(true);
  30886. matrix = mesh.getWorldMatrix();
  30887. meshPosition = mesh.position.clone();
  30888. meshRotation = mesh.rotation.clone();
  30889. if (mesh.rotationQuaternion) {
  30890. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30891. }
  30892. meshScaling = mesh.scaling.clone();
  30893. }
  30894. else {
  30895. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30896. }
  30897. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30898. var subMeshes = mesh.subMeshes;
  30899. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30900. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30901. vertices = [];
  30902. for (var j = 0; j < 3; j++) {
  30903. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30904. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30905. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30906. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30907. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30908. vertex = new Vertex(position, normal, uv);
  30909. vertices.push(vertex);
  30910. }
  30911. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30912. // To handle the case of degenerated triangle
  30913. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30914. if (polygon.plane)
  30915. polygons.push(polygon);
  30916. }
  30917. }
  30918. var csg = CSG.FromPolygons(polygons);
  30919. csg.matrix = matrix;
  30920. csg.position = meshPosition;
  30921. csg.rotation = meshRotation;
  30922. csg.scaling = meshScaling;
  30923. csg.rotationQuaternion = meshRotationQuaternion;
  30924. currentCSGMeshId++;
  30925. return csg;
  30926. };
  30927. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30928. CSG.FromPolygons = function (polygons) {
  30929. var csg = new CSG();
  30930. csg.polygons = polygons;
  30931. return csg;
  30932. };
  30933. CSG.prototype.clone = function () {
  30934. var csg = new CSG();
  30935. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30936. csg.copyTransformAttributes(this);
  30937. return csg;
  30938. };
  30939. CSG.prototype.toPolygons = function () {
  30940. return this.polygons;
  30941. };
  30942. CSG.prototype.union = function (csg) {
  30943. var a = new Node(this.clone().polygons);
  30944. var b = new Node(csg.clone().polygons);
  30945. a.clipTo(b);
  30946. b.clipTo(a);
  30947. b.invert();
  30948. b.clipTo(a);
  30949. b.invert();
  30950. a.build(b.allPolygons());
  30951. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30952. };
  30953. CSG.prototype.unionInPlace = function (csg) {
  30954. var a = new Node(this.polygons);
  30955. var b = new Node(csg.polygons);
  30956. a.clipTo(b);
  30957. b.clipTo(a);
  30958. b.invert();
  30959. b.clipTo(a);
  30960. b.invert();
  30961. a.build(b.allPolygons());
  30962. this.polygons = a.allPolygons();
  30963. };
  30964. CSG.prototype.subtract = function (csg) {
  30965. var a = new Node(this.clone().polygons);
  30966. var b = new Node(csg.clone().polygons);
  30967. a.invert();
  30968. a.clipTo(b);
  30969. b.clipTo(a);
  30970. b.invert();
  30971. b.clipTo(a);
  30972. b.invert();
  30973. a.build(b.allPolygons());
  30974. a.invert();
  30975. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30976. };
  30977. CSG.prototype.subtractInPlace = function (csg) {
  30978. var a = new Node(this.polygons);
  30979. var b = new Node(csg.polygons);
  30980. a.invert();
  30981. a.clipTo(b);
  30982. b.clipTo(a);
  30983. b.invert();
  30984. b.clipTo(a);
  30985. b.invert();
  30986. a.build(b.allPolygons());
  30987. a.invert();
  30988. this.polygons = a.allPolygons();
  30989. };
  30990. CSG.prototype.intersect = function (csg) {
  30991. var a = new Node(this.clone().polygons);
  30992. var b = new Node(csg.clone().polygons);
  30993. a.invert();
  30994. b.clipTo(a);
  30995. b.invert();
  30996. a.clipTo(b);
  30997. b.clipTo(a);
  30998. a.build(b.allPolygons());
  30999. a.invert();
  31000. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31001. };
  31002. CSG.prototype.intersectInPlace = function (csg) {
  31003. var a = new Node(this.polygons);
  31004. var b = new Node(csg.polygons);
  31005. a.invert();
  31006. b.clipTo(a);
  31007. b.invert();
  31008. a.clipTo(b);
  31009. b.clipTo(a);
  31010. a.build(b.allPolygons());
  31011. a.invert();
  31012. this.polygons = a.allPolygons();
  31013. };
  31014. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31015. // not modified.
  31016. CSG.prototype.inverse = function () {
  31017. var csg = this.clone();
  31018. csg.inverseInPlace();
  31019. return csg;
  31020. };
  31021. CSG.prototype.inverseInPlace = function () {
  31022. this.polygons.map(function (p) { p.flip(); });
  31023. };
  31024. // This is used to keep meshes transformations so they can be restored
  31025. // when we build back a Babylon Mesh
  31026. // NB : All CSG operations are performed in world coordinates
  31027. CSG.prototype.copyTransformAttributes = function (csg) {
  31028. this.matrix = csg.matrix;
  31029. this.position = csg.position;
  31030. this.rotation = csg.rotation;
  31031. this.scaling = csg.scaling;
  31032. this.rotationQuaternion = csg.rotationQuaternion;
  31033. return this;
  31034. };
  31035. // Build Raw mesh from CSG
  31036. // Coordinates here are in world space
  31037. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31038. var matrix = this.matrix.clone();
  31039. matrix.invert();
  31040. 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;
  31041. if (keepSubMeshes) {
  31042. // Sort Polygons, since subMeshes are indices range
  31043. polygons.sort(function (a, b) {
  31044. if (a.shared.meshId === b.shared.meshId) {
  31045. return a.shared.subMeshId - b.shared.subMeshId;
  31046. }
  31047. else {
  31048. return a.shared.meshId - b.shared.meshId;
  31049. }
  31050. });
  31051. }
  31052. for (var i = 0, il = polygons.length; i < il; i++) {
  31053. polygon = polygons[i];
  31054. // Building SubMeshes
  31055. if (!subMesh_dict[polygon.shared.meshId]) {
  31056. subMesh_dict[polygon.shared.meshId] = {};
  31057. }
  31058. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31059. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31060. indexStart: +Infinity,
  31061. indexEnd: -Infinity,
  31062. materialIndex: polygon.shared.materialIndex
  31063. };
  31064. }
  31065. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31066. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31067. polygonIndices[0] = 0;
  31068. polygonIndices[1] = j - 1;
  31069. polygonIndices[2] = j;
  31070. for (var k = 0; k < 3; k++) {
  31071. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31072. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31073. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31074. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31075. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31076. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31077. // Check if 2 points can be merged
  31078. if (!(typeof vertex_idx !== 'undefined' &&
  31079. normals[vertex_idx * 3] === localNormal.x &&
  31080. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31081. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31082. uvs[vertex_idx * 2] === uv.x &&
  31083. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31084. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31085. uvs.push(uv.x, uv.y);
  31086. normals.push(normal.x, normal.y, normal.z);
  31087. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31088. }
  31089. indices.push(vertex_idx);
  31090. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31091. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31092. currentIndex++;
  31093. }
  31094. }
  31095. }
  31096. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31097. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31098. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31099. mesh.setIndices(indices);
  31100. if (keepSubMeshes) {
  31101. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31102. var materialIndexOffset = 0, materialMaxIndex;
  31103. mesh.subMeshes = new Array();
  31104. for (var m in subMesh_dict) {
  31105. materialMaxIndex = -1;
  31106. for (var sm in subMesh_dict[m]) {
  31107. subMesh_obj = subMesh_dict[m][sm];
  31108. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31109. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31110. }
  31111. materialIndexOffset += ++materialMaxIndex;
  31112. }
  31113. }
  31114. return mesh;
  31115. };
  31116. // Build Mesh from CSG taking material and transforms into account
  31117. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31118. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31119. mesh.material = material;
  31120. mesh.position.copyFrom(this.position);
  31121. mesh.rotation.copyFrom(this.rotation);
  31122. if (this.rotationQuaternion) {
  31123. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31124. }
  31125. mesh.scaling.copyFrom(this.scaling);
  31126. mesh.computeWorldMatrix(true);
  31127. return mesh;
  31128. };
  31129. return CSG;
  31130. })();
  31131. BABYLON.CSG = CSG;
  31132. })(BABYLON || (BABYLON = {}));
  31133. var BABYLON;
  31134. (function (BABYLON) {
  31135. var VRDistortionCorrectionPostProcess = (function (_super) {
  31136. __extends(VRDistortionCorrectionPostProcess, _super);
  31137. //ANY
  31138. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31139. var _this = this;
  31140. _super.call(this, name, "vrDistortionCorrection", [
  31141. 'LensCenter',
  31142. 'Scale',
  31143. 'ScaleIn',
  31144. 'HmdWarpParam'
  31145. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31146. this._isRightEye = isRightEye;
  31147. this._distortionFactors = vrMetrics.distortionK;
  31148. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31149. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31150. this.onSizeChanged = function () {
  31151. _this.aspectRatio = _this.width * .5 / _this.height;
  31152. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31153. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31154. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31155. };
  31156. this.onApply = function (effect) {
  31157. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31158. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31159. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31160. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31161. };
  31162. }
  31163. return VRDistortionCorrectionPostProcess;
  31164. })(BABYLON.PostProcess);
  31165. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31166. })(BABYLON || (BABYLON = {}));
  31167. // Mainly based on these 2 articles :
  31168. // 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
  31169. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31170. var BABYLON;
  31171. (function (BABYLON) {
  31172. (function (JoystickAxis) {
  31173. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31174. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31175. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31176. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31177. var JoystickAxis = BABYLON.JoystickAxis;
  31178. var VirtualJoystick = (function () {
  31179. function VirtualJoystick(leftJoystick) {
  31180. var _this = this;
  31181. if (leftJoystick) {
  31182. this._leftJoystick = true;
  31183. }
  31184. else {
  31185. this._leftJoystick = false;
  31186. }
  31187. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31188. VirtualJoystick._globalJoystickIndex++;
  31189. // By default left & right arrow keys are moving the X
  31190. // and up & down keys are moving the Y
  31191. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31192. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31193. this.reverseLeftRight = false;
  31194. this.reverseUpDown = false;
  31195. // collections of pointers
  31196. this._touches = new BABYLON.SmartCollection();
  31197. this.deltaPosition = BABYLON.Vector3.Zero();
  31198. this._joystickSensibility = 25;
  31199. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31200. this._rotationSpeed = 25;
  31201. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31202. this._rotateOnAxisRelativeToMesh = false;
  31203. this._onResize = function (evt) {
  31204. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31205. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31206. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31207. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31208. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31209. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31210. };
  31211. // injecting a canvas element on top of the canvas 3D game
  31212. if (!VirtualJoystick.vjCanvas) {
  31213. window.addEventListener("resize", this._onResize, false);
  31214. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31215. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31216. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31217. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31218. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31219. VirtualJoystick.vjCanvas.style.width = "100%";
  31220. VirtualJoystick.vjCanvas.style.height = "100%";
  31221. VirtualJoystick.vjCanvas.style.position = "absolute";
  31222. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31223. VirtualJoystick.vjCanvas.style.top = "0px";
  31224. VirtualJoystick.vjCanvas.style.left = "0px";
  31225. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31226. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31227. // Support for jQuery PEP polyfill
  31228. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31229. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31230. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31231. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31232. document.body.appendChild(VirtualJoystick.vjCanvas);
  31233. }
  31234. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31235. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31236. this.pressed = false;
  31237. // default joystick color
  31238. this._joystickColor = "cyan";
  31239. this._joystickPointerID = -1;
  31240. // current joystick position
  31241. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31242. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31243. // origin joystick position
  31244. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31245. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31246. this._onPointerDownHandlerRef = function (evt) {
  31247. _this._onPointerDown(evt);
  31248. };
  31249. this._onPointerMoveHandlerRef = function (evt) {
  31250. _this._onPointerMove(evt);
  31251. };
  31252. this._onPointerOutHandlerRef = function (evt) {
  31253. _this._onPointerUp(evt);
  31254. };
  31255. this._onPointerUpHandlerRef = function (evt) {
  31256. _this._onPointerUp(evt);
  31257. };
  31258. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31259. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31260. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31261. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31262. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31263. evt.preventDefault(); // Disables system menu
  31264. }, false);
  31265. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31266. }
  31267. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31268. this._joystickSensibility = newJoystickSensibility;
  31269. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31270. };
  31271. VirtualJoystick.prototype._onPointerDown = function (e) {
  31272. var positionOnScreenCondition;
  31273. e.preventDefault();
  31274. if (this._leftJoystick === true) {
  31275. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31276. }
  31277. else {
  31278. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31279. }
  31280. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31281. // First contact will be dedicated to the virtual joystick
  31282. this._joystickPointerID = e.pointerId;
  31283. this._joystickPointerStartPos.x = e.clientX;
  31284. this._joystickPointerStartPos.y = e.clientY;
  31285. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31286. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31287. this._deltaJoystickVector.x = 0;
  31288. this._deltaJoystickVector.y = 0;
  31289. this.pressed = true;
  31290. this._touches.add(e.pointerId.toString(), e);
  31291. }
  31292. else {
  31293. // You can only trigger the action buttons with a joystick declared
  31294. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31295. this._action();
  31296. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31297. }
  31298. }
  31299. };
  31300. VirtualJoystick.prototype._onPointerMove = function (e) {
  31301. // If the current pointer is the one associated to the joystick (first touch contact)
  31302. if (this._joystickPointerID == e.pointerId) {
  31303. this._joystickPointerPos.x = e.clientX;
  31304. this._joystickPointerPos.y = e.clientY;
  31305. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31306. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31307. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31308. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31309. switch (this._axisTargetedByLeftAndRight) {
  31310. case JoystickAxis.X:
  31311. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31312. break;
  31313. case JoystickAxis.Y:
  31314. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31315. break;
  31316. case JoystickAxis.Z:
  31317. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31318. break;
  31319. }
  31320. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31321. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31322. switch (this._axisTargetedByUpAndDown) {
  31323. case JoystickAxis.X:
  31324. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31325. break;
  31326. case JoystickAxis.Y:
  31327. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31328. break;
  31329. case JoystickAxis.Z:
  31330. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31331. break;
  31332. }
  31333. }
  31334. else {
  31335. if (this._touches.item(e.pointerId.toString())) {
  31336. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31337. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31338. }
  31339. }
  31340. };
  31341. VirtualJoystick.prototype._onPointerUp = function (e) {
  31342. if (this._joystickPointerID == e.pointerId) {
  31343. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31344. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31345. this._joystickPointerID = -1;
  31346. this.pressed = false;
  31347. }
  31348. else {
  31349. var touch = this._touches.item(e.pointerId.toString());
  31350. if (touch) {
  31351. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31352. }
  31353. }
  31354. this._deltaJoystickVector.x = 0;
  31355. this._deltaJoystickVector.y = 0;
  31356. this._touches.remove(e.pointerId.toString());
  31357. };
  31358. /**
  31359. * Change the color of the virtual joystick
  31360. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31361. */
  31362. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31363. this._joystickColor = newColor;
  31364. };
  31365. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31366. this._action = action;
  31367. };
  31368. // Define which axis you'd like to control for left & right
  31369. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31370. switch (axis) {
  31371. case JoystickAxis.X:
  31372. case JoystickAxis.Y:
  31373. case JoystickAxis.Z:
  31374. this._axisTargetedByLeftAndRight = axis;
  31375. break;
  31376. default:
  31377. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31378. break;
  31379. }
  31380. };
  31381. // Define which axis you'd like to control for up & down
  31382. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31383. switch (axis) {
  31384. case JoystickAxis.X:
  31385. case JoystickAxis.Y:
  31386. case JoystickAxis.Z:
  31387. this._axisTargetedByUpAndDown = axis;
  31388. break;
  31389. default:
  31390. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31391. break;
  31392. }
  31393. };
  31394. VirtualJoystick.prototype._clearCanvas = function () {
  31395. if (this._leftJoystick) {
  31396. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31397. }
  31398. else {
  31399. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31400. }
  31401. };
  31402. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31403. var _this = this;
  31404. if (this.pressed) {
  31405. this._touches.forEach(function (touch) {
  31406. if (touch.pointerId === _this._joystickPointerID) {
  31407. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31408. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31409. VirtualJoystick.vjCanvasContext.beginPath();
  31410. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31411. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31412. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31413. VirtualJoystick.vjCanvasContext.stroke();
  31414. VirtualJoystick.vjCanvasContext.closePath();
  31415. VirtualJoystick.vjCanvasContext.beginPath();
  31416. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31417. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31418. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31419. VirtualJoystick.vjCanvasContext.stroke();
  31420. VirtualJoystick.vjCanvasContext.closePath();
  31421. VirtualJoystick.vjCanvasContext.beginPath();
  31422. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31423. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31424. VirtualJoystick.vjCanvasContext.stroke();
  31425. VirtualJoystick.vjCanvasContext.closePath();
  31426. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31427. }
  31428. else {
  31429. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31430. VirtualJoystick.vjCanvasContext.beginPath();
  31431. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31432. VirtualJoystick.vjCanvasContext.beginPath();
  31433. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31434. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31435. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31436. VirtualJoystick.vjCanvasContext.stroke();
  31437. VirtualJoystick.vjCanvasContext.closePath();
  31438. touch.prevX = touch.x;
  31439. touch.prevY = touch.y;
  31440. }
  31441. ;
  31442. });
  31443. }
  31444. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31445. };
  31446. VirtualJoystick.prototype.releaseCanvas = function () {
  31447. if (VirtualJoystick.vjCanvas) {
  31448. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31449. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31450. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31451. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31452. window.removeEventListener("resize", this._onResize);
  31453. document.body.removeChild(VirtualJoystick.vjCanvas);
  31454. VirtualJoystick.vjCanvas = null;
  31455. }
  31456. };
  31457. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31458. VirtualJoystick._globalJoystickIndex = 0;
  31459. return VirtualJoystick;
  31460. })();
  31461. BABYLON.VirtualJoystick = VirtualJoystick;
  31462. })(BABYLON || (BABYLON = {}));
  31463. var BABYLON;
  31464. (function (BABYLON) {
  31465. // We're mainly based on the logic defined into the FreeCamera code
  31466. var VirtualJoysticksCamera = (function (_super) {
  31467. __extends(VirtualJoysticksCamera, _super);
  31468. function VirtualJoysticksCamera(name, position, scene) {
  31469. _super.call(this, name, position, scene);
  31470. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31471. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31472. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31473. this._leftjoystick.setJoystickSensibility(0.15);
  31474. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31475. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31476. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31477. this._rightjoystick.reverseUpDown = true;
  31478. this._rightjoystick.setJoystickSensibility(0.05);
  31479. this._rightjoystick.setJoystickColor("yellow");
  31480. }
  31481. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31482. return this._leftjoystick;
  31483. };
  31484. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31485. return this._rightjoystick;
  31486. };
  31487. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31488. var speed = this._computeLocalCameraSpeed() * 50;
  31489. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31490. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31491. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31492. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31493. if (!this._leftjoystick.pressed) {
  31494. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31495. }
  31496. if (!this._rightjoystick.pressed) {
  31497. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31498. }
  31499. _super.prototype._checkInputs.call(this);
  31500. };
  31501. VirtualJoysticksCamera.prototype.dispose = function () {
  31502. this._leftjoystick.releaseCanvas();
  31503. _super.prototype.dispose.call(this);
  31504. };
  31505. return VirtualJoysticksCamera;
  31506. })(BABYLON.FreeCamera);
  31507. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31508. })(BABYLON || (BABYLON = {}));
  31509. var BABYLON;
  31510. (function (BABYLON) {
  31511. var AnaglyphPostProcess = (function (_super) {
  31512. __extends(AnaglyphPostProcess, _super);
  31513. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31514. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31515. }
  31516. return AnaglyphPostProcess;
  31517. })(BABYLON.PostProcess);
  31518. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31519. })(BABYLON || (BABYLON = {}));
  31520. var BABYLON;
  31521. (function (BABYLON) {
  31522. var OutlineRenderer = (function () {
  31523. function OutlineRenderer(scene) {
  31524. this._scene = scene;
  31525. }
  31526. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31527. var _this = this;
  31528. if (useOverlay === void 0) { useOverlay = false; }
  31529. var scene = this._scene;
  31530. var engine = this._scene.getEngine();
  31531. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31532. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31533. return;
  31534. }
  31535. var mesh = subMesh.getRenderingMesh();
  31536. var material = subMesh.getMaterial();
  31537. engine.enableEffect(this._effect);
  31538. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31539. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31540. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31541. // Bones
  31542. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31543. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31544. }
  31545. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31546. // Alpha test
  31547. if (material && material.needAlphaTesting()) {
  31548. var alphaTexture = material.getAlphaTestTexture();
  31549. this._effect.setTexture("diffuseSampler", alphaTexture);
  31550. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31551. }
  31552. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31553. };
  31554. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31555. var defines = [];
  31556. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31557. var mesh = subMesh.getMesh();
  31558. var material = subMesh.getMaterial();
  31559. // Alpha test
  31560. if (material && material.needAlphaTesting()) {
  31561. defines.push("#define ALPHATEST");
  31562. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31563. attribs.push(BABYLON.VertexBuffer.UVKind);
  31564. defines.push("#define UV1");
  31565. }
  31566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31567. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31568. defines.push("#define UV2");
  31569. }
  31570. }
  31571. // Bones
  31572. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31573. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31574. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31575. if (mesh.numBoneInfluencers > 4) {
  31576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31578. }
  31579. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31580. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31581. }
  31582. else {
  31583. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31584. }
  31585. // Instances
  31586. if (useInstances) {
  31587. defines.push("#define INSTANCES");
  31588. attribs.push("world0");
  31589. attribs.push("world1");
  31590. attribs.push("world2");
  31591. attribs.push("world3");
  31592. }
  31593. // Get correct effect
  31594. var join = defines.join("\n");
  31595. if (this._cachedDefines !== join) {
  31596. this._cachedDefines = join;
  31597. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31598. }
  31599. return this._effect.isReady();
  31600. };
  31601. return OutlineRenderer;
  31602. })();
  31603. BABYLON.OutlineRenderer = OutlineRenderer;
  31604. })(BABYLON || (BABYLON = {}));
  31605. var BABYLON;
  31606. (function (BABYLON) {
  31607. var MeshAssetTask = (function () {
  31608. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31609. this.name = name;
  31610. this.meshesNames = meshesNames;
  31611. this.rootUrl = rootUrl;
  31612. this.sceneFilename = sceneFilename;
  31613. this.isCompleted = false;
  31614. }
  31615. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31616. var _this = this;
  31617. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31618. _this.loadedMeshes = meshes;
  31619. _this.loadedParticleSystems = particleSystems;
  31620. _this.loadedSkeletons = skeletons;
  31621. _this.isCompleted = true;
  31622. if (_this.onSuccess) {
  31623. _this.onSuccess(_this);
  31624. }
  31625. onSuccess();
  31626. }, null, function () {
  31627. if (_this.onError) {
  31628. _this.onError(_this);
  31629. }
  31630. onError();
  31631. });
  31632. };
  31633. return MeshAssetTask;
  31634. })();
  31635. BABYLON.MeshAssetTask = MeshAssetTask;
  31636. var TextFileAssetTask = (function () {
  31637. function TextFileAssetTask(name, url) {
  31638. this.name = name;
  31639. this.url = url;
  31640. this.isCompleted = false;
  31641. }
  31642. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31643. var _this = this;
  31644. BABYLON.Tools.LoadFile(this.url, function (data) {
  31645. _this.text = data;
  31646. _this.isCompleted = true;
  31647. if (_this.onSuccess) {
  31648. _this.onSuccess(_this);
  31649. }
  31650. onSuccess();
  31651. }, null, scene.database, false, function () {
  31652. if (_this.onError) {
  31653. _this.onError(_this);
  31654. }
  31655. onError();
  31656. });
  31657. };
  31658. return TextFileAssetTask;
  31659. })();
  31660. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31661. var BinaryFileAssetTask = (function () {
  31662. function BinaryFileAssetTask(name, url) {
  31663. this.name = name;
  31664. this.url = url;
  31665. this.isCompleted = false;
  31666. }
  31667. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31668. var _this = this;
  31669. BABYLON.Tools.LoadFile(this.url, function (data) {
  31670. _this.data = data;
  31671. _this.isCompleted = true;
  31672. if (_this.onSuccess) {
  31673. _this.onSuccess(_this);
  31674. }
  31675. onSuccess();
  31676. }, null, scene.database, true, function () {
  31677. if (_this.onError) {
  31678. _this.onError(_this);
  31679. }
  31680. onError();
  31681. });
  31682. };
  31683. return BinaryFileAssetTask;
  31684. })();
  31685. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31686. var ImageAssetTask = (function () {
  31687. function ImageAssetTask(name, url) {
  31688. this.name = name;
  31689. this.url = url;
  31690. this.isCompleted = false;
  31691. }
  31692. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31693. var _this = this;
  31694. var img = new Image();
  31695. img.onload = function () {
  31696. _this.image = img;
  31697. _this.isCompleted = true;
  31698. if (_this.onSuccess) {
  31699. _this.onSuccess(_this);
  31700. }
  31701. onSuccess();
  31702. };
  31703. img.onerror = function () {
  31704. if (_this.onError) {
  31705. _this.onError(_this);
  31706. }
  31707. onError();
  31708. };
  31709. img.src = this.url;
  31710. };
  31711. return ImageAssetTask;
  31712. })();
  31713. BABYLON.ImageAssetTask = ImageAssetTask;
  31714. var TextureAssetTask = (function () {
  31715. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31717. this.name = name;
  31718. this.url = url;
  31719. this.noMipmap = noMipmap;
  31720. this.invertY = invertY;
  31721. this.samplingMode = samplingMode;
  31722. this.isCompleted = false;
  31723. }
  31724. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31725. var _this = this;
  31726. var onload = function () {
  31727. _this.isCompleted = true;
  31728. if (_this.onSuccess) {
  31729. _this.onSuccess(_this);
  31730. }
  31731. onSuccess();
  31732. };
  31733. var onerror = function () {
  31734. if (_this.onError) {
  31735. _this.onError(_this);
  31736. }
  31737. onError();
  31738. };
  31739. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31740. };
  31741. return TextureAssetTask;
  31742. })();
  31743. BABYLON.TextureAssetTask = TextureAssetTask;
  31744. var AssetsManager = (function () {
  31745. function AssetsManager(scene) {
  31746. this._tasks = new Array();
  31747. this._waitingTasksCount = 0;
  31748. this.useDefaultLoadingScreen = true;
  31749. this._scene = scene;
  31750. }
  31751. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31752. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31753. this._tasks.push(task);
  31754. return task;
  31755. };
  31756. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31757. var task = new TextFileAssetTask(taskName, url);
  31758. this._tasks.push(task);
  31759. return task;
  31760. };
  31761. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31762. var task = new BinaryFileAssetTask(taskName, url);
  31763. this._tasks.push(task);
  31764. return task;
  31765. };
  31766. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31767. var task = new ImageAssetTask(taskName, url);
  31768. this._tasks.push(task);
  31769. return task;
  31770. };
  31771. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31773. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31774. this._tasks.push(task);
  31775. return task;
  31776. };
  31777. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31778. this._waitingTasksCount--;
  31779. if (this._waitingTasksCount === 0) {
  31780. if (this.onFinish) {
  31781. this.onFinish(this._tasks);
  31782. }
  31783. this._scene.getEngine().hideLoadingUI();
  31784. }
  31785. };
  31786. AssetsManager.prototype._runTask = function (task) {
  31787. var _this = this;
  31788. task.run(this._scene, function () {
  31789. if (_this.onTaskSuccess) {
  31790. _this.onTaskSuccess(task);
  31791. }
  31792. _this._decreaseWaitingTasksCount();
  31793. }, function () {
  31794. if (_this.onTaskError) {
  31795. _this.onTaskError(task);
  31796. }
  31797. _this._decreaseWaitingTasksCount();
  31798. });
  31799. };
  31800. AssetsManager.prototype.reset = function () {
  31801. this._tasks = new Array();
  31802. return this;
  31803. };
  31804. AssetsManager.prototype.load = function () {
  31805. this._waitingTasksCount = this._tasks.length;
  31806. if (this._waitingTasksCount === 0) {
  31807. if (this.onFinish) {
  31808. this.onFinish(this._tasks);
  31809. }
  31810. return this;
  31811. }
  31812. if (this.useDefaultLoadingScreen) {
  31813. this._scene.getEngine().displayLoadingUI();
  31814. }
  31815. for (var index = 0; index < this._tasks.length; index++) {
  31816. var task = this._tasks[index];
  31817. this._runTask(task);
  31818. }
  31819. return this;
  31820. };
  31821. return AssetsManager;
  31822. })();
  31823. BABYLON.AssetsManager = AssetsManager;
  31824. })(BABYLON || (BABYLON = {}));
  31825. var BABYLON;
  31826. (function (BABYLON) {
  31827. var VRDeviceOrientationFreeCamera = (function (_super) {
  31828. __extends(VRDeviceOrientationFreeCamera, _super);
  31829. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31830. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31831. _super.call(this, name, position, scene);
  31832. this._alpha = 0;
  31833. this._beta = 0;
  31834. this._gamma = 0;
  31835. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31836. metrics.compensateDistortion = compensateDistortion;
  31837. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31838. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31839. }
  31840. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31841. this._alpha = +evt.alpha | 0;
  31842. this._beta = +evt.beta | 0;
  31843. this._gamma = +evt.gamma | 0;
  31844. if (this._gamma < 0) {
  31845. this._gamma = 90 + this._gamma;
  31846. }
  31847. else {
  31848. // Incline it in the correct angle.
  31849. this._gamma = 270 - this._gamma;
  31850. }
  31851. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31852. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31853. this.rotation.z = this._beta / 180.0 * Math.PI;
  31854. };
  31855. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31856. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31857. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31858. };
  31859. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31860. _super.prototype.detachControl.call(this, element);
  31861. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31862. };
  31863. return VRDeviceOrientationFreeCamera;
  31864. })(BABYLON.FreeCamera);
  31865. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31866. })(BABYLON || (BABYLON = {}));
  31867. var BABYLON;
  31868. (function (BABYLON) {
  31869. var WebVRFreeCamera = (function (_super) {
  31870. __extends(WebVRFreeCamera, _super);
  31871. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31872. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31873. _super.call(this, name, position, scene);
  31874. this._hmdDevice = null;
  31875. this._sensorDevice = null;
  31876. this._cacheState = null;
  31877. this._cacheQuaternion = new BABYLON.Quaternion();
  31878. this._cacheRotation = BABYLON.Vector3.Zero();
  31879. this._vrEnabled = false;
  31880. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31881. metrics.compensateDistortion = compensateDistortion;
  31882. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31883. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31884. }
  31885. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31886. var size = devices.length;
  31887. var i = 0;
  31888. // Reset devices.
  31889. this._sensorDevice = null;
  31890. this._hmdDevice = null;
  31891. // Search for a HmdDevice.
  31892. while (i < size && this._hmdDevice === null) {
  31893. if (devices[i] instanceof HMDVRDevice) {
  31894. this._hmdDevice = devices[i];
  31895. }
  31896. i++;
  31897. }
  31898. i = 0;
  31899. while (i < size && this._sensorDevice === null) {
  31900. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31901. this._sensorDevice = devices[i];
  31902. }
  31903. i++;
  31904. }
  31905. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31906. };
  31907. WebVRFreeCamera.prototype._checkInputs = function () {
  31908. if (this._vrEnabled) {
  31909. this._cacheState = this._sensorDevice.getState();
  31910. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31911. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31912. this.rotation.x = -this._cacheRotation.z;
  31913. this.rotation.y = -this._cacheRotation.y;
  31914. this.rotation.z = this._cacheRotation.x;
  31915. }
  31916. _super.prototype._checkInputs.call(this);
  31917. };
  31918. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31919. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31920. if (navigator.getVRDevices) {
  31921. navigator.getVRDevices().then(this._getWebVRDevices);
  31922. }
  31923. else if (navigator.mozGetVRDevices) {
  31924. navigator.mozGetVRDevices(this._getWebVRDevices);
  31925. }
  31926. };
  31927. WebVRFreeCamera.prototype.detachControl = function (element) {
  31928. _super.prototype.detachControl.call(this, element);
  31929. this._vrEnabled = false;
  31930. };
  31931. return WebVRFreeCamera;
  31932. })(BABYLON.FreeCamera);
  31933. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31934. })(BABYLON || (BABYLON = {}));
  31935. var BABYLON;
  31936. (function (BABYLON) {
  31937. // Standard optimizations
  31938. var SceneOptimization = (function () {
  31939. function SceneOptimization(priority) {
  31940. if (priority === void 0) { priority = 0; }
  31941. this.priority = priority;
  31942. this.apply = function (scene) {
  31943. return true; // Return true if everything that can be done was applied
  31944. };
  31945. }
  31946. return SceneOptimization;
  31947. })();
  31948. BABYLON.SceneOptimization = SceneOptimization;
  31949. var TextureOptimization = (function (_super) {
  31950. __extends(TextureOptimization, _super);
  31951. function TextureOptimization(priority, maximumSize) {
  31952. var _this = this;
  31953. if (priority === void 0) { priority = 0; }
  31954. if (maximumSize === void 0) { maximumSize = 1024; }
  31955. _super.call(this, priority);
  31956. this.priority = priority;
  31957. this.maximumSize = maximumSize;
  31958. this.apply = function (scene) {
  31959. var allDone = true;
  31960. for (var index = 0; index < scene.textures.length; index++) {
  31961. var texture = scene.textures[index];
  31962. if (!texture.canRescale) {
  31963. continue;
  31964. }
  31965. var currentSize = texture.getSize();
  31966. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31967. if (maxDimension > _this.maximumSize) {
  31968. texture.scale(0.5);
  31969. allDone = false;
  31970. }
  31971. }
  31972. return allDone;
  31973. };
  31974. }
  31975. return TextureOptimization;
  31976. })(SceneOptimization);
  31977. BABYLON.TextureOptimization = TextureOptimization;
  31978. var HardwareScalingOptimization = (function (_super) {
  31979. __extends(HardwareScalingOptimization, _super);
  31980. function HardwareScalingOptimization(priority, maximumScale) {
  31981. var _this = this;
  31982. if (priority === void 0) { priority = 0; }
  31983. if (maximumScale === void 0) { maximumScale = 2; }
  31984. _super.call(this, priority);
  31985. this.priority = priority;
  31986. this.maximumScale = maximumScale;
  31987. this._currentScale = 1;
  31988. this.apply = function (scene) {
  31989. _this._currentScale++;
  31990. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31991. return _this._currentScale >= _this.maximumScale;
  31992. };
  31993. }
  31994. return HardwareScalingOptimization;
  31995. })(SceneOptimization);
  31996. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31997. var ShadowsOptimization = (function (_super) {
  31998. __extends(ShadowsOptimization, _super);
  31999. function ShadowsOptimization() {
  32000. _super.apply(this, arguments);
  32001. this.apply = function (scene) {
  32002. scene.shadowsEnabled = false;
  32003. return true;
  32004. };
  32005. }
  32006. return ShadowsOptimization;
  32007. })(SceneOptimization);
  32008. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32009. var PostProcessesOptimization = (function (_super) {
  32010. __extends(PostProcessesOptimization, _super);
  32011. function PostProcessesOptimization() {
  32012. _super.apply(this, arguments);
  32013. this.apply = function (scene) {
  32014. scene.postProcessesEnabled = false;
  32015. return true;
  32016. };
  32017. }
  32018. return PostProcessesOptimization;
  32019. })(SceneOptimization);
  32020. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32021. var LensFlaresOptimization = (function (_super) {
  32022. __extends(LensFlaresOptimization, _super);
  32023. function LensFlaresOptimization() {
  32024. _super.apply(this, arguments);
  32025. this.apply = function (scene) {
  32026. scene.lensFlaresEnabled = false;
  32027. return true;
  32028. };
  32029. }
  32030. return LensFlaresOptimization;
  32031. })(SceneOptimization);
  32032. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32033. var ParticlesOptimization = (function (_super) {
  32034. __extends(ParticlesOptimization, _super);
  32035. function ParticlesOptimization() {
  32036. _super.apply(this, arguments);
  32037. this.apply = function (scene) {
  32038. scene.particlesEnabled = false;
  32039. return true;
  32040. };
  32041. }
  32042. return ParticlesOptimization;
  32043. })(SceneOptimization);
  32044. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32045. var RenderTargetsOptimization = (function (_super) {
  32046. __extends(RenderTargetsOptimization, _super);
  32047. function RenderTargetsOptimization() {
  32048. _super.apply(this, arguments);
  32049. this.apply = function (scene) {
  32050. scene.renderTargetsEnabled = false;
  32051. return true;
  32052. };
  32053. }
  32054. return RenderTargetsOptimization;
  32055. })(SceneOptimization);
  32056. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32057. var MergeMeshesOptimization = (function (_super) {
  32058. __extends(MergeMeshesOptimization, _super);
  32059. function MergeMeshesOptimization() {
  32060. var _this = this;
  32061. _super.apply(this, arguments);
  32062. this._canBeMerged = function (abstractMesh) {
  32063. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32064. return false;
  32065. }
  32066. var mesh = abstractMesh;
  32067. if (!mesh.isVisible || !mesh.isEnabled()) {
  32068. return false;
  32069. }
  32070. if (mesh.instances.length > 0) {
  32071. return false;
  32072. }
  32073. if (mesh.skeleton || mesh.hasLODLevels) {
  32074. return false;
  32075. }
  32076. if (mesh.parent) {
  32077. return false;
  32078. }
  32079. return true;
  32080. };
  32081. this.apply = function (scene, updateSelectionTree) {
  32082. var globalPool = scene.meshes.slice(0);
  32083. var globalLength = globalPool.length;
  32084. for (var index = 0; index < globalLength; index++) {
  32085. var currentPool = new Array();
  32086. var current = globalPool[index];
  32087. // Checks
  32088. if (!_this._canBeMerged(current)) {
  32089. continue;
  32090. }
  32091. currentPool.push(current);
  32092. // Find compatible meshes
  32093. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32094. var otherMesh = globalPool[subIndex];
  32095. if (!_this._canBeMerged(otherMesh)) {
  32096. continue;
  32097. }
  32098. if (otherMesh.material !== current.material) {
  32099. continue;
  32100. }
  32101. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32102. continue;
  32103. }
  32104. currentPool.push(otherMesh);
  32105. globalLength--;
  32106. globalPool.splice(subIndex, 1);
  32107. subIndex--;
  32108. }
  32109. if (currentPool.length < 2) {
  32110. continue;
  32111. }
  32112. // Merge meshes
  32113. BABYLON.Mesh.MergeMeshes(currentPool);
  32114. }
  32115. if (updateSelectionTree != undefined) {
  32116. if (updateSelectionTree) {
  32117. scene.createOrUpdateSelectionOctree();
  32118. }
  32119. }
  32120. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32121. scene.createOrUpdateSelectionOctree();
  32122. }
  32123. return true;
  32124. };
  32125. }
  32126. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32127. get: function () {
  32128. return MergeMeshesOptimization._UpdateSelectionTree;
  32129. },
  32130. set: function (value) {
  32131. MergeMeshesOptimization._UpdateSelectionTree = value;
  32132. },
  32133. enumerable: true,
  32134. configurable: true
  32135. });
  32136. MergeMeshesOptimization._UpdateSelectionTree = false;
  32137. return MergeMeshesOptimization;
  32138. })(SceneOptimization);
  32139. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32140. // Options
  32141. var SceneOptimizerOptions = (function () {
  32142. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32143. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32144. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32145. this.targetFrameRate = targetFrameRate;
  32146. this.trackerDuration = trackerDuration;
  32147. this.optimizations = new Array();
  32148. }
  32149. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32150. var result = new SceneOptimizerOptions(targetFrameRate);
  32151. var priority = 0;
  32152. result.optimizations.push(new MergeMeshesOptimization(priority));
  32153. result.optimizations.push(new ShadowsOptimization(priority));
  32154. result.optimizations.push(new LensFlaresOptimization(priority));
  32155. // Next priority
  32156. priority++;
  32157. result.optimizations.push(new PostProcessesOptimization(priority));
  32158. result.optimizations.push(new ParticlesOptimization(priority));
  32159. // Next priority
  32160. priority++;
  32161. result.optimizations.push(new TextureOptimization(priority, 1024));
  32162. return result;
  32163. };
  32164. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32165. var result = new SceneOptimizerOptions(targetFrameRate);
  32166. var priority = 0;
  32167. result.optimizations.push(new MergeMeshesOptimization(priority));
  32168. result.optimizations.push(new ShadowsOptimization(priority));
  32169. result.optimizations.push(new LensFlaresOptimization(priority));
  32170. // Next priority
  32171. priority++;
  32172. result.optimizations.push(new PostProcessesOptimization(priority));
  32173. result.optimizations.push(new ParticlesOptimization(priority));
  32174. // Next priority
  32175. priority++;
  32176. result.optimizations.push(new TextureOptimization(priority, 512));
  32177. // Next priority
  32178. priority++;
  32179. result.optimizations.push(new RenderTargetsOptimization(priority));
  32180. // Next priority
  32181. priority++;
  32182. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32183. return result;
  32184. };
  32185. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32186. var result = new SceneOptimizerOptions(targetFrameRate);
  32187. var priority = 0;
  32188. result.optimizations.push(new MergeMeshesOptimization(priority));
  32189. result.optimizations.push(new ShadowsOptimization(priority));
  32190. result.optimizations.push(new LensFlaresOptimization(priority));
  32191. // Next priority
  32192. priority++;
  32193. result.optimizations.push(new PostProcessesOptimization(priority));
  32194. result.optimizations.push(new ParticlesOptimization(priority));
  32195. // Next priority
  32196. priority++;
  32197. result.optimizations.push(new TextureOptimization(priority, 256));
  32198. // Next priority
  32199. priority++;
  32200. result.optimizations.push(new RenderTargetsOptimization(priority));
  32201. // Next priority
  32202. priority++;
  32203. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32204. return result;
  32205. };
  32206. return SceneOptimizerOptions;
  32207. })();
  32208. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32209. // Scene optimizer tool
  32210. var SceneOptimizer = (function () {
  32211. function SceneOptimizer() {
  32212. }
  32213. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32214. // TODO: add an epsilon
  32215. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32216. if (onSuccess) {
  32217. onSuccess();
  32218. }
  32219. return;
  32220. }
  32221. // Apply current level of optimizations
  32222. var allDone = true;
  32223. var noOptimizationApplied = true;
  32224. for (var index = 0; index < options.optimizations.length; index++) {
  32225. var optimization = options.optimizations[index];
  32226. if (optimization.priority === currentPriorityLevel) {
  32227. noOptimizationApplied = false;
  32228. allDone = allDone && optimization.apply(scene);
  32229. }
  32230. }
  32231. // If no optimization was applied, this is a failure :(
  32232. if (noOptimizationApplied) {
  32233. if (onFailure) {
  32234. onFailure();
  32235. }
  32236. return;
  32237. }
  32238. // If all optimizations were done, move to next level
  32239. if (allDone) {
  32240. currentPriorityLevel++;
  32241. }
  32242. // Let's the system running for a specific amount of time before checking FPS
  32243. scene.executeWhenReady(function () {
  32244. setTimeout(function () {
  32245. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32246. }, options.trackerDuration);
  32247. });
  32248. };
  32249. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32250. if (!options) {
  32251. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32252. }
  32253. // Let's the system running for a specific amount of time before checking FPS
  32254. scene.executeWhenReady(function () {
  32255. setTimeout(function () {
  32256. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32257. }, options.trackerDuration);
  32258. });
  32259. };
  32260. return SceneOptimizer;
  32261. })();
  32262. BABYLON.SceneOptimizer = SceneOptimizer;
  32263. })(BABYLON || (BABYLON = {}));
  32264. var BABYLON;
  32265. (function (BABYLON) {
  32266. var Internals;
  32267. (function (Internals) {
  32268. var MeshLODLevel = (function () {
  32269. function MeshLODLevel(distance, mesh) {
  32270. this.distance = distance;
  32271. this.mesh = mesh;
  32272. }
  32273. return MeshLODLevel;
  32274. })();
  32275. Internals.MeshLODLevel = MeshLODLevel;
  32276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32277. })(BABYLON || (BABYLON = {}));
  32278. var BABYLON;
  32279. (function (BABYLON) {
  32280. var RawTexture = (function (_super) {
  32281. __extends(RawTexture, _super);
  32282. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32283. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32284. if (invertY === void 0) { invertY = false; }
  32285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32286. _super.call(this, null, scene, !generateMipMaps, invertY);
  32287. this.format = format;
  32288. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32289. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32290. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32291. }
  32292. RawTexture.prototype.update = function (data) {
  32293. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32294. };
  32295. // Statics
  32296. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32297. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32298. if (invertY === void 0) { invertY = false; }
  32299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32300. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32301. };
  32302. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32304. if (invertY === void 0) { invertY = false; }
  32305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32306. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32307. };
  32308. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32310. if (invertY === void 0) { invertY = false; }
  32311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32312. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32313. };
  32314. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32315. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32316. if (invertY === void 0) { invertY = false; }
  32317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32318. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32319. };
  32320. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32321. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32322. if (invertY === void 0) { invertY = false; }
  32323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32324. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32325. };
  32326. return RawTexture;
  32327. })(BABYLON.Texture);
  32328. BABYLON.RawTexture = RawTexture;
  32329. })(BABYLON || (BABYLON = {}));
  32330. var BABYLON;
  32331. (function (BABYLON) {
  32332. var IndexedVector2 = (function (_super) {
  32333. __extends(IndexedVector2, _super);
  32334. function IndexedVector2(original, index) {
  32335. _super.call(this, original.x, original.y);
  32336. this.index = index;
  32337. }
  32338. return IndexedVector2;
  32339. })(BABYLON.Vector2);
  32340. var PolygonPoints = (function () {
  32341. function PolygonPoints() {
  32342. this.elements = new Array();
  32343. }
  32344. PolygonPoints.prototype.add = function (originalPoints) {
  32345. var _this = this;
  32346. var result = new Array();
  32347. originalPoints.forEach(function (point) {
  32348. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32349. var newPoint = new IndexedVector2(point, _this.elements.length);
  32350. result.push(newPoint);
  32351. _this.elements.push(newPoint);
  32352. }
  32353. });
  32354. return result;
  32355. };
  32356. PolygonPoints.prototype.computeBounds = function () {
  32357. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32358. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32359. this.elements.forEach(function (point) {
  32360. // x
  32361. if (point.x < lmin.x) {
  32362. lmin.x = point.x;
  32363. }
  32364. else if (point.x > lmax.x) {
  32365. lmax.x = point.x;
  32366. }
  32367. // y
  32368. if (point.y < lmin.y) {
  32369. lmin.y = point.y;
  32370. }
  32371. else if (point.y > lmax.y) {
  32372. lmax.y = point.y;
  32373. }
  32374. });
  32375. return {
  32376. min: lmin,
  32377. max: lmax,
  32378. width: lmax.x - lmin.x,
  32379. height: lmax.y - lmin.y
  32380. };
  32381. };
  32382. return PolygonPoints;
  32383. })();
  32384. var Polygon = (function () {
  32385. function Polygon() {
  32386. }
  32387. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32388. return [
  32389. new BABYLON.Vector2(xmin, ymin),
  32390. new BABYLON.Vector2(xmax, ymin),
  32391. new BABYLON.Vector2(xmax, ymax),
  32392. new BABYLON.Vector2(xmin, ymax)
  32393. ];
  32394. };
  32395. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32396. if (cx === void 0) { cx = 0; }
  32397. if (cy === void 0) { cy = 0; }
  32398. if (numberOfSides === void 0) { numberOfSides = 32; }
  32399. var result = new Array();
  32400. var angle = 0;
  32401. var increment = (Math.PI * 2) / numberOfSides;
  32402. for (var i = 0; i < numberOfSides; i++) {
  32403. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32404. angle -= increment;
  32405. }
  32406. return result;
  32407. };
  32408. Polygon.Parse = function (input) {
  32409. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32410. var i, result = [];
  32411. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32412. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32413. }
  32414. return result;
  32415. };
  32416. Polygon.StartingAt = function (x, y) {
  32417. return BABYLON.Path2.StartingAt(x, y);
  32418. };
  32419. return Polygon;
  32420. })();
  32421. BABYLON.Polygon = Polygon;
  32422. var PolygonMeshBuilder = (function () {
  32423. function PolygonMeshBuilder(name, contours, scene) {
  32424. this._points = new PolygonPoints();
  32425. this._outlinepoints = new PolygonPoints();
  32426. this._holes = [];
  32427. if (!("poly2tri" in window)) {
  32428. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32429. }
  32430. this._name = name;
  32431. this._scene = scene;
  32432. var points;
  32433. if (contours instanceof BABYLON.Path2) {
  32434. points = contours.getPoints();
  32435. }
  32436. else {
  32437. points = contours;
  32438. }
  32439. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32440. this._outlinepoints.add(points);
  32441. }
  32442. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32443. this._swctx.addHole(this._points.add(hole));
  32444. var holepoints = new PolygonPoints();
  32445. holepoints.add(hole);
  32446. this._holes.push(holepoints);
  32447. return this;
  32448. };
  32449. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32450. var _this = this;
  32451. if (updatable === void 0) { updatable = false; }
  32452. var result = new BABYLON.Mesh(this._name, this._scene);
  32453. var normals = [];
  32454. var positions = [];
  32455. var uvs = [];
  32456. var bounds = this._points.computeBounds();
  32457. this._points.elements.forEach(function (p) {
  32458. normals.push(0, 1.0, 0);
  32459. positions.push(p.x, 0, p.y);
  32460. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32461. });
  32462. var indices = [];
  32463. this._swctx.triangulate();
  32464. this._swctx.getTriangles().forEach(function (triangle) {
  32465. triangle.getPoints().forEach(function (point) {
  32466. indices.push(point.index);
  32467. });
  32468. });
  32469. if (depth > 0) {
  32470. var positionscount = (positions.length / 3); //get the current pointcount
  32471. this._points.elements.forEach(function (p) {
  32472. normals.push(0, -1.0, 0);
  32473. positions.push(p.x, -depth, p.y);
  32474. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32475. });
  32476. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32477. var p2;
  32478. var poscounter = 0;
  32479. this._swctx.getTriangles().forEach(function (triangle) {
  32480. triangle.getPoints().forEach(function (point) {
  32481. switch (poscounter) {
  32482. case 0:
  32483. p1 = point;
  32484. break;
  32485. case 1:
  32486. p2 = point;
  32487. break;
  32488. case 2:
  32489. indices.push(point.index + positionscount);
  32490. indices.push(p2.index + positionscount);
  32491. indices.push(p1.index + positionscount);
  32492. poscounter = -1;
  32493. break;
  32494. }
  32495. poscounter++;
  32496. //indices.push((<IndexedVector2>point).index + positionscount);
  32497. });
  32498. });
  32499. //Add the sides
  32500. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32501. this._holes.forEach(function (hole) {
  32502. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32503. });
  32504. }
  32505. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32506. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32507. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32508. result.setIndices(indices);
  32509. return result;
  32510. };
  32511. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32512. var StartIndex = positions.length / 3;
  32513. var ulength = 0;
  32514. for (var i = 0; i < points.elements.length; i++) {
  32515. var p = points.elements[i];
  32516. var p1;
  32517. if ((i + 1) > points.elements.length - 1) {
  32518. p1 = points.elements[0];
  32519. }
  32520. else {
  32521. p1 = points.elements[i + 1];
  32522. }
  32523. positions.push(p.x, 0, p.y);
  32524. positions.push(p.x, -depth, p.y);
  32525. positions.push(p1.x, 0, p1.y);
  32526. positions.push(p1.x, -depth, p1.y);
  32527. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32528. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32529. var v3 = v2.subtract(v1);
  32530. var v4 = new BABYLON.Vector3(0, 1, 0);
  32531. var vn = BABYLON.Vector3.Cross(v3, v4);
  32532. vn = vn.normalize();
  32533. uvs.push(ulength / bounds.width, 0);
  32534. uvs.push(ulength / bounds.width, 1);
  32535. ulength += v3.length();
  32536. uvs.push((ulength / bounds.width), 0);
  32537. uvs.push((ulength / bounds.width), 1);
  32538. if (!flip) {
  32539. normals.push(-vn.x, -vn.y, -vn.z);
  32540. normals.push(-vn.x, -vn.y, -vn.z);
  32541. normals.push(-vn.x, -vn.y, -vn.z);
  32542. normals.push(-vn.x, -vn.y, -vn.z);
  32543. indices.push(StartIndex);
  32544. indices.push(StartIndex + 1);
  32545. indices.push(StartIndex + 2);
  32546. indices.push(StartIndex + 1);
  32547. indices.push(StartIndex + 3);
  32548. indices.push(StartIndex + 2);
  32549. }
  32550. else {
  32551. normals.push(vn.x, vn.y, vn.z);
  32552. normals.push(vn.x, vn.y, vn.z);
  32553. normals.push(vn.x, vn.y, vn.z);
  32554. normals.push(vn.x, vn.y, vn.z);
  32555. indices.push(StartIndex);
  32556. indices.push(StartIndex + 2);
  32557. indices.push(StartIndex + 1);
  32558. indices.push(StartIndex + 1);
  32559. indices.push(StartIndex + 2);
  32560. indices.push(StartIndex + 3);
  32561. }
  32562. StartIndex += 4;
  32563. }
  32564. ;
  32565. };
  32566. return PolygonMeshBuilder;
  32567. })();
  32568. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32569. })(BABYLON || (BABYLON = {}));
  32570. var BABYLON;
  32571. (function (BABYLON) {
  32572. var Octree = (function () {
  32573. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32574. if (maxDepth === void 0) { maxDepth = 2; }
  32575. this.maxDepth = maxDepth;
  32576. this.dynamicContent = new Array();
  32577. this._maxBlockCapacity = maxBlockCapacity || 64;
  32578. this._selectionContent = new BABYLON.SmartArray(1024);
  32579. this._creationFunc = creationFunc;
  32580. }
  32581. // Methods
  32582. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32583. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32584. };
  32585. Octree.prototype.addMesh = function (entry) {
  32586. for (var index = 0; index < this.blocks.length; index++) {
  32587. var block = this.blocks[index];
  32588. block.addEntry(entry);
  32589. }
  32590. };
  32591. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32592. this._selectionContent.reset();
  32593. for (var index = 0; index < this.blocks.length; index++) {
  32594. var block = this.blocks[index];
  32595. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32596. }
  32597. if (allowDuplicate) {
  32598. this._selectionContent.concat(this.dynamicContent);
  32599. }
  32600. else {
  32601. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32602. }
  32603. return this._selectionContent;
  32604. };
  32605. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32606. this._selectionContent.reset();
  32607. for (var index = 0; index < this.blocks.length; index++) {
  32608. var block = this.blocks[index];
  32609. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32610. }
  32611. if (allowDuplicate) {
  32612. this._selectionContent.concat(this.dynamicContent);
  32613. }
  32614. else {
  32615. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32616. }
  32617. return this._selectionContent;
  32618. };
  32619. Octree.prototype.intersectsRay = function (ray) {
  32620. this._selectionContent.reset();
  32621. for (var index = 0; index < this.blocks.length; index++) {
  32622. var block = this.blocks[index];
  32623. block.intersectsRay(ray, this._selectionContent);
  32624. }
  32625. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32626. return this._selectionContent;
  32627. };
  32628. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32629. target.blocks = new Array();
  32630. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32631. // Segmenting space
  32632. for (var x = 0; x < 2; x++) {
  32633. for (var y = 0; y < 2; y++) {
  32634. for (var z = 0; z < 2; z++) {
  32635. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32636. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32637. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32638. block.addEntries(entries);
  32639. target.blocks.push(block);
  32640. }
  32641. }
  32642. }
  32643. };
  32644. Octree.CreationFuncForMeshes = function (entry, block) {
  32645. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32646. block.entries.push(entry);
  32647. }
  32648. };
  32649. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32650. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32651. block.entries.push(entry);
  32652. }
  32653. };
  32654. return Octree;
  32655. })();
  32656. BABYLON.Octree = Octree;
  32657. })(BABYLON || (BABYLON = {}));
  32658. var BABYLON;
  32659. (function (BABYLON) {
  32660. var OctreeBlock = (function () {
  32661. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32662. this.entries = new Array();
  32663. this._boundingVectors = new Array();
  32664. this._capacity = capacity;
  32665. this._depth = depth;
  32666. this._maxDepth = maxDepth;
  32667. this._creationFunc = creationFunc;
  32668. this._minPoint = minPoint;
  32669. this._maxPoint = maxPoint;
  32670. this._boundingVectors.push(minPoint.clone());
  32671. this._boundingVectors.push(maxPoint.clone());
  32672. this._boundingVectors.push(minPoint.clone());
  32673. this._boundingVectors[2].x = maxPoint.x;
  32674. this._boundingVectors.push(minPoint.clone());
  32675. this._boundingVectors[3].y = maxPoint.y;
  32676. this._boundingVectors.push(minPoint.clone());
  32677. this._boundingVectors[4].z = maxPoint.z;
  32678. this._boundingVectors.push(maxPoint.clone());
  32679. this._boundingVectors[5].z = minPoint.z;
  32680. this._boundingVectors.push(maxPoint.clone());
  32681. this._boundingVectors[6].x = minPoint.x;
  32682. this._boundingVectors.push(maxPoint.clone());
  32683. this._boundingVectors[7].y = minPoint.y;
  32684. }
  32685. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32686. // Property
  32687. get: function () {
  32688. return this._capacity;
  32689. },
  32690. enumerable: true,
  32691. configurable: true
  32692. });
  32693. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32694. get: function () {
  32695. return this._minPoint;
  32696. },
  32697. enumerable: true,
  32698. configurable: true
  32699. });
  32700. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32701. get: function () {
  32702. return this._maxPoint;
  32703. },
  32704. enumerable: true,
  32705. configurable: true
  32706. });
  32707. // Methods
  32708. OctreeBlock.prototype.addEntry = function (entry) {
  32709. if (this.blocks) {
  32710. for (var index = 0; index < this.blocks.length; index++) {
  32711. var block = this.blocks[index];
  32712. block.addEntry(entry);
  32713. }
  32714. return;
  32715. }
  32716. this._creationFunc(entry, this);
  32717. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32718. this.createInnerBlocks();
  32719. }
  32720. };
  32721. OctreeBlock.prototype.addEntries = function (entries) {
  32722. for (var index = 0; index < entries.length; index++) {
  32723. var mesh = entries[index];
  32724. this.addEntry(mesh);
  32725. }
  32726. };
  32727. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32728. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32729. if (this.blocks) {
  32730. for (var index = 0; index < this.blocks.length; index++) {
  32731. var block = this.blocks[index];
  32732. block.select(frustumPlanes, selection, allowDuplicate);
  32733. }
  32734. return;
  32735. }
  32736. if (allowDuplicate) {
  32737. selection.concat(this.entries);
  32738. }
  32739. else {
  32740. selection.concatWithNoDuplicate(this.entries);
  32741. }
  32742. }
  32743. };
  32744. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32745. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32746. if (this.blocks) {
  32747. for (var index = 0; index < this.blocks.length; index++) {
  32748. var block = this.blocks[index];
  32749. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32750. }
  32751. return;
  32752. }
  32753. if (allowDuplicate) {
  32754. selection.concat(this.entries);
  32755. }
  32756. else {
  32757. selection.concatWithNoDuplicate(this.entries);
  32758. }
  32759. }
  32760. };
  32761. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32762. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32763. if (this.blocks) {
  32764. for (var index = 0; index < this.blocks.length; index++) {
  32765. var block = this.blocks[index];
  32766. block.intersectsRay(ray, selection);
  32767. }
  32768. return;
  32769. }
  32770. selection.concatWithNoDuplicate(this.entries);
  32771. }
  32772. };
  32773. OctreeBlock.prototype.createInnerBlocks = function () {
  32774. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32775. };
  32776. return OctreeBlock;
  32777. })();
  32778. BABYLON.OctreeBlock = OctreeBlock;
  32779. })(BABYLON || (BABYLON = {}));
  32780. var BABYLON;
  32781. (function (BABYLON) {
  32782. var BlurPostProcess = (function (_super) {
  32783. __extends(BlurPostProcess, _super);
  32784. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32785. var _this = this;
  32786. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32787. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32788. this.direction = direction;
  32789. this.blurWidth = blurWidth;
  32790. this.onApply = function (effect) {
  32791. effect.setFloat2("screenSize", _this.width, _this.height);
  32792. effect.setVector2("direction", _this.direction);
  32793. effect.setFloat("blurWidth", _this.blurWidth);
  32794. };
  32795. }
  32796. return BlurPostProcess;
  32797. })(BABYLON.PostProcess);
  32798. BABYLON.BlurPostProcess = BlurPostProcess;
  32799. })(BABYLON || (BABYLON = {}));
  32800. var BABYLON;
  32801. (function (BABYLON) {
  32802. var RefractionPostProcess = (function (_super) {
  32803. __extends(RefractionPostProcess, _super);
  32804. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32805. var _this = this;
  32806. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32807. this.color = color;
  32808. this.depth = depth;
  32809. this.colorLevel = colorLevel;
  32810. this.onActivate = function (cam) {
  32811. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32812. };
  32813. this.onApply = function (effect) {
  32814. effect.setColor3("baseColor", _this.color);
  32815. effect.setFloat("depth", _this.depth);
  32816. effect.setFloat("colorLevel", _this.colorLevel);
  32817. effect.setTexture("refractionSampler", _this._refRexture);
  32818. };
  32819. }
  32820. // Methods
  32821. RefractionPostProcess.prototype.dispose = function (camera) {
  32822. if (this._refRexture) {
  32823. this._refRexture.dispose();
  32824. }
  32825. _super.prototype.dispose.call(this, camera);
  32826. };
  32827. return RefractionPostProcess;
  32828. })(BABYLON.PostProcess);
  32829. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32830. })(BABYLON || (BABYLON = {}));
  32831. var BABYLON;
  32832. (function (BABYLON) {
  32833. var BlackAndWhitePostProcess = (function (_super) {
  32834. __extends(BlackAndWhitePostProcess, _super);
  32835. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32836. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32837. }
  32838. return BlackAndWhitePostProcess;
  32839. })(BABYLON.PostProcess);
  32840. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32841. })(BABYLON || (BABYLON = {}));
  32842. var BABYLON;
  32843. (function (BABYLON) {
  32844. var ConvolutionPostProcess = (function (_super) {
  32845. __extends(ConvolutionPostProcess, _super);
  32846. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32847. var _this = this;
  32848. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32849. this.kernel = kernel;
  32850. this.onApply = function (effect) {
  32851. effect.setFloat2("screenSize", _this.width, _this.height);
  32852. effect.setArray("kernel", _this.kernel);
  32853. };
  32854. }
  32855. // Statics
  32856. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32857. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32858. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32859. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32860. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32861. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32862. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32863. return ConvolutionPostProcess;
  32864. })(BABYLON.PostProcess);
  32865. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32866. })(BABYLON || (BABYLON = {}));
  32867. var BABYLON;
  32868. (function (BABYLON) {
  32869. var FilterPostProcess = (function (_super) {
  32870. __extends(FilterPostProcess, _super);
  32871. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32872. var _this = this;
  32873. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32874. this.kernelMatrix = kernelMatrix;
  32875. this.onApply = function (effect) {
  32876. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32877. };
  32878. }
  32879. return FilterPostProcess;
  32880. })(BABYLON.PostProcess);
  32881. BABYLON.FilterPostProcess = FilterPostProcess;
  32882. })(BABYLON || (BABYLON = {}));
  32883. var BABYLON;
  32884. (function (BABYLON) {
  32885. var FxaaPostProcess = (function (_super) {
  32886. __extends(FxaaPostProcess, _super);
  32887. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32888. var _this = this;
  32889. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32890. this.onSizeChanged = function () {
  32891. _this.texelWidth = 1.0 / _this.width;
  32892. _this.texelHeight = 1.0 / _this.height;
  32893. };
  32894. this.onApply = function (effect) {
  32895. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32896. };
  32897. }
  32898. return FxaaPostProcess;
  32899. })(BABYLON.PostProcess);
  32900. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32901. })(BABYLON || (BABYLON = {}));
  32902. var BABYLON;
  32903. (function (BABYLON) {
  32904. var StereoscopicInterlacePostProcess = (function (_super) {
  32905. __extends(StereoscopicInterlacePostProcess, _super);
  32906. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32907. var _this = this;
  32908. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32909. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32910. this.onSizeChanged = function () {
  32911. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32912. };
  32913. this.onApply = function (effect) {
  32914. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32915. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32916. };
  32917. }
  32918. return StereoscopicInterlacePostProcess;
  32919. })(BABYLON.PostProcess);
  32920. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32921. })(BABYLON || (BABYLON = {}));
  32922. var BABYLON;
  32923. (function (BABYLON) {
  32924. var LensFlare = (function () {
  32925. function LensFlare(size, position, color, imgUrl, system) {
  32926. this.size = size;
  32927. this.position = position;
  32928. this.dispose = function () {
  32929. if (this.texture) {
  32930. this.texture.dispose();
  32931. }
  32932. // Remove from scene
  32933. var index = this._system.lensFlares.indexOf(this);
  32934. this._system.lensFlares.splice(index, 1);
  32935. };
  32936. this.color = color || new BABYLON.Color3(1, 1, 1);
  32937. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32938. this._system = system;
  32939. system.lensFlares.push(this);
  32940. }
  32941. return LensFlare;
  32942. })();
  32943. BABYLON.LensFlare = LensFlare;
  32944. })(BABYLON || (BABYLON = {}));
  32945. var BABYLON;
  32946. (function (BABYLON) {
  32947. var LensFlareSystem = (function () {
  32948. function LensFlareSystem(name, emitter, scene) {
  32949. this.name = name;
  32950. this.lensFlares = new Array();
  32951. this.borderLimit = 300;
  32952. this.layerMask = 0x0FFFFFFF;
  32953. this._vertexDeclaration = [2];
  32954. this._vertexStrideSize = 2 * 4;
  32955. this._isEnabled = true;
  32956. this._scene = scene;
  32957. this._emitter = emitter;
  32958. scene.lensFlareSystems.push(this);
  32959. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32960. // VBO
  32961. var vertices = [];
  32962. vertices.push(1, 1);
  32963. vertices.push(-1, 1);
  32964. vertices.push(-1, -1);
  32965. vertices.push(1, -1);
  32966. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32967. // Indices
  32968. var indices = [];
  32969. indices.push(0);
  32970. indices.push(1);
  32971. indices.push(2);
  32972. indices.push(0);
  32973. indices.push(2);
  32974. indices.push(3);
  32975. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32976. // Effects
  32977. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32978. }
  32979. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32980. get: function () {
  32981. return this._isEnabled;
  32982. },
  32983. set: function (value) {
  32984. this._isEnabled = value;
  32985. },
  32986. enumerable: true,
  32987. configurable: true
  32988. });
  32989. LensFlareSystem.prototype.getScene = function () {
  32990. return this._scene;
  32991. };
  32992. LensFlareSystem.prototype.getEmitter = function () {
  32993. return this._emitter;
  32994. };
  32995. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32996. this._emitter = newEmitter;
  32997. };
  32998. LensFlareSystem.prototype.getEmitterPosition = function () {
  32999. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33000. };
  33001. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33002. var position = this.getEmitterPosition();
  33003. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33004. this._positionX = position.x;
  33005. this._positionY = position.y;
  33006. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33007. if (position.z > 0) {
  33008. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33009. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33010. return true;
  33011. }
  33012. }
  33013. return false;
  33014. };
  33015. LensFlareSystem.prototype._isVisible = function () {
  33016. if (!this._isEnabled) {
  33017. return false;
  33018. }
  33019. var emitterPosition = this.getEmitterPosition();
  33020. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33021. var distance = direction.length();
  33022. direction.normalize();
  33023. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33024. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33025. return !pickInfo.hit || pickInfo.distance > distance;
  33026. };
  33027. LensFlareSystem.prototype.render = function () {
  33028. if (!this._effect.isReady())
  33029. return false;
  33030. var engine = this._scene.getEngine();
  33031. var viewport = this._scene.activeCamera.viewport;
  33032. var globalViewport = viewport.toScreenGlobal(engine);
  33033. // Position
  33034. if (!this.computeEffectivePosition(globalViewport)) {
  33035. return false;
  33036. }
  33037. // Visibility
  33038. if (!this._isVisible()) {
  33039. return false;
  33040. }
  33041. // Intensity
  33042. var awayX;
  33043. var awayY;
  33044. if (this._positionX < this.borderLimit + globalViewport.x) {
  33045. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33046. }
  33047. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33048. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33049. }
  33050. else {
  33051. awayX = 0;
  33052. }
  33053. if (this._positionY < this.borderLimit + globalViewport.y) {
  33054. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33055. }
  33056. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33057. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33058. }
  33059. else {
  33060. awayY = 0;
  33061. }
  33062. var away = (awayX > awayY) ? awayX : awayY;
  33063. if (away > this.borderLimit) {
  33064. away = this.borderLimit;
  33065. }
  33066. var intensity = 1.0 - (away / this.borderLimit);
  33067. if (intensity < 0) {
  33068. return false;
  33069. }
  33070. if (intensity > 1.0) {
  33071. intensity = 1.0;
  33072. }
  33073. // Position
  33074. var centerX = globalViewport.x + globalViewport.width / 2;
  33075. var centerY = globalViewport.y + globalViewport.height / 2;
  33076. var distX = centerX - this._positionX;
  33077. var distY = centerY - this._positionY;
  33078. // Effects
  33079. engine.enableEffect(this._effect);
  33080. engine.setState(false);
  33081. engine.setDepthBuffer(false);
  33082. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33083. // VBOs
  33084. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33085. // Flares
  33086. for (var index = 0; index < this.lensFlares.length; index++) {
  33087. var flare = this.lensFlares[index];
  33088. var x = centerX - (distX * flare.position);
  33089. var y = centerY - (distY * flare.position);
  33090. var cw = flare.size;
  33091. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33092. var cx = 2 * (x / globalViewport.width) - 1.0;
  33093. var cy = 1.0 - 2 * (y / globalViewport.height);
  33094. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33095. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33096. // Texture
  33097. this._effect.setTexture("textureSampler", flare.texture);
  33098. // Color
  33099. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33100. // Draw order
  33101. engine.draw(true, 0, 6);
  33102. }
  33103. engine.setDepthBuffer(true);
  33104. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33105. return true;
  33106. };
  33107. LensFlareSystem.prototype.dispose = function () {
  33108. if (this._vertexBuffer) {
  33109. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33110. this._vertexBuffer = null;
  33111. }
  33112. if (this._indexBuffer) {
  33113. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33114. this._indexBuffer = null;
  33115. }
  33116. while (this.lensFlares.length) {
  33117. this.lensFlares[0].dispose();
  33118. }
  33119. // Remove from scene
  33120. var index = this._scene.lensFlareSystems.indexOf(this);
  33121. this._scene.lensFlareSystems.splice(index, 1);
  33122. };
  33123. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33124. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33125. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33126. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33127. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33128. var parsedFlare = parsedLensFlareSystem.flares[index];
  33129. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33130. }
  33131. return lensFlareSystem;
  33132. };
  33133. LensFlareSystem.prototype.serialize = function () {
  33134. var serializationObject = {};
  33135. serializationObject.emitterId = this.getEmitter().id;
  33136. serializationObject.borderLimit = this.borderLimit;
  33137. serializationObject.flares = [];
  33138. for (var index = 0; index < this.lensFlares.length; index++) {
  33139. var flare = this.lensFlares[index];
  33140. serializationObject.flares.push({
  33141. size: flare.size,
  33142. position: flare.position,
  33143. color: flare.color.asArray(),
  33144. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33145. });
  33146. }
  33147. return serializationObject;
  33148. };
  33149. return LensFlareSystem;
  33150. })();
  33151. BABYLON.LensFlareSystem = LensFlareSystem;
  33152. })(BABYLON || (BABYLON = {}));
  33153. var BABYLON;
  33154. (function (BABYLON) {
  33155. // We're mainly based on the logic defined into the FreeCamera code
  33156. var DeviceOrientationCamera = (function (_super) {
  33157. __extends(DeviceOrientationCamera, _super);
  33158. function DeviceOrientationCamera(name, position, scene) {
  33159. var _this = this;
  33160. _super.call(this, name, position, scene);
  33161. this._offsetX = null;
  33162. this._offsetY = null;
  33163. this._orientationGamma = 0;
  33164. this._orientationBeta = 0;
  33165. this._initialOrientationGamma = 0;
  33166. this._initialOrientationBeta = 0;
  33167. this.angularSensibility = 10000.0;
  33168. this.moveSensibility = 50.0;
  33169. window.addEventListener("resize", function () {
  33170. _this._initialOrientationGamma = null;
  33171. }, false);
  33172. }
  33173. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33174. var _this = this;
  33175. if (this._attachedCanvas) {
  33176. return;
  33177. }
  33178. this._attachedCanvas = canvas;
  33179. if (!this._orientationChanged) {
  33180. this._orientationChanged = function (evt) {
  33181. if (!_this._initialOrientationGamma) {
  33182. _this._initialOrientationGamma = evt.gamma;
  33183. _this._initialOrientationBeta = evt.beta;
  33184. }
  33185. _this._orientationGamma = evt.gamma;
  33186. _this._orientationBeta = evt.beta;
  33187. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33188. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33189. };
  33190. }
  33191. window.addEventListener("deviceorientation", this._orientationChanged);
  33192. };
  33193. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33194. if (this._attachedCanvas !== canvas) {
  33195. return;
  33196. }
  33197. window.removeEventListener("deviceorientation", this._orientationChanged);
  33198. this._attachedCanvas = null;
  33199. this._orientationGamma = 0;
  33200. this._orientationBeta = 0;
  33201. this._initialOrientationGamma = 0;
  33202. this._initialOrientationBeta = 0;
  33203. };
  33204. DeviceOrientationCamera.prototype._checkInputs = function () {
  33205. if (!this._offsetX) {
  33206. return;
  33207. }
  33208. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33209. var speed = this._computeLocalCameraSpeed();
  33210. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33211. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33212. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33213. _super.prototype._checkInputs.call(this);
  33214. };
  33215. return DeviceOrientationCamera;
  33216. })(BABYLON.FreeCamera);
  33217. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33218. })(BABYLON || (BABYLON = {}));
  33219. var BABYLON;
  33220. (function (BABYLON) {
  33221. var Gamepads = (function () {
  33222. function Gamepads(ongamedpadconnected) {
  33223. var _this = this;
  33224. this.babylonGamepads = [];
  33225. this.oneGamepadConnected = false;
  33226. this.isMonitoring = false;
  33227. this.gamepadEventSupported = 'GamepadEvent' in window;
  33228. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33229. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33230. 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=";
  33231. this._callbackGamepadConnected = ongamedpadconnected;
  33232. if (this.gamepadSupportAvailable) {
  33233. // Checking if the gamepad connected event is supported (like in Firefox)
  33234. if (this.gamepadEventSupported) {
  33235. window.addEventListener('gamepadconnected', function (evt) {
  33236. _this._onGamepadConnected(evt);
  33237. }, false);
  33238. window.addEventListener('gamepaddisconnected', function (evt) {
  33239. _this._onGamepadDisconnected(evt);
  33240. }, false);
  33241. }
  33242. else {
  33243. this._startMonitoringGamepads();
  33244. }
  33245. if (!this.oneGamepadConnected) {
  33246. this._insertGamepadDOMInstructions();
  33247. }
  33248. }
  33249. else {
  33250. this._insertGamepadDOMNotSupported();
  33251. }
  33252. }
  33253. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33254. Gamepads.gamepadDOMInfo = document.createElement("div");
  33255. var buttonAImage = document.createElement("img");
  33256. buttonAImage.src = this.buttonADataURL;
  33257. var spanMessage = document.createElement("span");
  33258. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33259. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33260. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33261. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33262. Gamepads.gamepadDOMInfo.style.width = "100%";
  33263. Gamepads.gamepadDOMInfo.style.height = "48px";
  33264. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33265. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33266. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33267. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33268. buttonAImage.style.position = "relative";
  33269. buttonAImage.style.bottom = "8px";
  33270. spanMessage.style.position = "relative";
  33271. spanMessage.style.fontSize = "32px";
  33272. spanMessage.style.bottom = "32px";
  33273. spanMessage.style.color = "green";
  33274. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33275. };
  33276. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33277. Gamepads.gamepadDOMInfo = document.createElement("div");
  33278. var spanMessage = document.createElement("span");
  33279. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33280. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33281. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33282. Gamepads.gamepadDOMInfo.style.width = "100%";
  33283. Gamepads.gamepadDOMInfo.style.height = "40px";
  33284. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33285. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33286. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33287. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33288. spanMessage.style.position = "relative";
  33289. spanMessage.style.fontSize = "32px";
  33290. spanMessage.style.color = "red";
  33291. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33292. };
  33293. Gamepads.prototype.dispose = function () {
  33294. if (Gamepads.gamepadDOMInfo) {
  33295. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33296. }
  33297. };
  33298. Gamepads.prototype._onGamepadConnected = function (evt) {
  33299. var newGamepad = this._addNewGamepad(evt.gamepad);
  33300. if (this._callbackGamepadConnected)
  33301. this._callbackGamepadConnected(newGamepad);
  33302. this._startMonitoringGamepads();
  33303. };
  33304. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33305. if (!this.oneGamepadConnected) {
  33306. this.oneGamepadConnected = true;
  33307. if (Gamepads.gamepadDOMInfo) {
  33308. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33309. Gamepads.gamepadDOMInfo = null;
  33310. }
  33311. }
  33312. var newGamepad;
  33313. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33314. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33315. }
  33316. else {
  33317. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33318. }
  33319. this.babylonGamepads.push(newGamepad);
  33320. return newGamepad;
  33321. };
  33322. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33323. // Remove the gamepad from the list of gamepads to monitor.
  33324. for (var i in this.babylonGamepads) {
  33325. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33326. this.babylonGamepads.splice(i, 1);
  33327. break;
  33328. }
  33329. }
  33330. // If no gamepads are left, stop the polling loop.
  33331. if (this.babylonGamepads.length == 0) {
  33332. this._stopMonitoringGamepads();
  33333. }
  33334. };
  33335. Gamepads.prototype._startMonitoringGamepads = function () {
  33336. if (!this.isMonitoring) {
  33337. this.isMonitoring = true;
  33338. this._checkGamepadsStatus();
  33339. }
  33340. };
  33341. Gamepads.prototype._stopMonitoringGamepads = function () {
  33342. this.isMonitoring = false;
  33343. };
  33344. Gamepads.prototype._checkGamepadsStatus = function () {
  33345. var _this = this;
  33346. // updating gamepad objects
  33347. this._updateGamepadObjects();
  33348. for (var i in this.babylonGamepads) {
  33349. this.babylonGamepads[i].update();
  33350. }
  33351. if (this.isMonitoring) {
  33352. if (window.requestAnimationFrame) {
  33353. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33354. }
  33355. else if (window.mozRequestAnimationFrame) {
  33356. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33357. }
  33358. else if (window.webkitRequestAnimationFrame) {
  33359. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33360. }
  33361. }
  33362. };
  33363. // This function is called only on Chrome, which does not yet support
  33364. // connection/disconnection events, but requires you to monitor
  33365. // an array for changes.
  33366. Gamepads.prototype._updateGamepadObjects = function () {
  33367. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33368. for (var i = 0; i < gamepads.length; i++) {
  33369. if (gamepads[i]) {
  33370. if (!(gamepads[i].index in this.babylonGamepads)) {
  33371. var newGamepad = this._addNewGamepad(gamepads[i]);
  33372. if (this._callbackGamepadConnected) {
  33373. this._callbackGamepadConnected(newGamepad);
  33374. }
  33375. }
  33376. else {
  33377. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33378. }
  33379. }
  33380. }
  33381. };
  33382. return Gamepads;
  33383. })();
  33384. BABYLON.Gamepads = Gamepads;
  33385. var StickValues = (function () {
  33386. function StickValues(x, y) {
  33387. this.x = x;
  33388. this.y = y;
  33389. }
  33390. return StickValues;
  33391. })();
  33392. BABYLON.StickValues = StickValues;
  33393. var Gamepad = (function () {
  33394. function Gamepad(id, index, browserGamepad) {
  33395. this.id = id;
  33396. this.index = index;
  33397. this.browserGamepad = browserGamepad;
  33398. if (this.browserGamepad.axes.length >= 2) {
  33399. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33400. }
  33401. if (this.browserGamepad.axes.length >= 4) {
  33402. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33403. }
  33404. }
  33405. Gamepad.prototype.onleftstickchanged = function (callback) {
  33406. this._onleftstickchanged = callback;
  33407. };
  33408. Gamepad.prototype.onrightstickchanged = function (callback) {
  33409. this._onrightstickchanged = callback;
  33410. };
  33411. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33412. get: function () {
  33413. return this._leftStick;
  33414. },
  33415. set: function (newValues) {
  33416. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33417. this._onleftstickchanged(newValues);
  33418. }
  33419. this._leftStick = newValues;
  33420. },
  33421. enumerable: true,
  33422. configurable: true
  33423. });
  33424. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33425. get: function () {
  33426. return this._rightStick;
  33427. },
  33428. set: function (newValues) {
  33429. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33430. this._onrightstickchanged(newValues);
  33431. }
  33432. this._rightStick = newValues;
  33433. },
  33434. enumerable: true,
  33435. configurable: true
  33436. });
  33437. Gamepad.prototype.update = function () {
  33438. if (this._leftStick) {
  33439. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33440. }
  33441. if (this._rightStick) {
  33442. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33443. }
  33444. };
  33445. return Gamepad;
  33446. })();
  33447. BABYLON.Gamepad = Gamepad;
  33448. var GenericPad = (function (_super) {
  33449. __extends(GenericPad, _super);
  33450. function GenericPad(id, index, gamepad) {
  33451. _super.call(this, id, index, gamepad);
  33452. this.id = id;
  33453. this.index = index;
  33454. this.gamepad = gamepad;
  33455. this._buttons = new Array(gamepad.buttons.length);
  33456. }
  33457. GenericPad.prototype.onbuttondown = function (callback) {
  33458. this._onbuttondown = callback;
  33459. };
  33460. GenericPad.prototype.onbuttonup = function (callback) {
  33461. this._onbuttonup = callback;
  33462. };
  33463. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33464. if (newValue !== currentValue) {
  33465. if (this._onbuttondown && newValue === 1) {
  33466. this._onbuttondown(buttonIndex);
  33467. }
  33468. if (this._onbuttonup && newValue === 0) {
  33469. this._onbuttonup(buttonIndex);
  33470. }
  33471. }
  33472. return newValue;
  33473. };
  33474. GenericPad.prototype.update = function () {
  33475. _super.prototype.update.call(this);
  33476. for (var index = 0; index < this._buttons.length; index++) {
  33477. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33478. }
  33479. };
  33480. return GenericPad;
  33481. })(Gamepad);
  33482. BABYLON.GenericPad = GenericPad;
  33483. (function (Xbox360Button) {
  33484. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33485. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33486. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33487. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33488. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33489. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33490. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33491. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33492. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33493. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33494. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33495. var Xbox360Button = BABYLON.Xbox360Button;
  33496. (function (Xbox360Dpad) {
  33497. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33498. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33499. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33500. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33501. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33502. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33503. var Xbox360Pad = (function (_super) {
  33504. __extends(Xbox360Pad, _super);
  33505. function Xbox360Pad() {
  33506. _super.apply(this, arguments);
  33507. this._leftTrigger = 0;
  33508. this._rightTrigger = 0;
  33509. this._buttonA = 0;
  33510. this._buttonB = 0;
  33511. this._buttonX = 0;
  33512. this._buttonY = 0;
  33513. this._buttonBack = 0;
  33514. this._buttonStart = 0;
  33515. this._buttonLB = 0;
  33516. this._buttonRB = 0;
  33517. this._buttonLeftStick = 0;
  33518. this._buttonRightStick = 0;
  33519. this._dPadUp = 0;
  33520. this._dPadDown = 0;
  33521. this._dPadLeft = 0;
  33522. this._dPadRight = 0;
  33523. }
  33524. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33525. this._onlefttriggerchanged = callback;
  33526. };
  33527. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33528. this._onrighttriggerchanged = callback;
  33529. };
  33530. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33531. get: function () {
  33532. return this._leftTrigger;
  33533. },
  33534. set: function (newValue) {
  33535. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33536. this._onlefttriggerchanged(newValue);
  33537. }
  33538. this._leftTrigger = newValue;
  33539. },
  33540. enumerable: true,
  33541. configurable: true
  33542. });
  33543. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33544. get: function () {
  33545. return this._rightTrigger;
  33546. },
  33547. set: function (newValue) {
  33548. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33549. this._onrighttriggerchanged(newValue);
  33550. }
  33551. this._rightTrigger = newValue;
  33552. },
  33553. enumerable: true,
  33554. configurable: true
  33555. });
  33556. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33557. this._onbuttondown = callback;
  33558. };
  33559. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33560. this._onbuttonup = callback;
  33561. };
  33562. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33563. this._ondpaddown = callback;
  33564. };
  33565. Xbox360Pad.prototype.ondpadup = function (callback) {
  33566. this._ondpadup = callback;
  33567. };
  33568. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33569. if (newValue !== currentValue) {
  33570. if (this._onbuttondown && newValue === 1) {
  33571. this._onbuttondown(buttonType);
  33572. }
  33573. if (this._onbuttonup && newValue === 0) {
  33574. this._onbuttonup(buttonType);
  33575. }
  33576. }
  33577. return newValue;
  33578. };
  33579. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33580. if (newValue !== currentValue) {
  33581. if (this._ondpaddown && newValue === 1) {
  33582. this._ondpaddown(buttonType);
  33583. }
  33584. if (this._ondpadup && newValue === 0) {
  33585. this._ondpadup(buttonType);
  33586. }
  33587. }
  33588. return newValue;
  33589. };
  33590. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33591. get: function () {
  33592. return this._buttonA;
  33593. },
  33594. set: function (value) {
  33595. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33596. },
  33597. enumerable: true,
  33598. configurable: true
  33599. });
  33600. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33601. get: function () {
  33602. return this._buttonB;
  33603. },
  33604. set: function (value) {
  33605. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33606. },
  33607. enumerable: true,
  33608. configurable: true
  33609. });
  33610. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33611. get: function () {
  33612. return this._buttonX;
  33613. },
  33614. set: function (value) {
  33615. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33616. },
  33617. enumerable: true,
  33618. configurable: true
  33619. });
  33620. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33621. get: function () {
  33622. return this._buttonY;
  33623. },
  33624. set: function (value) {
  33625. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33626. },
  33627. enumerable: true,
  33628. configurable: true
  33629. });
  33630. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33631. get: function () {
  33632. return this._buttonStart;
  33633. },
  33634. set: function (value) {
  33635. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33636. },
  33637. enumerable: true,
  33638. configurable: true
  33639. });
  33640. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33641. get: function () {
  33642. return this._buttonBack;
  33643. },
  33644. set: function (value) {
  33645. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33646. },
  33647. enumerable: true,
  33648. configurable: true
  33649. });
  33650. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33651. get: function () {
  33652. return this._buttonLB;
  33653. },
  33654. set: function (value) {
  33655. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33656. },
  33657. enumerable: true,
  33658. configurable: true
  33659. });
  33660. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33661. get: function () {
  33662. return this._buttonRB;
  33663. },
  33664. set: function (value) {
  33665. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33666. },
  33667. enumerable: true,
  33668. configurable: true
  33669. });
  33670. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33671. get: function () {
  33672. return this._buttonLeftStick;
  33673. },
  33674. set: function (value) {
  33675. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33676. },
  33677. enumerable: true,
  33678. configurable: true
  33679. });
  33680. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33681. get: function () {
  33682. return this._buttonRightStick;
  33683. },
  33684. set: function (value) {
  33685. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33686. },
  33687. enumerable: true,
  33688. configurable: true
  33689. });
  33690. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33691. get: function () {
  33692. return this._dPadUp;
  33693. },
  33694. set: function (value) {
  33695. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33696. },
  33697. enumerable: true,
  33698. configurable: true
  33699. });
  33700. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33701. get: function () {
  33702. return this._dPadDown;
  33703. },
  33704. set: function (value) {
  33705. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33706. },
  33707. enumerable: true,
  33708. configurable: true
  33709. });
  33710. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33711. get: function () {
  33712. return this._dPadLeft;
  33713. },
  33714. set: function (value) {
  33715. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33716. },
  33717. enumerable: true,
  33718. configurable: true
  33719. });
  33720. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33721. get: function () {
  33722. return this._dPadRight;
  33723. },
  33724. set: function (value) {
  33725. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33726. },
  33727. enumerable: true,
  33728. configurable: true
  33729. });
  33730. Xbox360Pad.prototype.update = function () {
  33731. _super.prototype.update.call(this);
  33732. this.buttonA = this.browserGamepad.buttons[0].value;
  33733. this.buttonB = this.browserGamepad.buttons[1].value;
  33734. this.buttonX = this.browserGamepad.buttons[2].value;
  33735. this.buttonY = this.browserGamepad.buttons[3].value;
  33736. this.buttonLB = this.browserGamepad.buttons[4].value;
  33737. this.buttonRB = this.browserGamepad.buttons[5].value;
  33738. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33739. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33740. this.buttonBack = this.browserGamepad.buttons[8].value;
  33741. this.buttonStart = this.browserGamepad.buttons[9].value;
  33742. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33743. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33744. this.dPadUp = this.browserGamepad.buttons[12].value;
  33745. this.dPadDown = this.browserGamepad.buttons[13].value;
  33746. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33747. this.dPadRight = this.browserGamepad.buttons[15].value;
  33748. };
  33749. return Xbox360Pad;
  33750. })(Gamepad);
  33751. BABYLON.Xbox360Pad = Xbox360Pad;
  33752. })(BABYLON || (BABYLON = {}));
  33753. var BABYLON;
  33754. (function (BABYLON) {
  33755. // We're mainly based on the logic defined into the FreeCamera code
  33756. var GamepadCamera = (function (_super) {
  33757. __extends(GamepadCamera, _super);
  33758. function GamepadCamera(name, position, scene) {
  33759. var _this = this;
  33760. _super.call(this, name, position, scene);
  33761. this.angularSensibility = 200;
  33762. this.moveSensibility = 75;
  33763. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33764. }
  33765. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33766. // Only the first gamepad can control the camera
  33767. if (gamepad.index === 0) {
  33768. this._gamepad = gamepad;
  33769. }
  33770. };
  33771. GamepadCamera.prototype._checkInputs = function () {
  33772. if (this._gamepad) {
  33773. var LSValues = this._gamepad.leftStick;
  33774. var normalizedLX = LSValues.x / this.moveSensibility;
  33775. var normalizedLY = LSValues.y / this.moveSensibility;
  33776. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33777. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33778. var RSValues = this._gamepad.rightStick;
  33779. var normalizedRX = RSValues.x / this.angularSensibility;
  33780. var normalizedRY = RSValues.y / this.angularSensibility;
  33781. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33782. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33783. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33784. var speed = this._computeLocalCameraSpeed() * 50.0;
  33785. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33786. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33787. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33788. }
  33789. _super.prototype._checkInputs.call(this);
  33790. };
  33791. GamepadCamera.prototype.dispose = function () {
  33792. this._gamepads.dispose();
  33793. _super.prototype.dispose.call(this);
  33794. };
  33795. return GamepadCamera;
  33796. })(BABYLON.FreeCamera);
  33797. BABYLON.GamepadCamera = GamepadCamera;
  33798. })(BABYLON || (BABYLON = {}));
  33799. var BABYLON;
  33800. (function (BABYLON) {
  33801. var Analyser = (function () {
  33802. function Analyser(scene) {
  33803. this.SMOOTHING = 0.75;
  33804. this.FFT_SIZE = 512;
  33805. this.BARGRAPHAMPLITUDE = 256;
  33806. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33807. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33808. this._scene = scene;
  33809. this._audioEngine = BABYLON.Engine.audioEngine;
  33810. if (this._audioEngine.canUseWebAudio) {
  33811. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33812. this._webAudioAnalyser.minDecibels = -140;
  33813. this._webAudioAnalyser.maxDecibels = 0;
  33814. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33815. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33816. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33817. }
  33818. }
  33819. Analyser.prototype.getFrequencyBinCount = function () {
  33820. if (this._audioEngine.canUseWebAudio) {
  33821. return this._webAudioAnalyser.frequencyBinCount;
  33822. }
  33823. else {
  33824. return 0;
  33825. }
  33826. };
  33827. Analyser.prototype.getByteFrequencyData = function () {
  33828. if (this._audioEngine.canUseWebAudio) {
  33829. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33830. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33831. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33832. }
  33833. return this._byteFreqs;
  33834. };
  33835. Analyser.prototype.getByteTimeDomainData = function () {
  33836. if (this._audioEngine.canUseWebAudio) {
  33837. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33838. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33839. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33840. }
  33841. return this._byteTime;
  33842. };
  33843. Analyser.prototype.getFloatFrequencyData = function () {
  33844. if (this._audioEngine.canUseWebAudio) {
  33845. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33846. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33847. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33848. }
  33849. return this._floatFreqs;
  33850. };
  33851. Analyser.prototype.drawDebugCanvas = function () {
  33852. var _this = this;
  33853. if (this._audioEngine.canUseWebAudio) {
  33854. if (!this._debugCanvas) {
  33855. this._debugCanvas = document.createElement("canvas");
  33856. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33857. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33858. this._debugCanvas.style.position = "absolute";
  33859. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33860. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33861. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33862. document.body.appendChild(this._debugCanvas);
  33863. this._registerFunc = function () {
  33864. _this.drawDebugCanvas();
  33865. };
  33866. this._scene.registerBeforeRender(this._registerFunc);
  33867. }
  33868. if (this._registerFunc) {
  33869. var workingArray = this.getByteFrequencyData();
  33870. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33871. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33872. // Draw the frequency domain chart.
  33873. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33874. var value = workingArray[i];
  33875. var percent = value / this.BARGRAPHAMPLITUDE;
  33876. var height = this.DEBUGCANVASSIZE.height * percent;
  33877. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33878. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33879. var hue = i / this.getFrequencyBinCount() * 360;
  33880. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33881. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33882. }
  33883. }
  33884. }
  33885. };
  33886. Analyser.prototype.stopDebugCanvas = function () {
  33887. if (this._debugCanvas) {
  33888. this._scene.unregisterBeforeRender(this._registerFunc);
  33889. this._registerFunc = null;
  33890. document.body.removeChild(this._debugCanvas);
  33891. this._debugCanvas = null;
  33892. this._debugCanvasContext = null;
  33893. }
  33894. };
  33895. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33896. if (this._audioEngine.canUseWebAudio) {
  33897. inputAudioNode.connect(this._webAudioAnalyser);
  33898. this._webAudioAnalyser.connect(outputAudioNode);
  33899. }
  33900. };
  33901. Analyser.prototype.dispose = function () {
  33902. if (this._audioEngine.canUseWebAudio) {
  33903. this._webAudioAnalyser.disconnect();
  33904. }
  33905. };
  33906. return Analyser;
  33907. })();
  33908. BABYLON.Analyser = Analyser;
  33909. })(BABYLON || (BABYLON = {}));
  33910. var BABYLON;
  33911. (function (BABYLON) {
  33912. var AudioEngine = (function () {
  33913. function AudioEngine() {
  33914. this._audioContext = null;
  33915. this._audioContextInitialized = false;
  33916. this.canUseWebAudio = false;
  33917. this.WarnedWebAudioUnsupported = false;
  33918. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33919. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33920. this.canUseWebAudio = true;
  33921. }
  33922. }
  33923. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33924. get: function () {
  33925. if (!this._audioContextInitialized) {
  33926. this._initializeAudioContext();
  33927. }
  33928. return this._audioContext;
  33929. },
  33930. enumerable: true,
  33931. configurable: true
  33932. });
  33933. AudioEngine.prototype._initializeAudioContext = function () {
  33934. try {
  33935. if (this.canUseWebAudio) {
  33936. this._audioContext = new AudioContext();
  33937. // create a global volume gain node
  33938. this.masterGain = this._audioContext.createGain();
  33939. this.masterGain.gain.value = 1;
  33940. this.masterGain.connect(this._audioContext.destination);
  33941. this._audioContextInitialized = true;
  33942. }
  33943. }
  33944. catch (e) {
  33945. this.canUseWebAudio = false;
  33946. BABYLON.Tools.Error("Web Audio: " + e.message);
  33947. }
  33948. };
  33949. AudioEngine.prototype.dispose = function () {
  33950. if (this.canUseWebAudio && this._audioContextInitialized) {
  33951. if (this._connectedAnalyser) {
  33952. this._connectedAnalyser.stopDebugCanvas();
  33953. this._connectedAnalyser.dispose();
  33954. this.masterGain.disconnect();
  33955. this.masterGain.connect(this._audioContext.destination);
  33956. this._connectedAnalyser = null;
  33957. }
  33958. this.masterGain.gain.value = 1;
  33959. }
  33960. this.WarnedWebAudioUnsupported = false;
  33961. };
  33962. AudioEngine.prototype.getGlobalVolume = function () {
  33963. if (this.canUseWebAudio && this._audioContextInitialized) {
  33964. return this.masterGain.gain.value;
  33965. }
  33966. else {
  33967. return -1;
  33968. }
  33969. };
  33970. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33971. if (this.canUseWebAudio && this._audioContextInitialized) {
  33972. this.masterGain.gain.value = newVolume;
  33973. }
  33974. };
  33975. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33976. if (this._connectedAnalyser) {
  33977. this._connectedAnalyser.stopDebugCanvas();
  33978. }
  33979. if (this.canUseWebAudio && this._audioContextInitialized) {
  33980. this._connectedAnalyser = analyser;
  33981. this.masterGain.disconnect();
  33982. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33983. }
  33984. };
  33985. return AudioEngine;
  33986. })();
  33987. BABYLON.AudioEngine = AudioEngine;
  33988. })(BABYLON || (BABYLON = {}));
  33989. var BABYLON;
  33990. (function (BABYLON) {
  33991. var Sound = (function () {
  33992. /**
  33993. * Create a sound and attach it to a scene
  33994. * @param name Name of your sound
  33995. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33996. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33997. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33998. */
  33999. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34000. var _this = this;
  34001. this.autoplay = false;
  34002. this.loop = false;
  34003. this.useCustomAttenuation = false;
  34004. this.spatialSound = false;
  34005. this.refDistance = 1;
  34006. this.rolloffFactor = 1;
  34007. this.maxDistance = 100;
  34008. this.distanceModel = "linear";
  34009. this._panningModel = "equalpower";
  34010. this._playbackRate = 1;
  34011. this._streaming = false;
  34012. this._startTime = 0;
  34013. this._startOffset = 0;
  34014. this._position = BABYLON.Vector3.Zero();
  34015. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34016. this._volume = 1;
  34017. this._isLoaded = false;
  34018. this._isReadyToPlay = false;
  34019. this.isPlaying = false;
  34020. this.isPaused = false;
  34021. this._isDirectional = false;
  34022. // Used if you'd like to create a directional sound.
  34023. // If not set, the sound will be omnidirectional
  34024. this._coneInnerAngle = 360;
  34025. this._coneOuterAngle = 360;
  34026. this._coneOuterGain = 0;
  34027. this._isOutputConnected = false;
  34028. this.name = name;
  34029. this._scene = scene;
  34030. this._readyToPlayCallback = readyToPlayCallback;
  34031. // Default custom attenuation function is a linear attenuation
  34032. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34033. if (currentDistance < maxDistance) {
  34034. return currentVolume * (1 - currentDistance / maxDistance);
  34035. }
  34036. else {
  34037. return 0;
  34038. }
  34039. };
  34040. if (options) {
  34041. this.autoplay = options.autoplay || false;
  34042. this.loop = options.loop || false;
  34043. // if volume === 0, we need another way to check this option
  34044. if (options.volume !== undefined) {
  34045. this._volume = options.volume;
  34046. }
  34047. this.spatialSound = options.spatialSound || false;
  34048. this.maxDistance = options.maxDistance || 100;
  34049. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34050. this.rolloffFactor = options.rolloffFactor || 1;
  34051. this.refDistance = options.refDistance || 1;
  34052. this.distanceModel = options.distanceModel || "linear";
  34053. this._playbackRate = options.playbackRate || 1;
  34054. this._streaming = options.streaming || false;
  34055. }
  34056. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34057. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34058. this._soundGain.gain.value = this._volume;
  34059. this._inputAudioNode = this._soundGain;
  34060. this._ouputAudioNode = this._soundGain;
  34061. if (this.spatialSound) {
  34062. this._createSpatialParameters();
  34063. }
  34064. this._scene.mainSoundTrack.AddSound(this);
  34065. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34066. if (urlOrArrayBuffer) {
  34067. // If it's an URL
  34068. if (typeof (urlOrArrayBuffer) === "string") {
  34069. // Loading sound using XHR2
  34070. if (!this._streaming) {
  34071. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  34072. }
  34073. else {
  34074. this._htmlAudioElement = new Audio();
  34075. this._htmlAudioElement.src = urlOrArrayBuffer;
  34076. this._htmlAudioElement.controls = false;
  34077. this._htmlAudioElement.loop = this.loop;
  34078. this._htmlAudioElement.crossOrigin = "anonymous";
  34079. this._isReadyToPlay = true;
  34080. document.body.appendChild(this._htmlAudioElement);
  34081. // Simulating a ready to play event for consistent behavior with non streamed audio source
  34082. if (this._readyToPlayCallback) {
  34083. window.setTimeout(function () {
  34084. _this._readyToPlayCallback();
  34085. }, 1000);
  34086. }
  34087. if (this.autoplay) {
  34088. this.play();
  34089. }
  34090. }
  34091. }
  34092. else {
  34093. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34094. if (urlOrArrayBuffer.byteLength > 0) {
  34095. this._soundLoaded(urlOrArrayBuffer);
  34096. }
  34097. }
  34098. else {
  34099. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34100. }
  34101. }
  34102. }
  34103. }
  34104. else {
  34105. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34106. this._scene.mainSoundTrack.AddSound(this);
  34107. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34108. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34109. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34110. }
  34111. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34112. if (this._readyToPlayCallback) {
  34113. window.setTimeout(function () {
  34114. _this._readyToPlayCallback();
  34115. }, 1000);
  34116. }
  34117. }
  34118. }
  34119. Sound.prototype.dispose = function () {
  34120. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34121. if (this.isPlaying) {
  34122. this.stop();
  34123. }
  34124. this._isReadyToPlay = false;
  34125. if (this.soundTrackId === -1) {
  34126. this._scene.mainSoundTrack.RemoveSound(this);
  34127. }
  34128. else {
  34129. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34130. }
  34131. if (this._soundGain) {
  34132. this._soundGain.disconnect();
  34133. this._soundGain = null;
  34134. }
  34135. if (this._soundPanner) {
  34136. this._soundPanner.disconnect();
  34137. this._soundPanner = null;
  34138. }
  34139. if (this._soundSource) {
  34140. this._soundSource.disconnect();
  34141. this._soundSource = null;
  34142. }
  34143. this._audioBuffer = null;
  34144. if (this._htmlAudioElement) {
  34145. this._htmlAudioElement.pause();
  34146. this._htmlAudioElement.src = "";
  34147. document.body.removeChild(this._htmlAudioElement);
  34148. }
  34149. if (this._connectedMesh) {
  34150. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34151. this._connectedMesh = null;
  34152. }
  34153. }
  34154. };
  34155. Sound.prototype._soundLoaded = function (audioData) {
  34156. var _this = this;
  34157. this._isLoaded = true;
  34158. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34159. _this._audioBuffer = buffer;
  34160. _this._isReadyToPlay = true;
  34161. if (_this.autoplay) {
  34162. _this.play();
  34163. }
  34164. if (_this._readyToPlayCallback) {
  34165. _this._readyToPlayCallback();
  34166. }
  34167. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34168. };
  34169. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34170. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34171. this._audioBuffer = audioBuffer;
  34172. this._isReadyToPlay = true;
  34173. }
  34174. };
  34175. Sound.prototype.updateOptions = function (options) {
  34176. if (options) {
  34177. this.loop = options.loop || this.loop;
  34178. this.maxDistance = options.maxDistance || this.maxDistance;
  34179. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34180. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34181. this.refDistance = options.refDistance || this.refDistance;
  34182. this.distanceModel = options.distanceModel || this.distanceModel;
  34183. this._playbackRate = options.playbackRate || this._playbackRate;
  34184. this._updateSpatialParameters();
  34185. if (this.isPlaying) {
  34186. if (this._streaming) {
  34187. this._htmlAudioElement.playbackRate = this._playbackRate;
  34188. }
  34189. else {
  34190. this._soundSource.playbackRate.value = this._playbackRate;
  34191. }
  34192. }
  34193. }
  34194. };
  34195. Sound.prototype._createSpatialParameters = function () {
  34196. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34197. if (this._scene.headphone) {
  34198. this._panningModel = "HRTF";
  34199. }
  34200. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34201. this._updateSpatialParameters();
  34202. this._soundPanner.connect(this._ouputAudioNode);
  34203. this._inputAudioNode = this._soundPanner;
  34204. }
  34205. };
  34206. Sound.prototype._updateSpatialParameters = function () {
  34207. if (this.spatialSound) {
  34208. if (this.useCustomAttenuation) {
  34209. // Tricks to disable in a way embedded Web Audio attenuation
  34210. this._soundPanner.distanceModel = "linear";
  34211. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34212. this._soundPanner.refDistance = 1;
  34213. this._soundPanner.rolloffFactor = 1;
  34214. this._soundPanner.panningModel = this._panningModel;
  34215. }
  34216. else {
  34217. this._soundPanner.distanceModel = this.distanceModel;
  34218. this._soundPanner.maxDistance = this.maxDistance;
  34219. this._soundPanner.refDistance = this.refDistance;
  34220. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34221. this._soundPanner.panningModel = this._panningModel;
  34222. }
  34223. }
  34224. };
  34225. Sound.prototype.switchPanningModelToHRTF = function () {
  34226. this._panningModel = "HRTF";
  34227. this._switchPanningModel();
  34228. };
  34229. Sound.prototype.switchPanningModelToEqualPower = function () {
  34230. this._panningModel = "equalpower";
  34231. this._switchPanningModel();
  34232. };
  34233. Sound.prototype._switchPanningModel = function () {
  34234. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34235. this._soundPanner.panningModel = this._panningModel;
  34236. }
  34237. };
  34238. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34239. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34240. if (this._isOutputConnected) {
  34241. this._ouputAudioNode.disconnect();
  34242. }
  34243. this._ouputAudioNode.connect(soundTrackAudioNode);
  34244. this._isOutputConnected = true;
  34245. }
  34246. };
  34247. /**
  34248. * Transform this sound into a directional source
  34249. * @param coneInnerAngle Size of the inner cone in degree
  34250. * @param coneOuterAngle Size of the outer cone in degree
  34251. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34252. */
  34253. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34254. if (coneOuterAngle < coneInnerAngle) {
  34255. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34256. return;
  34257. }
  34258. this._coneInnerAngle = coneInnerAngle;
  34259. this._coneOuterAngle = coneOuterAngle;
  34260. this._coneOuterGain = coneOuterGain;
  34261. this._isDirectional = true;
  34262. if (this.isPlaying && this.loop) {
  34263. this.stop();
  34264. this.play();
  34265. }
  34266. };
  34267. Sound.prototype.setPosition = function (newPosition) {
  34268. this._position = newPosition;
  34269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34270. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34271. }
  34272. };
  34273. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34274. this._localDirection = newLocalDirection;
  34275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34276. this._updateDirection();
  34277. }
  34278. };
  34279. Sound.prototype._updateDirection = function () {
  34280. var mat = this._connectedMesh.getWorldMatrix();
  34281. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34282. direction.normalize();
  34283. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34284. };
  34285. Sound.prototype.updateDistanceFromListener = function () {
  34286. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34287. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34288. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34289. }
  34290. };
  34291. Sound.prototype.setAttenuationFunction = function (callback) {
  34292. this._customAttenuationFunction = callback;
  34293. };
  34294. /**
  34295. * Play the sound
  34296. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34297. */
  34298. Sound.prototype.play = function (time) {
  34299. var _this = this;
  34300. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34301. try {
  34302. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34303. if (!this._soundSource || !this._streamingSource) {
  34304. if (this.spatialSound) {
  34305. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34306. if (this._isDirectional) {
  34307. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34308. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34309. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34310. if (this._connectedMesh) {
  34311. this._updateDirection();
  34312. }
  34313. else {
  34314. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34315. }
  34316. }
  34317. }
  34318. }
  34319. if (this._streaming) {
  34320. if (!this._streamingSource) {
  34321. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34322. this._htmlAudioElement.onended = function () { _this._onended(); };
  34323. this._htmlAudioElement.playbackRate = this._playbackRate;
  34324. }
  34325. this._streamingSource.disconnect();
  34326. this._streamingSource.connect(this._inputAudioNode);
  34327. this._htmlAudioElement.play();
  34328. }
  34329. else {
  34330. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34331. this._soundSource.buffer = this._audioBuffer;
  34332. this._soundSource.connect(this._inputAudioNode);
  34333. this._soundSource.loop = this.loop;
  34334. this._soundSource.playbackRate.value = this._playbackRate;
  34335. this._soundSource.onended = function () { _this._onended(); };
  34336. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34337. }
  34338. this._startTime = startTime;
  34339. this.isPlaying = true;
  34340. this.isPaused = false;
  34341. }
  34342. catch (ex) {
  34343. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34344. }
  34345. }
  34346. };
  34347. Sound.prototype._onended = function () {
  34348. this.isPlaying = false;
  34349. if (this.onended) {
  34350. this.onended();
  34351. }
  34352. };
  34353. /**
  34354. * Stop the sound
  34355. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34356. */
  34357. Sound.prototype.stop = function (time) {
  34358. if (this.isPlaying) {
  34359. if (this._streaming) {
  34360. this._htmlAudioElement.pause();
  34361. // Test needed for Firefox or it will generate an Invalid State Error
  34362. if (this._htmlAudioElement.currentTime > 0) {
  34363. this._htmlAudioElement.currentTime = 0;
  34364. }
  34365. }
  34366. else {
  34367. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34368. this._soundSource.stop(stopTime);
  34369. }
  34370. this.isPlaying = false;
  34371. }
  34372. };
  34373. Sound.prototype.pause = function () {
  34374. if (this.isPlaying) {
  34375. if (this._streaming) {
  34376. this._htmlAudioElement.pause();
  34377. }
  34378. else {
  34379. this.stop(0);
  34380. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34381. }
  34382. this.isPaused = true;
  34383. }
  34384. };
  34385. Sound.prototype.setVolume = function (newVolume, time) {
  34386. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34387. if (time) {
  34388. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34389. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34390. }
  34391. else {
  34392. this._soundGain.gain.value = newVolume;
  34393. }
  34394. }
  34395. this._volume = newVolume;
  34396. };
  34397. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34398. this._playbackRate = newPlaybackRate;
  34399. if (this.isPlaying) {
  34400. if (this._streaming) {
  34401. this._htmlAudioElement.playbackRate = this._playbackRate;
  34402. }
  34403. else {
  34404. this._soundSource.playbackRate.value = this._playbackRate;
  34405. }
  34406. }
  34407. };
  34408. Sound.prototype.getVolume = function () {
  34409. return this._volume;
  34410. };
  34411. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34412. var _this = this;
  34413. if (this._connectedMesh) {
  34414. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34415. this._registerFunc = null;
  34416. }
  34417. this._connectedMesh = meshToConnectTo;
  34418. if (!this.spatialSound) {
  34419. this.spatialSound = true;
  34420. this._createSpatialParameters();
  34421. if (this.isPlaying && this.loop) {
  34422. this.stop();
  34423. this.play();
  34424. }
  34425. }
  34426. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34427. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34428. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34429. };
  34430. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34431. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34432. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34433. this._updateDirection();
  34434. }
  34435. };
  34436. Sound.prototype.clone = function () {
  34437. var _this = this;
  34438. if (!this._streaming) {
  34439. var setBufferAndRun = function () {
  34440. if (_this._isReadyToPlay) {
  34441. clonedSound._audioBuffer = _this.getAudioBuffer();
  34442. clonedSound._isReadyToPlay = true;
  34443. if (clonedSound.autoplay) {
  34444. clonedSound.play();
  34445. }
  34446. }
  34447. else {
  34448. window.setTimeout(setBufferAndRun, 300);
  34449. }
  34450. };
  34451. var currentOptions = {
  34452. autoplay: this.autoplay, loop: this.loop,
  34453. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34454. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34455. refDistance: this.refDistance, distanceModel: this.distanceModel
  34456. };
  34457. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34458. if (this.useCustomAttenuation) {
  34459. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34460. }
  34461. clonedSound.setPosition(this._position);
  34462. clonedSound.setPlaybackRate(this._playbackRate);
  34463. setBufferAndRun();
  34464. return clonedSound;
  34465. }
  34466. else {
  34467. return null;
  34468. }
  34469. };
  34470. Sound.prototype.getAudioBuffer = function () {
  34471. return this._audioBuffer;
  34472. };
  34473. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34474. var soundName = parsedSound.name;
  34475. var soundUrl;
  34476. if (parsedSound.url) {
  34477. soundUrl = rootUrl + parsedSound.url;
  34478. }
  34479. else {
  34480. soundUrl = rootUrl + soundName;
  34481. }
  34482. var options = {
  34483. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34484. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34485. rolloffFactor: parsedSound.rolloffFactor,
  34486. refDistance: parsedSound.refDistance,
  34487. distanceModel: parsedSound.distanceModel,
  34488. playbackRate: parsedSound.playbackRate
  34489. };
  34490. var newSound;
  34491. if (!sourceSound) {
  34492. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34493. scene._addPendingData(newSound);
  34494. }
  34495. else {
  34496. var setBufferAndRun = function () {
  34497. if (sourceSound._isReadyToPlay) {
  34498. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34499. newSound._isReadyToPlay = true;
  34500. if (newSound.autoplay) {
  34501. newSound.play();
  34502. }
  34503. }
  34504. else {
  34505. window.setTimeout(setBufferAndRun, 300);
  34506. }
  34507. };
  34508. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34509. setBufferAndRun();
  34510. }
  34511. if (parsedSound.position) {
  34512. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34513. newSound.setPosition(soundPosition);
  34514. }
  34515. if (parsedSound.isDirectional) {
  34516. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34517. if (parsedSound.localDirectionToMesh) {
  34518. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34519. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34520. }
  34521. }
  34522. if (parsedSound.connectedMeshId) {
  34523. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34524. if (connectedMesh) {
  34525. newSound.attachToMesh(connectedMesh);
  34526. }
  34527. }
  34528. return newSound;
  34529. };
  34530. return Sound;
  34531. })();
  34532. BABYLON.Sound = Sound;
  34533. })(BABYLON || (BABYLON = {}));
  34534. var BABYLON;
  34535. (function (BABYLON) {
  34536. var SoundTrack = (function () {
  34537. function SoundTrack(scene, options) {
  34538. this.id = -1;
  34539. this._isMainTrack = false;
  34540. this._isInitialized = false;
  34541. this._scene = scene;
  34542. this.soundCollection = new Array();
  34543. this._options = options;
  34544. if (!this._isMainTrack) {
  34545. this._scene.soundTracks.push(this);
  34546. this.id = this._scene.soundTracks.length - 1;
  34547. }
  34548. }
  34549. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34550. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34551. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34552. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34553. if (this._options) {
  34554. if (this._options.volume) {
  34555. this._outputAudioNode.gain.value = this._options.volume;
  34556. }
  34557. if (this._options.mainTrack) {
  34558. this._isMainTrack = this._options.mainTrack;
  34559. }
  34560. }
  34561. this._isInitialized = true;
  34562. }
  34563. };
  34564. SoundTrack.prototype.dispose = function () {
  34565. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34566. if (this._connectedAnalyser) {
  34567. this._connectedAnalyser.stopDebugCanvas();
  34568. }
  34569. while (this.soundCollection.length) {
  34570. this.soundCollection[0].dispose();
  34571. }
  34572. if (this._outputAudioNode) {
  34573. this._outputAudioNode.disconnect();
  34574. }
  34575. this._outputAudioNode = null;
  34576. }
  34577. };
  34578. SoundTrack.prototype.AddSound = function (sound) {
  34579. if (!this._isInitialized) {
  34580. this._initializeSoundTrackAudioGraph();
  34581. }
  34582. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34583. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34584. }
  34585. if (sound.soundTrackId) {
  34586. if (sound.soundTrackId === -1) {
  34587. this._scene.mainSoundTrack.RemoveSound(sound);
  34588. }
  34589. else {
  34590. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34591. }
  34592. }
  34593. this.soundCollection.push(sound);
  34594. sound.soundTrackId = this.id;
  34595. };
  34596. SoundTrack.prototype.RemoveSound = function (sound) {
  34597. var index = this.soundCollection.indexOf(sound);
  34598. if (index !== -1) {
  34599. this.soundCollection.splice(index, 1);
  34600. }
  34601. };
  34602. SoundTrack.prototype.setVolume = function (newVolume) {
  34603. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34604. this._outputAudioNode.gain.value = newVolume;
  34605. }
  34606. };
  34607. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34608. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34609. for (var i = 0; i < this.soundCollection.length; i++) {
  34610. this.soundCollection[i].switchPanningModelToHRTF();
  34611. }
  34612. }
  34613. };
  34614. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34615. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34616. for (var i = 0; i < this.soundCollection.length; i++) {
  34617. this.soundCollection[i].switchPanningModelToEqualPower();
  34618. }
  34619. }
  34620. };
  34621. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34622. if (this._connectedAnalyser) {
  34623. this._connectedAnalyser.stopDebugCanvas();
  34624. }
  34625. this._connectedAnalyser = analyser;
  34626. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34627. this._outputAudioNode.disconnect();
  34628. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34629. }
  34630. };
  34631. return SoundTrack;
  34632. })();
  34633. BABYLON.SoundTrack = SoundTrack;
  34634. })(BABYLON || (BABYLON = {}));
  34635. var BABYLON;
  34636. (function (BABYLON) {
  34637. var DepthRenderer = (function () {
  34638. function DepthRenderer(scene, type) {
  34639. var _this = this;
  34640. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34641. this._viewMatrix = BABYLON.Matrix.Zero();
  34642. this._projectionMatrix = BABYLON.Matrix.Zero();
  34643. this._transformMatrix = BABYLON.Matrix.Zero();
  34644. this._worldViewProjection = BABYLON.Matrix.Zero();
  34645. this._scene = scene;
  34646. var engine = scene.getEngine();
  34647. // Render target
  34648. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34649. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34650. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34651. this._depthMap.refreshRate = 1;
  34652. this._depthMap.renderParticles = false;
  34653. this._depthMap.renderList = null;
  34654. // set default depth value to 1.0 (far away)
  34655. this._depthMap.onClear = function (engine) {
  34656. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34657. };
  34658. // Custom render function
  34659. var renderSubMesh = function (subMesh) {
  34660. var mesh = subMesh.getRenderingMesh();
  34661. var scene = _this._scene;
  34662. var engine = scene.getEngine();
  34663. // Culling
  34664. engine.setState(subMesh.getMaterial().backFaceCulling);
  34665. // Managing instances
  34666. var batch = mesh._getInstancesRenderList(subMesh._id);
  34667. if (batch.mustReturn) {
  34668. return;
  34669. }
  34670. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34671. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34672. engine.enableEffect(_this._effect);
  34673. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34674. var material = subMesh.getMaterial();
  34675. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34676. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34677. // Alpha test
  34678. if (material && material.needAlphaTesting()) {
  34679. var alphaTexture = material.getAlphaTestTexture();
  34680. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34681. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34682. }
  34683. // Bones
  34684. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34685. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34686. }
  34687. // Draw
  34688. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34689. }
  34690. };
  34691. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34692. var index;
  34693. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34694. renderSubMesh(opaqueSubMeshes.data[index]);
  34695. }
  34696. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34697. renderSubMesh(alphaTestSubMeshes.data[index]);
  34698. }
  34699. };
  34700. }
  34701. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34702. var defines = [];
  34703. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34704. var mesh = subMesh.getMesh();
  34705. var scene = mesh.getScene();
  34706. var material = subMesh.getMaterial();
  34707. // Alpha test
  34708. if (material && material.needAlphaTesting()) {
  34709. defines.push("#define ALPHATEST");
  34710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34711. attribs.push(BABYLON.VertexBuffer.UVKind);
  34712. defines.push("#define UV1");
  34713. }
  34714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34715. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34716. defines.push("#define UV2");
  34717. }
  34718. }
  34719. // Bones
  34720. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34723. if (mesh.numBoneInfluencers > 4) {
  34724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34726. }
  34727. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34728. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34729. }
  34730. else {
  34731. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34732. }
  34733. // Instances
  34734. if (useInstances) {
  34735. defines.push("#define INSTANCES");
  34736. attribs.push("world0");
  34737. attribs.push("world1");
  34738. attribs.push("world2");
  34739. attribs.push("world3");
  34740. }
  34741. // Get correct effect
  34742. var join = defines.join("\n");
  34743. if (this._cachedDefines !== join) {
  34744. this._cachedDefines = join;
  34745. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34746. }
  34747. return this._effect.isReady();
  34748. };
  34749. DepthRenderer.prototype.getDepthMap = function () {
  34750. return this._depthMap;
  34751. };
  34752. // Methods
  34753. DepthRenderer.prototype.dispose = function () {
  34754. this._depthMap.dispose();
  34755. };
  34756. return DepthRenderer;
  34757. })();
  34758. BABYLON.DepthRenderer = DepthRenderer;
  34759. })(BABYLON || (BABYLON = {}));
  34760. var BABYLON;
  34761. (function (BABYLON) {
  34762. var SSAORenderingPipeline = (function (_super) {
  34763. __extends(SSAORenderingPipeline, _super);
  34764. /**
  34765. * @constructor
  34766. * @param {string} name - The rendering pipeline name
  34767. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34768. * @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 }
  34769. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34770. */
  34771. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34772. var _this = this;
  34773. _super.call(this, scene.getEngine(), name);
  34774. // Members
  34775. /**
  34776. * The PassPostProcess id in the pipeline that contains the original scene color
  34777. * @type {string}
  34778. */
  34779. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34780. /**
  34781. * The SSAO PostProcess id in the pipeline
  34782. * @type {string}
  34783. */
  34784. this.SSAORenderEffect = "SSAORenderEffect";
  34785. /**
  34786. * The horizontal blur PostProcess id in the pipeline
  34787. * @type {string}
  34788. */
  34789. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34790. /**
  34791. * The vertical blur PostProcess id in the pipeline
  34792. * @type {string}
  34793. */
  34794. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34795. /**
  34796. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34797. * @type {string}
  34798. */
  34799. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34800. /**
  34801. * The output strength of the SSAO post-process. Default value is 1.0.
  34802. * @type {number}
  34803. */
  34804. this.totalStrength = 1.0;
  34805. /**
  34806. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34807. * @type {number}
  34808. */
  34809. this.radius = 0.0001;
  34810. /**
  34811. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34812. * Must not be equal to fallOff and superior to fallOff.
  34813. * Default value is 0.975
  34814. * @type {number}
  34815. */
  34816. this.area = 0.0075;
  34817. /**
  34818. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34819. * Must not be equal to area and inferior to area.
  34820. * Default value is 0.0
  34821. * @type {number}
  34822. */
  34823. this.fallOff = 0.000001;
  34824. /**
  34825. * The base color of the SSAO post-process
  34826. * The final result is "base + ssao" between [0, 1]
  34827. * @type {number}
  34828. */
  34829. this.base = 0.5;
  34830. this._firstUpdate = true;
  34831. this._scene = scene;
  34832. // Set up assets
  34833. this._createRandomTexture();
  34834. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34835. var ssaoRatio = ratio.ssaoRatio || ratio;
  34836. var combineRatio = ratio.combineRatio || ratio;
  34837. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34838. this._createSSAOPostProcess(ssaoRatio);
  34839. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34840. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34841. this._createSSAOCombinePostProcess(combineRatio);
  34842. // Set up pipeline
  34843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34848. // Finish
  34849. scene.postProcessRenderPipelineManager.addPipeline(this);
  34850. if (cameras)
  34851. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34852. }
  34853. // Public Methods
  34854. /**
  34855. * Returns the horizontal blur PostProcess
  34856. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34857. */
  34858. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34859. return this._blurHPostProcess;
  34860. };
  34861. /**
  34862. * Returns the vertical blur PostProcess
  34863. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34864. */
  34865. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34866. return this._blurVPostProcess;
  34867. };
  34868. /**
  34869. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34870. */
  34871. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34872. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34873. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34874. this._originalColorPostProcess = undefined;
  34875. this._ssaoPostProcess = undefined;
  34876. this._blurHPostProcess = undefined;
  34877. this._blurVPostProcess = undefined;
  34878. this._ssaoCombinePostProcess = undefined;
  34879. this._randomTexture.dispose();
  34880. if (disableDepthRender)
  34881. this._scene.disableDepthRenderer();
  34882. };
  34883. // Private Methods
  34884. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34885. var _this = this;
  34886. var numSamples = 16;
  34887. var sampleSphere = [
  34888. 0.5381, 0.1856, -0.4319,
  34889. 0.1379, 0.2486, 0.4430,
  34890. 0.3371, 0.5679, -0.0057,
  34891. -0.6999, -0.0451, -0.0019,
  34892. 0.0689, -0.1598, -0.8547,
  34893. 0.0560, 0.0069, -0.1843,
  34894. -0.0146, 0.1402, 0.0762,
  34895. 0.0100, -0.1924, -0.0344,
  34896. -0.3577, -0.5301, -0.4358,
  34897. -0.3169, 0.1063, 0.0158,
  34898. 0.0103, -0.5869, 0.0046,
  34899. -0.0897, -0.4940, 0.3287,
  34900. 0.7119, -0.0154, -0.0918,
  34901. -0.0533, 0.0596, -0.5411,
  34902. 0.0352, -0.0631, 0.5460,
  34903. -0.4776, 0.2847, -0.0271
  34904. ];
  34905. var samplesFactor = 1.0 / numSamples;
  34906. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34907. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34908. "area", "fallOff", "base"
  34909. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34910. this._ssaoPostProcess.onApply = function (effect) {
  34911. if (_this._firstUpdate) {
  34912. effect.setArray3("sampleSphere", sampleSphere);
  34913. effect.setFloat("samplesFactor", samplesFactor);
  34914. effect.setFloat("randTextureTiles", 4.0);
  34915. _this._firstUpdate = false;
  34916. }
  34917. effect.setFloat("totalStrength", _this.totalStrength);
  34918. effect.setFloat("radius", _this.radius);
  34919. effect.setFloat("area", _this.area);
  34920. effect.setFloat("fallOff", _this.fallOff);
  34921. effect.setFloat("base", _this.base);
  34922. effect.setTexture("textureSampler", _this._depthTexture);
  34923. effect.setTexture("randomSampler", _this._randomTexture);
  34924. };
  34925. };
  34926. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34927. var _this = this;
  34928. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34929. this._ssaoCombinePostProcess.onApply = function (effect) {
  34930. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34931. };
  34932. };
  34933. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34934. var size = 512;
  34935. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34936. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34937. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34938. var context = this._randomTexture.getContext();
  34939. var rand = function (min, max) {
  34940. return Math.random() * (max - min) + min;
  34941. };
  34942. var randVector = BABYLON.Vector3.Zero();
  34943. for (var x = 0; x < size; x++) {
  34944. for (var y = 0; y < size; y++) {
  34945. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34946. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34947. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34948. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34949. context.fillRect(x, y, 1, 1);
  34950. }
  34951. }
  34952. this._randomTexture.update(false);
  34953. };
  34954. return SSAORenderingPipeline;
  34955. })(BABYLON.PostProcessRenderPipeline);
  34956. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34957. })(BABYLON || (BABYLON = {}));
  34958. var BABYLON;
  34959. (function (BABYLON) {
  34960. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34961. var VolumetricLightScatteringPostProcess = (function (_super) {
  34962. __extends(VolumetricLightScatteringPostProcess, _super);
  34963. /**
  34964. * @constructor
  34965. * @param {string} name - The post-process name
  34966. * @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)
  34967. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34968. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34969. * @param {number} samples - The post-process quality, default 100
  34970. * @param {number} samplingMode - The post-process filtering mode
  34971. * @param {BABYLON.Engine} engine - The babylon engine
  34972. * @param {boolean} reusable - If the post-process is reusable
  34973. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34974. */
  34975. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34976. var _this = this;
  34977. if (samples === void 0) { samples = 100; }
  34978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34979. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34980. this._screenCoordinates = BABYLON.Vector2.Zero();
  34981. /**
  34982. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34983. * @type {boolean}
  34984. */
  34985. this.useCustomMeshPosition = false;
  34986. /**
  34987. * If the post-process should inverse the light scattering direction
  34988. * @type {boolean}
  34989. */
  34990. this.invert = true;
  34991. /**
  34992. * Set to true to use the diffuseColor instead of the diffuseTexture
  34993. * @type {boolean}
  34994. */
  34995. this.useDiffuseColor = false;
  34996. /**
  34997. * Array containing the excluded meshes not rendered in the internal pass
  34998. */
  34999. this.excludedMeshes = new Array();
  35000. /**
  35001. * Controls the overall intensity of the post-process
  35002. * @type {number}
  35003. */
  35004. this.exposure = 0.3;
  35005. /**
  35006. * Dissipates each sample's contribution in range [0, 1]
  35007. * @type {number}
  35008. */
  35009. this.decay = 0.96815;
  35010. /**
  35011. * Controls the overall intensity of each sample
  35012. * @type {number}
  35013. */
  35014. this.weight = 0.58767;
  35015. /**
  35016. * Controls the density of each sample
  35017. * @type {number}
  35018. */
  35019. this.density = 0.926;
  35020. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35021. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35022. // Configure mesh
  35023. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35024. // Configure
  35025. this._createPass(scene, ratio.passRatio || ratio);
  35026. this.onActivate = function (camera) {
  35027. if (!_this.isSupported) {
  35028. _this.dispose(camera);
  35029. }
  35030. _this.onActivate = null;
  35031. };
  35032. this.onApply = function (effect) {
  35033. _this._updateMeshScreenCoordinates(scene);
  35034. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35035. effect.setFloat("exposure", _this.exposure);
  35036. effect.setFloat("decay", _this.decay);
  35037. effect.setFloat("weight", _this.weight);
  35038. effect.setFloat("density", _this.density);
  35039. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35040. };
  35041. }
  35042. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35043. var mesh = subMesh.getMesh();
  35044. var defines = [];
  35045. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35046. var material = subMesh.getMaterial();
  35047. var needUV = false;
  35048. // Render this.mesh as default
  35049. if (mesh === this.mesh) {
  35050. if (this.useDiffuseColor) {
  35051. defines.push("#define DIFFUSE_COLOR_RENDER");
  35052. }
  35053. else if (material) {
  35054. if (material.diffuseTexture !== undefined) {
  35055. defines.push("#define BASIC_RENDER");
  35056. }
  35057. else {
  35058. defines.push("#define DIFFUSE_COLOR_RENDER");
  35059. }
  35060. }
  35061. defines.push("#define NEED_UV");
  35062. needUV = true;
  35063. }
  35064. // Alpha test
  35065. if (material) {
  35066. if (material.needAlphaTesting()) {
  35067. defines.push("#define ALPHATEST");
  35068. }
  35069. if (material.opacityTexture !== undefined) {
  35070. defines.push("#define OPACITY");
  35071. if (material.opacityTexture.getAlphaFromRGB) {
  35072. defines.push("#define OPACITYRGB");
  35073. }
  35074. if (!needUV) {
  35075. defines.push("#define NEED_UV");
  35076. }
  35077. }
  35078. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35079. attribs.push(BABYLON.VertexBuffer.UVKind);
  35080. defines.push("#define UV1");
  35081. }
  35082. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35083. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35084. defines.push("#define UV2");
  35085. }
  35086. }
  35087. // Bones
  35088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35089. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35090. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35091. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35092. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35093. }
  35094. else {
  35095. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35096. }
  35097. // Instances
  35098. if (useInstances) {
  35099. defines.push("#define INSTANCES");
  35100. attribs.push("world0");
  35101. attribs.push("world1");
  35102. attribs.push("world2");
  35103. attribs.push("world3");
  35104. }
  35105. // Get correct effect
  35106. var join = defines.join("\n");
  35107. if (this._cachedDefines !== join) {
  35108. this._cachedDefines = join;
  35109. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35110. }
  35111. return this._volumetricLightScatteringPass.isReady();
  35112. };
  35113. /**
  35114. * Sets the new light position for light scattering effect
  35115. * @param {BABYLON.Vector3} The new custom light position
  35116. */
  35117. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35118. this._customMeshPosition = position;
  35119. };
  35120. /**
  35121. * Returns the light position for light scattering effect
  35122. * @return {BABYLON.Vector3} The custom light position
  35123. */
  35124. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35125. return this._customMeshPosition;
  35126. };
  35127. /**
  35128. * Disposes the internal assets and detaches the post-process from the camera
  35129. */
  35130. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35131. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35132. if (rttIndex !== -1) {
  35133. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35134. }
  35135. this._volumetricLightScatteringRTT.dispose();
  35136. _super.prototype.dispose.call(this, camera);
  35137. };
  35138. /**
  35139. * Returns the render target texture used by the post-process
  35140. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35141. */
  35142. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35143. return this._volumetricLightScatteringRTT;
  35144. };
  35145. // Private methods
  35146. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35147. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35148. return true;
  35149. }
  35150. return false;
  35151. };
  35152. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35153. var _this = this;
  35154. var engine = scene.getEngine();
  35155. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35156. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35157. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35158. this._volumetricLightScatteringRTT.renderList = null;
  35159. this._volumetricLightScatteringRTT.renderParticles = false;
  35160. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35161. // Custom render function for submeshes
  35162. var renderSubMesh = function (subMesh) {
  35163. var mesh = subMesh.getRenderingMesh();
  35164. if (_this._meshExcluded(mesh)) {
  35165. return;
  35166. }
  35167. var scene = mesh.getScene();
  35168. var engine = scene.getEngine();
  35169. // Culling
  35170. engine.setState(subMesh.getMaterial().backFaceCulling);
  35171. // Managing instances
  35172. var batch = mesh._getInstancesRenderList(subMesh._id);
  35173. if (batch.mustReturn) {
  35174. return;
  35175. }
  35176. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35177. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35178. engine.enableEffect(_this._volumetricLightScatteringPass);
  35179. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35180. var material = subMesh.getMaterial();
  35181. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35182. // Alpha test
  35183. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35184. var alphaTexture = material.getAlphaTestTexture();
  35185. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35186. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35187. }
  35188. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35189. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35190. if (alphaTexture) {
  35191. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35192. }
  35193. }
  35194. if (material.opacityTexture !== undefined) {
  35195. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35196. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35197. }
  35198. }
  35199. // Bones
  35200. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35201. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35202. }
  35203. // Draw
  35204. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35205. }
  35206. };
  35207. // Render target texture callbacks
  35208. var savedSceneClearColor;
  35209. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35210. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35211. savedSceneClearColor = scene.clearColor;
  35212. scene.clearColor = sceneClearColor;
  35213. };
  35214. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35215. scene.clearColor = savedSceneClearColor;
  35216. };
  35217. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35218. var engine = scene.getEngine();
  35219. var index;
  35220. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35221. renderSubMesh(opaqueSubMeshes.data[index]);
  35222. }
  35223. engine.setAlphaTesting(true);
  35224. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35225. renderSubMesh(alphaTestSubMeshes.data[index]);
  35226. }
  35227. engine.setAlphaTesting(false);
  35228. if (transparentSubMeshes.length) {
  35229. // Sort sub meshes
  35230. for (index = 0; index < transparentSubMeshes.length; index++) {
  35231. var submesh = transparentSubMeshes.data[index];
  35232. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35233. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35234. }
  35235. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35236. sortedArray.sort(function (a, b) {
  35237. // Alpha index first
  35238. if (a._alphaIndex > b._alphaIndex) {
  35239. return 1;
  35240. }
  35241. if (a._alphaIndex < b._alphaIndex) {
  35242. return -1;
  35243. }
  35244. // Then distance to camera
  35245. if (a._distanceToCamera < b._distanceToCamera) {
  35246. return 1;
  35247. }
  35248. if (a._distanceToCamera > b._distanceToCamera) {
  35249. return -1;
  35250. }
  35251. return 0;
  35252. });
  35253. // Render sub meshes
  35254. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35255. for (index = 0; index < sortedArray.length; index++) {
  35256. renderSubMesh(sortedArray[index]);
  35257. }
  35258. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35259. }
  35260. };
  35261. };
  35262. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35263. var transform = scene.getTransformMatrix();
  35264. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35265. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35266. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35267. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35268. if (this.invert)
  35269. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35270. };
  35271. // Static methods
  35272. /**
  35273. * Creates a default mesh for the Volumeric Light Scattering post-process
  35274. * @param {string} The mesh name
  35275. * @param {BABYLON.Scene} The scene where to create the mesh
  35276. * @return {BABYLON.Mesh} the default mesh
  35277. */
  35278. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35279. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35280. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35281. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35282. return mesh;
  35283. };
  35284. return VolumetricLightScatteringPostProcess;
  35285. })(BABYLON.PostProcess);
  35286. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35287. })(BABYLON || (BABYLON = {}));
  35288. // BABYLON.JS Chromatic Aberration GLSL Shader
  35289. // Author: Olivier Guyot
  35290. // Separates very slightly R, G and B colors on the edges of the screen
  35291. // Inspired by Francois Tarlier & Martins Upitis
  35292. var BABYLON;
  35293. (function (BABYLON) {
  35294. var LensRenderingPipeline = (function (_super) {
  35295. __extends(LensRenderingPipeline, _super);
  35296. /**
  35297. * @constructor
  35298. *
  35299. * Effect parameters are as follow:
  35300. * {
  35301. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35302. * edge_blur: number; // from 0 to x (1 for realism)
  35303. * distortion: number; // from 0 to x (1 for realism)
  35304. * grain_amount: number; // from 0 to 1
  35305. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35306. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35307. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35308. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35309. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35310. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35311. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35312. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35313. * }
  35314. * Note: if an effect parameter is unset, effect is disabled
  35315. *
  35316. * @param {string} name - The rendering pipeline name
  35317. * @param {object} parameters - An object containing all parameters (see above)
  35318. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35319. * @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)
  35320. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35321. */
  35322. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35323. var _this = this;
  35324. if (ratio === void 0) { ratio = 1.0; }
  35325. _super.call(this, scene.getEngine(), name);
  35326. // Lens effects can be of the following:
  35327. // - chromatic aberration (slight shift of RGB colors)
  35328. // - blur on the edge of the lens
  35329. // - lens distortion
  35330. // - depth-of-field blur & highlights enhancing
  35331. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35332. // - grain effect (noise or custom texture)
  35333. // Two additional texture samplers are needed:
  35334. // - depth map (for depth-of-field)
  35335. // - grain texture
  35336. /**
  35337. * The chromatic aberration PostProcess id in the pipeline
  35338. * @type {string}
  35339. */
  35340. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35341. /**
  35342. * The highlights enhancing PostProcess id in the pipeline
  35343. * @type {string}
  35344. */
  35345. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35346. /**
  35347. * The depth-of-field PostProcess id in the pipeline
  35348. * @type {string}
  35349. */
  35350. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35351. this._scene = scene;
  35352. // Fetch texture samplers
  35353. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35354. if (parameters.grain_texture) {
  35355. this._grainTexture = parameters.grain_texture;
  35356. }
  35357. else {
  35358. this._createGrainTexture();
  35359. }
  35360. // save parameters
  35361. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35362. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35363. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35364. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35365. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35366. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35367. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35368. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35369. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35370. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35371. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35372. // Create effects
  35373. this._createChromaticAberrationPostProcess(ratio);
  35374. this._createHighlightsPostProcess(ratio);
  35375. this._createDepthOfFieldPostProcess(ratio / 4);
  35376. // Set up pipeline
  35377. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35380. if (this._highlightsGain === -1) {
  35381. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35382. }
  35383. // Finish
  35384. scene.postProcessRenderPipelineManager.addPipeline(this);
  35385. if (cameras) {
  35386. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35387. }
  35388. }
  35389. // public methods (self explanatory)
  35390. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35391. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35392. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35393. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35394. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35395. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35396. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35397. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35398. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35399. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35400. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35401. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35402. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35403. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35404. };
  35405. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35406. this._highlightsPostProcess.updateEffect();
  35407. };
  35408. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35409. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35410. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35411. this._highlightsGain = amount;
  35412. };
  35413. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35414. if (this._highlightsGain === -1) {
  35415. this._highlightsGain = 1.0;
  35416. }
  35417. this._highlightsThreshold = amount;
  35418. };
  35419. LensRenderingPipeline.prototype.disableHighlights = function () {
  35420. this._highlightsGain = -1;
  35421. };
  35422. /**
  35423. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35424. */
  35425. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35426. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35427. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35428. this._chromaticAberrationPostProcess = undefined;
  35429. this._highlightsPostProcess = undefined;
  35430. this._depthOfFieldPostProcess = undefined;
  35431. this._grainTexture.dispose();
  35432. if (disableDepthRender)
  35433. this._scene.disableDepthRenderer();
  35434. };
  35435. // colors shifting and distortion
  35436. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35437. var _this = this;
  35438. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35439. [], // samplers
  35440. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35441. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35442. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35443. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35444. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35445. };
  35446. };
  35447. // highlights enhancing
  35448. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35449. var _this = this;
  35450. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35451. [], // samplers
  35452. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35453. this._highlightsPostProcess.onApply = function (effect) {
  35454. effect.setFloat('gain', _this._highlightsGain);
  35455. effect.setFloat('threshold', _this._highlightsThreshold);
  35456. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35457. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35458. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35459. };
  35460. };
  35461. // colors shifting and distortion
  35462. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35463. var _this = this;
  35464. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35465. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35466. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35467. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35468. this._depthOfFieldPostProcess.onApply = function (effect) {
  35469. effect.setTexture("depthSampler", _this._depthTexture);
  35470. effect.setTexture("grainSampler", _this._grainTexture);
  35471. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35472. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35473. effect.setFloat('grain_amount', _this._grainAmount);
  35474. effect.setBool('blur_noise', _this._blurNoise);
  35475. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35476. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35477. effect.setFloat('distortion', _this._distortion);
  35478. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35479. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35480. effect.setFloat('aperture', _this._dofAperture);
  35481. effect.setFloat('darken', _this._dofDarken);
  35482. effect.setFloat('edge_blur', _this._edgeBlur);
  35483. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35484. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35485. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35486. };
  35487. };
  35488. // creates a black and white random noise texture, 512x512
  35489. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35490. var size = 512;
  35491. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35492. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35493. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35494. var context = this._grainTexture.getContext();
  35495. var rand = function (min, max) {
  35496. return Math.random() * (max - min) + min;
  35497. };
  35498. var value;
  35499. for (var x = 0; x < size; x++) {
  35500. for (var y = 0; y < size; y++) {
  35501. value = Math.floor(rand(0.42, 0.58) * 255);
  35502. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35503. context.fillRect(x, y, 1, 1);
  35504. }
  35505. }
  35506. this._grainTexture.update(false);
  35507. };
  35508. return LensRenderingPipeline;
  35509. })(BABYLON.PostProcessRenderPipeline);
  35510. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35511. })(BABYLON || (BABYLON = {}));
  35512. //
  35513. // This post-process allows the modification of rendered colors by using
  35514. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35515. //
  35516. // The object needs to be provided an url to a texture containing the color
  35517. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35518. // Use an image editing software to tweak the LUT to match your needs.
  35519. //
  35520. // For an example of a color LUT, see here:
  35521. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35522. // For explanations on color grading, see here:
  35523. // http://udn.epicgames.com/Three/ColorGrading.html
  35524. //
  35525. var BABYLON;
  35526. (function (BABYLON) {
  35527. var ColorCorrectionPostProcess = (function (_super) {
  35528. __extends(ColorCorrectionPostProcess, _super);
  35529. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35530. var _this = this;
  35531. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35532. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35533. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35534. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35535. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35536. this.onApply = function (effect) {
  35537. effect.setTexture("colorTable", _this._colorTableTexture);
  35538. };
  35539. }
  35540. return ColorCorrectionPostProcess;
  35541. })(BABYLON.PostProcess);
  35542. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35543. })(BABYLON || (BABYLON = {}));
  35544. var BABYLON;
  35545. (function (BABYLON) {
  35546. var AnaglyphFreeCamera = (function (_super) {
  35547. __extends(AnaglyphFreeCamera, _super);
  35548. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35549. _super.call(this, name, position, scene);
  35550. this.interaxialDistance = interaxialDistance;
  35551. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35552. }
  35553. return AnaglyphFreeCamera;
  35554. })(BABYLON.FreeCamera);
  35555. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35556. var AnaglyphArcRotateCamera = (function (_super) {
  35557. __extends(AnaglyphArcRotateCamera, _super);
  35558. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35559. _super.call(this, name, alpha, beta, radius, target, scene);
  35560. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35561. }
  35562. return AnaglyphArcRotateCamera;
  35563. })(BABYLON.ArcRotateCamera);
  35564. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35565. var AnaglyphGamepadCamera = (function (_super) {
  35566. __extends(AnaglyphGamepadCamera, _super);
  35567. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35568. _super.call(this, name, position, scene);
  35569. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35570. }
  35571. return AnaglyphGamepadCamera;
  35572. })(BABYLON.GamepadCamera);
  35573. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35574. var StereoscopicFreeCamera = (function (_super) {
  35575. __extends(StereoscopicFreeCamera, _super);
  35576. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35577. _super.call(this, name, position, scene);
  35578. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35579. }
  35580. return StereoscopicFreeCamera;
  35581. })(BABYLON.FreeCamera);
  35582. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35583. var StereoscopicArcRotateCamera = (function (_super) {
  35584. __extends(StereoscopicArcRotateCamera, _super);
  35585. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35586. _super.call(this, name, alpha, beta, radius, target, scene);
  35587. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35588. }
  35589. return StereoscopicArcRotateCamera;
  35590. })(BABYLON.ArcRotateCamera);
  35591. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35592. var StereoscopicGamepadCamera = (function (_super) {
  35593. __extends(StereoscopicGamepadCamera, _super);
  35594. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35595. _super.call(this, name, position, scene);
  35596. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35597. }
  35598. return StereoscopicGamepadCamera;
  35599. })(BABYLON.GamepadCamera);
  35600. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35601. })(BABYLON || (BABYLON = {}));
  35602. var BABYLON;
  35603. (function (BABYLON) {
  35604. var HDRRenderingPipeline = (function (_super) {
  35605. __extends(HDRRenderingPipeline, _super);
  35606. /**
  35607. * @constructor
  35608. * @param {string} name - The rendering pipeline name
  35609. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35610. * @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)
  35611. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35612. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35613. */
  35614. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35615. var _this = this;
  35616. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35617. _super.call(this, scene.getEngine(), name);
  35618. /**
  35619. * Public members
  35620. */
  35621. // Gaussian Blur
  35622. /**
  35623. * Gaussian blur coefficient
  35624. * @type {number}
  35625. */
  35626. this.gaussCoeff = 0.3;
  35627. /**
  35628. * Gaussian blur mean
  35629. * @type {number}
  35630. */
  35631. this.gaussMean = 1.0;
  35632. /**
  35633. * Gaussian blur standard deviation
  35634. * @type {number}
  35635. */
  35636. this.gaussStandDev = 0.8;
  35637. /**
  35638. * Gaussian blur multiplier. Multiplies the blur effect
  35639. * @type {number}
  35640. */
  35641. this.gaussMultiplier = 4.0;
  35642. // HDR
  35643. /**
  35644. * Exposure, controls the overall intensity of the pipeline
  35645. * @type {number}
  35646. */
  35647. this.exposure = 1.0;
  35648. /**
  35649. * Minimum luminance that the post-process can output. Luminance is >= 0
  35650. * @type {number}
  35651. */
  35652. this.minimumLuminance = 1.0;
  35653. /**
  35654. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35655. * @type {number}
  35656. */
  35657. this.maximumLuminance = 1e20;
  35658. /**
  35659. * Increase rate for luminance: eye adaptation speed to dark
  35660. * @type {number}
  35661. */
  35662. this.luminanceIncreaserate = 0.5;
  35663. /**
  35664. * Decrease rate for luminance: eye adaptation speed to bright
  35665. * @type {number}
  35666. */
  35667. this.luminanceDecreaseRate = 0.5;
  35668. // Bright pass
  35669. /**
  35670. * Minimum luminance needed to compute HDR
  35671. * @type {number}
  35672. */
  35673. this.brightThreshold = 0.8;
  35674. this._needUpdate = true;
  35675. this._scene = scene;
  35676. // Bright pass
  35677. this._createBrightPassPostProcess(scene, ratio);
  35678. // Down sample X4
  35679. this._createDownSampleX4PostProcess(scene, ratio);
  35680. // Create gaussian blur post-processes
  35681. this._createGaussianBlurPostProcess(scene, ratio);
  35682. // Texture adder
  35683. this._createTextureAdderPostProcess(scene, ratio);
  35684. // Luminance generator
  35685. this._createLuminanceGeneratorPostProcess(scene);
  35686. // HDR
  35687. this._createHDRPostProcess(scene, ratio);
  35688. // Pass postprocess
  35689. if (originalPostProcess === null) {
  35690. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35691. }
  35692. else {
  35693. this._originalPostProcess = originalPostProcess;
  35694. }
  35695. // Configure pipeline
  35696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35698. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35702. var addDownSamplerPostProcess = function (id) {
  35703. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35704. };
  35705. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35706. addDownSamplerPostProcess(i);
  35707. }
  35708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35709. // Finish
  35710. scene.postProcessRenderPipelineManager.addPipeline(this);
  35711. if (cameras !== null) {
  35712. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35713. }
  35714. this.update();
  35715. }
  35716. /**
  35717. * Tells the pipeline to update its post-processes
  35718. */
  35719. HDRRenderingPipeline.prototype.update = function () {
  35720. this._needUpdate = true;
  35721. };
  35722. /**
  35723. * Returns the current calculated luminance
  35724. */
  35725. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35726. return this._hdrCurrentLuminance;
  35727. };
  35728. /**
  35729. * Returns the currently drawn luminance
  35730. */
  35731. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35732. return this._hdrOutputLuminance;
  35733. };
  35734. /**
  35735. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35736. */
  35737. HDRRenderingPipeline.prototype.dispose = function () {
  35738. this._originalPostProcess = undefined;
  35739. this._brightPassPostProcess = undefined;
  35740. this._downSampleX4PostProcess = undefined;
  35741. this._guassianBlurHPostProcess = undefined;
  35742. this._guassianBlurVPostProcess = undefined;
  35743. this._textureAdderPostProcess = undefined;
  35744. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35745. this._downSamplePostProcesses[i] = undefined;
  35746. }
  35747. this._hdrPostProcess = undefined;
  35748. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35749. };
  35750. /**
  35751. * Creates the HDR post-process and computes the luminance adaptation
  35752. */
  35753. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35754. var _this = this;
  35755. var hdrLastLuminance = 0.0;
  35756. this._hdrOutputLuminance = -1.0;
  35757. this._hdrCurrentLuminance = 1.0;
  35758. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35759. this._hdrPostProcess.onApply = function (effect) {
  35760. if (_this._hdrOutputLuminance < 0.0) {
  35761. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35762. }
  35763. else {
  35764. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35765. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35766. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35767. }
  35768. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35769. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35770. }
  35771. else {
  35772. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35773. }
  35774. }
  35775. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35776. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35777. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35778. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35779. effect.setFloat("exposure", _this.exposure);
  35780. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35781. _this._needUpdate = false;
  35782. };
  35783. };
  35784. /**
  35785. * Texture Adder post-process
  35786. */
  35787. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35788. var _this = this;
  35789. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35790. this._textureAdderPostProcess.onApply = function (effect) {
  35791. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35792. };
  35793. };
  35794. /**
  35795. * Down sample X4 post-process
  35796. */
  35797. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35798. var _this = this;
  35799. var downSampleX4Offsets = new Array(32);
  35800. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35801. this._downSampleX4PostProcess.onApply = function (effect) {
  35802. if (_this._needUpdate) {
  35803. var id = 0;
  35804. for (var i = -2; i < 2; i++) {
  35805. for (var j = -2; j < 2; j++) {
  35806. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35807. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35808. id += 2;
  35809. }
  35810. }
  35811. }
  35812. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35813. };
  35814. };
  35815. /**
  35816. * Bright pass post-process
  35817. */
  35818. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35819. var _this = this;
  35820. var brightOffsets = new Array(8);
  35821. var brightPassCallback = function (effect) {
  35822. if (_this._needUpdate) {
  35823. var sU = (1.0 / _this._brightPassPostProcess.width);
  35824. var sV = (1.0 / _this._brightPassPostProcess.height);
  35825. brightOffsets[0] = -0.5 * sU;
  35826. brightOffsets[1] = 0.5 * sV;
  35827. brightOffsets[2] = 0.5 * sU;
  35828. brightOffsets[3] = 0.5 * sV;
  35829. brightOffsets[4] = -0.5 * sU;
  35830. brightOffsets[5] = -0.5 * sV;
  35831. brightOffsets[6] = 0.5 * sU;
  35832. brightOffsets[7] = -0.5 * sV;
  35833. }
  35834. effect.setArray2("dsOffsets", brightOffsets);
  35835. effect.setFloat("brightThreshold", _this.brightThreshold);
  35836. };
  35837. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35838. this._brightPassPostProcess.onApply = brightPassCallback;
  35839. };
  35840. /**
  35841. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35842. */
  35843. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35844. var _this = this;
  35845. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35846. var luminanceOffsets = new Array(8);
  35847. var downSampleOffsets = new Array(18);
  35848. var halfDestPixelSize;
  35849. this._downSamplePostProcesses = new Array(lumSteps);
  35850. // Utils for luminance
  35851. var luminanceUpdateSourceOffsets = function (width, height) {
  35852. var sU = (1.0 / width);
  35853. var sV = (1.0 / height);
  35854. luminanceOffsets[0] = -0.5 * sU;
  35855. luminanceOffsets[1] = 0.5 * sV;
  35856. luminanceOffsets[2] = 0.5 * sU;
  35857. luminanceOffsets[3] = 0.5 * sV;
  35858. luminanceOffsets[4] = -0.5 * sU;
  35859. luminanceOffsets[5] = -0.5 * sV;
  35860. luminanceOffsets[6] = 0.5 * sU;
  35861. luminanceOffsets[7] = -0.5 * sV;
  35862. };
  35863. var luminanceUpdateDestOffsets = function (width, height) {
  35864. var id = 0;
  35865. for (var x = -1; x < 2; x++) {
  35866. for (var y = -1; y < 2; y++) {
  35867. downSampleOffsets[id] = (x) / width;
  35868. downSampleOffsets[id + 1] = (y) / height;
  35869. id += 2;
  35870. }
  35871. }
  35872. };
  35873. // Luminance callback
  35874. var luminanceCallback = function (effect) {
  35875. if (_this._needUpdate) {
  35876. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35877. }
  35878. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35879. effect.setArray2("lumOffsets", luminanceOffsets);
  35880. };
  35881. // Down sample callbacks
  35882. var downSampleCallback = function (indice) {
  35883. var i = indice;
  35884. return function (effect) {
  35885. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35886. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35887. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35888. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35889. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35890. effect.setArray2("dsOffsets", downSampleOffsets);
  35891. };
  35892. };
  35893. var downSampleAfterRenderCallback = function (effect) {
  35894. // Unpack result
  35895. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35896. 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);
  35897. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35898. };
  35899. // Create luminance post-process
  35900. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35901. 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);
  35902. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35903. // Create down sample post-processes
  35904. for (var i = lumSteps - 2; i >= 0; i--) {
  35905. var length = Math.pow(3, i);
  35906. ratio = { width: length, height: length };
  35907. var defines = "#define DOWN_SAMPLE\n";
  35908. if (i === 0) {
  35909. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35910. }
  35911. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35912. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35913. if (i === 0) {
  35914. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35915. }
  35916. }
  35917. };
  35918. /**
  35919. * Gaussian blur post-processes. Horizontal and Vertical
  35920. */
  35921. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35922. var _this = this;
  35923. var blurOffsetsW = new Array(9);
  35924. var blurOffsetsH = new Array(9);
  35925. var blurWeights = new Array(9);
  35926. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35927. // Utils for gaussian blur
  35928. var calculateBlurOffsets = function (height) {
  35929. var lastOutputDimensions = {
  35930. width: scene.getEngine().getRenderWidth(),
  35931. height: scene.getEngine().getRenderHeight()
  35932. };
  35933. for (var i = 0; i < 9; i++) {
  35934. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35935. if (height) {
  35936. blurOffsetsH[i] = value;
  35937. }
  35938. else {
  35939. blurOffsetsW[i] = value;
  35940. }
  35941. }
  35942. };
  35943. var calculateWeights = function () {
  35944. var x = 0.0;
  35945. for (var i = 0; i < 9; i++) {
  35946. x = (i - 4.0) / 4.0;
  35947. 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));
  35948. }
  35949. };
  35950. // Callback
  35951. var gaussianBlurCallback = function (height) {
  35952. return function (effect) {
  35953. if (_this._needUpdate) {
  35954. calculateWeights();
  35955. calculateBlurOffsets(height);
  35956. }
  35957. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35958. effect.setArray("blurWeights", blurWeights);
  35959. effect.setFloat("multiplier", _this.gaussMultiplier);
  35960. };
  35961. };
  35962. // Create horizontal gaussian blur post-processes
  35963. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35964. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35965. // Create vertical gaussian blur post-process
  35966. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35967. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35968. };
  35969. // Luminance generator
  35970. HDRRenderingPipeline.LUM_STEPS = 6;
  35971. return HDRRenderingPipeline;
  35972. })(BABYLON.PostProcessRenderPipeline);
  35973. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35974. })(BABYLON || (BABYLON = {}));
  35975. var BABYLON;
  35976. (function (BABYLON) {
  35977. var FaceAdjacencies = (function () {
  35978. function FaceAdjacencies() {
  35979. this.edges = new Array();
  35980. this.edgesConnectedCount = 0;
  35981. }
  35982. return FaceAdjacencies;
  35983. })();
  35984. var EdgesRenderer = (function () {
  35985. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35986. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35987. if (epsilon === void 0) { epsilon = 0.95; }
  35988. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35989. this.edgesWidthScalerForOrthographic = 1000.0;
  35990. this.edgesWidthScalerForPerspective = 50.0;
  35991. this._linesPositions = new Array();
  35992. this._linesNormals = new Array();
  35993. this._linesIndices = new Array();
  35994. this._buffers = new Array();
  35995. this._checkVerticesInsteadOfIndices = false;
  35996. this._source = source;
  35997. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35998. this._epsilon = epsilon;
  35999. this._prepareRessources();
  36000. this._generateEdgesLines();
  36001. }
  36002. EdgesRenderer.prototype._prepareRessources = function () {
  36003. if (this._lineShader) {
  36004. return;
  36005. }
  36006. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36007. attributes: ["position", "normal"],
  36008. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36009. });
  36010. this._lineShader.disableDepthWrite = true;
  36011. this._lineShader.backFaceCulling = false;
  36012. };
  36013. EdgesRenderer.prototype.dispose = function () {
  36014. this._vb0.dispose();
  36015. this._vb1.dispose();
  36016. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36017. this._lineShader.dispose();
  36018. };
  36019. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36020. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36021. return 0;
  36022. }
  36023. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36024. return 1;
  36025. }
  36026. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36027. return 2;
  36028. }
  36029. return -1;
  36030. };
  36031. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36032. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36033. return 0;
  36034. }
  36035. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36036. return 1;
  36037. }
  36038. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36039. return 2;
  36040. }
  36041. return -1;
  36042. };
  36043. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36044. var needToCreateLine;
  36045. if (edge === undefined) {
  36046. needToCreateLine = true;
  36047. }
  36048. else {
  36049. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36050. needToCreateLine = dotProduct < this._epsilon;
  36051. }
  36052. if (needToCreateLine) {
  36053. var offset = this._linesPositions.length / 3;
  36054. var normal = p0.subtract(p1);
  36055. normal.normalize();
  36056. // Positions
  36057. this._linesPositions.push(p0.x);
  36058. this._linesPositions.push(p0.y);
  36059. this._linesPositions.push(p0.z);
  36060. this._linesPositions.push(p0.x);
  36061. this._linesPositions.push(p0.y);
  36062. this._linesPositions.push(p0.z);
  36063. this._linesPositions.push(p1.x);
  36064. this._linesPositions.push(p1.y);
  36065. this._linesPositions.push(p1.z);
  36066. this._linesPositions.push(p1.x);
  36067. this._linesPositions.push(p1.y);
  36068. this._linesPositions.push(p1.z);
  36069. // Normals
  36070. this._linesNormals.push(p1.x);
  36071. this._linesNormals.push(p1.y);
  36072. this._linesNormals.push(p1.z);
  36073. this._linesNormals.push(-1);
  36074. this._linesNormals.push(p1.x);
  36075. this._linesNormals.push(p1.y);
  36076. this._linesNormals.push(p1.z);
  36077. this._linesNormals.push(1);
  36078. this._linesNormals.push(p0.x);
  36079. this._linesNormals.push(p0.y);
  36080. this._linesNormals.push(p0.z);
  36081. this._linesNormals.push(-1);
  36082. this._linesNormals.push(p0.x);
  36083. this._linesNormals.push(p0.y);
  36084. this._linesNormals.push(p0.z);
  36085. this._linesNormals.push(1);
  36086. // Indices
  36087. this._linesIndices.push(offset);
  36088. this._linesIndices.push(offset + 1);
  36089. this._linesIndices.push(offset + 2);
  36090. this._linesIndices.push(offset);
  36091. this._linesIndices.push(offset + 2);
  36092. this._linesIndices.push(offset + 3);
  36093. }
  36094. };
  36095. EdgesRenderer.prototype._generateEdgesLines = function () {
  36096. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36097. var indices = this._source.getIndices();
  36098. // First let's find adjacencies
  36099. var adjacencies = new Array();
  36100. var faceNormals = new Array();
  36101. var index;
  36102. var faceAdjacencies;
  36103. // Prepare faces
  36104. for (index = 0; index < indices.length; index += 3) {
  36105. faceAdjacencies = new FaceAdjacencies();
  36106. var p0Index = indices[index];
  36107. var p1Index = indices[index + 1];
  36108. var p2Index = indices[index + 2];
  36109. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36110. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36111. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36112. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36113. faceNormal.normalize();
  36114. faceNormals.push(faceNormal);
  36115. adjacencies.push(faceAdjacencies);
  36116. }
  36117. // Scan
  36118. for (index = 0; index < adjacencies.length; index++) {
  36119. faceAdjacencies = adjacencies[index];
  36120. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36121. var otherFaceAdjacencies = adjacencies[otherIndex];
  36122. if (faceAdjacencies.edgesConnectedCount === 3) {
  36123. break;
  36124. }
  36125. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36126. continue;
  36127. }
  36128. var otherP0 = indices[otherIndex * 3];
  36129. var otherP1 = indices[otherIndex * 3 + 1];
  36130. var otherP2 = indices[otherIndex * 3 + 2];
  36131. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36132. var otherEdgeIndex;
  36133. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36134. continue;
  36135. }
  36136. switch (edgeIndex) {
  36137. case 0:
  36138. if (this._checkVerticesInsteadOfIndices) {
  36139. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36140. }
  36141. else {
  36142. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36143. }
  36144. break;
  36145. case 1:
  36146. if (this._checkVerticesInsteadOfIndices) {
  36147. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36148. }
  36149. else {
  36150. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36151. }
  36152. break;
  36153. case 2:
  36154. if (this._checkVerticesInsteadOfIndices) {
  36155. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36156. }
  36157. else {
  36158. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36159. }
  36160. break;
  36161. }
  36162. if (otherEdgeIndex === -1) {
  36163. continue;
  36164. }
  36165. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36166. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36167. faceAdjacencies.edgesConnectedCount++;
  36168. otherFaceAdjacencies.edgesConnectedCount++;
  36169. if (faceAdjacencies.edgesConnectedCount === 3) {
  36170. break;
  36171. }
  36172. }
  36173. }
  36174. }
  36175. // Create lines
  36176. for (index = 0; index < adjacencies.length; index++) {
  36177. // 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
  36178. var current = adjacencies[index];
  36179. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36180. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36181. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36182. }
  36183. // Merge into a single mesh
  36184. var engine = this._source.getScene().getEngine();
  36185. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36186. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36187. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36188. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36189. this._ib = engine.createIndexBuffer(this._linesIndices);
  36190. this._indicesCount = this._linesIndices.length;
  36191. };
  36192. EdgesRenderer.prototype.render = function () {
  36193. if (!this._lineShader.isReady()) {
  36194. return;
  36195. }
  36196. var scene = this._source.getScene();
  36197. var engine = scene.getEngine();
  36198. this._lineShader._preBind();
  36199. // VBOs
  36200. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36201. scene.resetCachedMaterial();
  36202. this._lineShader.setColor4("color", this._source.edgesColor);
  36203. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36204. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36205. }
  36206. else {
  36207. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36208. }
  36209. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36210. this._lineShader.bind(this._source.getWorldMatrix());
  36211. // Draw order
  36212. engine.draw(true, 0, this._indicesCount);
  36213. this._lineShader.unbind();
  36214. engine.setDepthWrite(true);
  36215. };
  36216. return EdgesRenderer;
  36217. })();
  36218. BABYLON.EdgesRenderer = EdgesRenderer;
  36219. })(BABYLON || (BABYLON = {}));
  36220. var BABYLON;
  36221. (function (BABYLON) {
  36222. (function (TonemappingOperator) {
  36223. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36224. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36225. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36226. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36227. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36228. var TonemappingOperator = BABYLON.TonemappingOperator;
  36229. ;
  36230. var TonemapPostProcess = (function (_super) {
  36231. __extends(TonemapPostProcess, _super);
  36232. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36233. var _this = this;
  36234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36235. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36236. this._operator = operator;
  36237. this._exposureAdjustment = exposureAdjustment;
  36238. var params = ["_ExposureAdjustment"];
  36239. var defines = "#define ";
  36240. if (operator === TonemappingOperator.Hable)
  36241. defines += "HABLE_TONEMAPPING";
  36242. else if (operator === TonemappingOperator.Reinhard)
  36243. defines += "REINHARD_TONEMAPPING";
  36244. else if (operator === TonemappingOperator.HejiDawson)
  36245. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36246. else if (operator === TonemappingOperator.Photographic)
  36247. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36248. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36249. this.onApply = function (effect) {
  36250. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36251. };
  36252. }
  36253. return TonemapPostProcess;
  36254. })(BABYLON.PostProcess);
  36255. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36256. })(BABYLON || (BABYLON = {}));
  36257. var BABYLON;
  36258. (function (BABYLON) {
  36259. var ReflectionProbe = (function () {
  36260. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36261. var _this = this;
  36262. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36263. this.name = name;
  36264. this._viewMatrix = BABYLON.Matrix.Identity();
  36265. this._target = BABYLON.Vector3.Zero();
  36266. this._add = BABYLON.Vector3.Zero();
  36267. this.position = BABYLON.Vector3.Zero();
  36268. this._scene = scene;
  36269. this._scene.reflectionProbes.push(this);
  36270. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36271. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36272. switch (faceIndex) {
  36273. case 0:
  36274. _this._add.copyFromFloats(1, 0, 0);
  36275. break;
  36276. case 1:
  36277. _this._add.copyFromFloats(-1, 0, 0);
  36278. break;
  36279. case 2:
  36280. _this._add.copyFromFloats(0, -1, 0);
  36281. break;
  36282. case 3:
  36283. _this._add.copyFromFloats(0, 1, 0);
  36284. break;
  36285. case 4:
  36286. _this._add.copyFromFloats(0, 0, 1);
  36287. break;
  36288. case 5:
  36289. _this._add.copyFromFloats(0, 0, -1);
  36290. break;
  36291. }
  36292. if (_this._attachedMesh) {
  36293. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36294. }
  36295. _this.position.addToRef(_this._add, _this._target);
  36296. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36297. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36298. };
  36299. this._renderTargetTexture.onAfterUnbind = function () {
  36300. scene.updateTransformMatrix(true);
  36301. };
  36302. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36303. }
  36304. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36305. get: function () {
  36306. return this._renderTargetTexture.refreshRate;
  36307. },
  36308. set: function (value) {
  36309. this._renderTargetTexture.refreshRate = value;
  36310. },
  36311. enumerable: true,
  36312. configurable: true
  36313. });
  36314. ReflectionProbe.prototype.getScene = function () {
  36315. return this._scene;
  36316. };
  36317. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36318. get: function () {
  36319. return this._renderTargetTexture;
  36320. },
  36321. enumerable: true,
  36322. configurable: true
  36323. });
  36324. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36325. get: function () {
  36326. return this._renderTargetTexture.renderList;
  36327. },
  36328. enumerable: true,
  36329. configurable: true
  36330. });
  36331. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36332. this._attachedMesh = mesh;
  36333. };
  36334. ReflectionProbe.prototype.dispose = function () {
  36335. var index = this._scene.reflectionProbes.indexOf(this);
  36336. if (index !== -1) {
  36337. // Remove from the scene if found
  36338. this._scene.reflectionProbes.splice(index, 1);
  36339. }
  36340. if (this._renderTargetTexture) {
  36341. this._renderTargetTexture.dispose();
  36342. this._renderTargetTexture = null;
  36343. }
  36344. };
  36345. return ReflectionProbe;
  36346. })();
  36347. BABYLON.ReflectionProbe = ReflectionProbe;
  36348. })(BABYLON || (BABYLON = {}));
  36349. var BABYLON;
  36350. (function (BABYLON) {
  36351. var SolidParticle = (function () {
  36352. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36353. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36354. this.position = BABYLON.Vector3.Zero(); // position
  36355. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36356. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36357. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36358. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36359. this.alive = true; // alive
  36360. this.idx = particleIndex;
  36361. this._pos = positionIndex;
  36362. this._model = model;
  36363. this.shapeId = shapeId;
  36364. this.idxInShape = idxInShape;
  36365. }
  36366. return SolidParticle;
  36367. })();
  36368. BABYLON.SolidParticle = SolidParticle;
  36369. var ModelShape = (function () {
  36370. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36371. this.shapeID = id;
  36372. this._shape = shape;
  36373. this._shapeUV = shapeUV;
  36374. this._positionFunction = posFunction;
  36375. this._vertexFunction = vtxFunction;
  36376. }
  36377. return ModelShape;
  36378. })();
  36379. BABYLON.ModelShape = ModelShape;
  36380. })(BABYLON || (BABYLON = {}));
  36381. var BABYLON;
  36382. (function (BABYLON) {
  36383. var SolidParticleSystem = (function () {
  36384. function SolidParticleSystem(name, scene, options) {
  36385. // public members
  36386. this.particles = new Array();
  36387. this.nbParticles = 0;
  36388. this.billboard = false;
  36389. this.counter = 0;
  36390. this.vars = {};
  36391. this._positions = new Array();
  36392. this._indices = new Array();
  36393. this._normals = new Array();
  36394. this._colors = new Array();
  36395. this._uvs = new Array();
  36396. this._index = 0; // indices index
  36397. this._updatable = true;
  36398. this._pickable = false;
  36399. this._alwaysVisible = false;
  36400. this._shapeCounter = 0;
  36401. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36402. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36403. this._computeParticleColor = true;
  36404. this._computeParticleTexture = true;
  36405. this._computeParticleRotation = true;
  36406. this._computeParticleVertex = false;
  36407. this._cam_axisZ = BABYLON.Vector3.Zero();
  36408. this._cam_axisY = BABYLON.Vector3.Zero();
  36409. this._cam_axisX = BABYLON.Vector3.Zero();
  36410. this._axisX = BABYLON.Axis.X;
  36411. this._axisY = BABYLON.Axis.Y;
  36412. this._axisZ = BABYLON.Axis.Z;
  36413. this._fakeCamPos = BABYLON.Vector3.Zero();
  36414. this._rotMatrix = new BABYLON.Matrix();
  36415. this._invertMatrix = new BABYLON.Matrix();
  36416. this._rotated = BABYLON.Vector3.Zero();
  36417. this._quaternion = new BABYLON.Quaternion();
  36418. this._vertex = BABYLON.Vector3.Zero();
  36419. this._normal = BABYLON.Vector3.Zero();
  36420. this._yaw = 0.0;
  36421. this._pitch = 0.0;
  36422. this._roll = 0.0;
  36423. this._halfroll = 0.0;
  36424. this._halfpitch = 0.0;
  36425. this._halfyaw = 0.0;
  36426. this._sinRoll = 0.0;
  36427. this._cosRoll = 0.0;
  36428. this._sinPitch = 0.0;
  36429. this._cosPitch = 0.0;
  36430. this._sinYaw = 0.0;
  36431. this._cosYaw = 0.0;
  36432. this._w = 0.0;
  36433. this.name = name;
  36434. this._scene = scene;
  36435. this._camera = scene.activeCamera;
  36436. this._pickable = options ? options.isPickable : false;
  36437. if (options && options.updatable) {
  36438. this._updatable = options.updatable;
  36439. }
  36440. else {
  36441. this._updatable = true;
  36442. }
  36443. if (this._pickable) {
  36444. this.pickedParticles = [];
  36445. }
  36446. }
  36447. // build the SPS mesh : returns the mesh
  36448. SolidParticleSystem.prototype.buildMesh = function () {
  36449. if (this.nbParticles === 0) {
  36450. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36451. this.addShape(triangle, 1);
  36452. triangle.dispose();
  36453. }
  36454. this._positions32 = new Float32Array(this._positions);
  36455. this._uvs32 = new Float32Array(this._uvs);
  36456. this._colors32 = new Float32Array(this._colors);
  36457. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36458. this._normals32 = new Float32Array(this._normals);
  36459. this._fixedNormal32 = new Float32Array(this._normals);
  36460. var vertexData = new BABYLON.VertexData();
  36461. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36462. vertexData.indices = this._indices;
  36463. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36464. if (this._uvs32) {
  36465. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36466. ;
  36467. }
  36468. if (this._colors32) {
  36469. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36470. }
  36471. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36472. vertexData.applyToMesh(mesh, this._updatable);
  36473. this.mesh = mesh;
  36474. this.mesh.isPickable = this._pickable;
  36475. // free memory
  36476. this._positions = null;
  36477. this._normals = null;
  36478. this._uvs = null;
  36479. this._colors = null;
  36480. if (!this._updatable) {
  36481. this.particles.length = 0;
  36482. }
  36483. return mesh;
  36484. };
  36485. //reset copy
  36486. SolidParticleSystem.prototype._resetCopy = function () {
  36487. this._copy.position.x = 0;
  36488. this._copy.position.y = 0;
  36489. this._copy.position.z = 0;
  36490. this._copy.rotation.x = 0;
  36491. this._copy.rotation.y = 0;
  36492. this._copy.rotation.z = 0;
  36493. this._copy.quaternion = null;
  36494. this._copy.scale.x = 1;
  36495. this._copy.scale.y = 1;
  36496. this._copy.scale.z = 1;
  36497. this._copy.uvs.x = 0;
  36498. this._copy.uvs.y = 0;
  36499. this._copy.uvs.z = 1;
  36500. this._copy.uvs.w = 1;
  36501. this._copy.color = null;
  36502. };
  36503. // _meshBuilder : inserts the shape model in the global SPS mesh
  36504. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36505. var i;
  36506. var u = 0;
  36507. var c = 0;
  36508. this._resetCopy();
  36509. if (options && options.positionFunction) {
  36510. options.positionFunction(this._copy, idx, idxInShape);
  36511. }
  36512. if (this._copy.quaternion) {
  36513. this._quaternion.x = this._copy.quaternion.x;
  36514. this._quaternion.y = this._copy.quaternion.y;
  36515. this._quaternion.z = this._copy.quaternion.z;
  36516. this._quaternion.w = this._copy.quaternion.w;
  36517. }
  36518. else {
  36519. this._yaw = this._copy.rotation.y;
  36520. this._pitch = this._copy.rotation.x;
  36521. this._roll = this._copy.rotation.z;
  36522. this._quaternionRotationYPR();
  36523. }
  36524. this._quaternionToRotationMatrix();
  36525. for (i = 0; i < shape.length; i++) {
  36526. this._vertex.x = shape[i].x;
  36527. this._vertex.y = shape[i].y;
  36528. this._vertex.z = shape[i].z;
  36529. if (options && options.vertexFunction) {
  36530. options.vertexFunction(this._copy, this._vertex, i);
  36531. }
  36532. this._vertex.x *= this._copy.scale.x;
  36533. this._vertex.y *= this._copy.scale.y;
  36534. this._vertex.z *= this._copy.scale.z;
  36535. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36536. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36537. if (meshUV) {
  36538. 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);
  36539. u += 2;
  36540. }
  36541. if (this._copy.color) {
  36542. this._color = this._copy.color;
  36543. }
  36544. else if (meshCol && meshCol[c]) {
  36545. this._color.r = meshCol[c];
  36546. this._color.g = meshCol[c + 1];
  36547. this._color.b = meshCol[c + 2];
  36548. this._color.a = meshCol[c + 3];
  36549. }
  36550. else {
  36551. this._color.r = 1;
  36552. this._color.g = 1;
  36553. this._color.b = 1;
  36554. this._color.a = 1;
  36555. }
  36556. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36557. c += 4;
  36558. }
  36559. for (i = 0; i < meshInd.length; i++) {
  36560. indices.push(p + meshInd[i]);
  36561. }
  36562. if (this._pickable) {
  36563. var nbfaces = meshInd.length / 3;
  36564. for (i = 0; i < nbfaces; i++) {
  36565. this.pickedParticles.push({ idx: idx, faceId: i });
  36566. }
  36567. }
  36568. };
  36569. // returns a shape array from positions array
  36570. SolidParticleSystem.prototype._posToShape = function (positions) {
  36571. var shape = [];
  36572. for (var i = 0; i < positions.length; i += 3) {
  36573. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36574. }
  36575. return shape;
  36576. };
  36577. // returns a shapeUV array from a Vector4 uvs
  36578. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36579. var shapeUV = [];
  36580. if (uvs) {
  36581. for (var i = 0; i < uvs.length; i++)
  36582. shapeUV.push(uvs[i]);
  36583. }
  36584. return shapeUV;
  36585. };
  36586. // adds a new particle object in the particles array
  36587. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36588. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36589. };
  36590. // add solid particles from a shape model in the particles array
  36591. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36592. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36593. var meshInd = mesh.getIndices();
  36594. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36595. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36596. var shape = this._posToShape(meshPos);
  36597. var shapeUV = this._uvsToShapeUV(meshUV);
  36598. var posfunc = options ? options.positionFunction : null;
  36599. var vtxfunc = options ? options.vertexFunction : null;
  36600. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36601. // particles
  36602. var idx = this.nbParticles;
  36603. for (var i = 0; i < nb; i++) {
  36604. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36605. if (this._updatable) {
  36606. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36607. }
  36608. this._index += shape.length;
  36609. idx++;
  36610. }
  36611. this.nbParticles += nb;
  36612. this._shapeCounter++;
  36613. return this._shapeCounter;
  36614. };
  36615. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36616. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36617. this._resetCopy();
  36618. if (particle._model._positionFunction) {
  36619. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36620. }
  36621. if (this._copy.quaternion) {
  36622. this._quaternion.x = this._copy.quaternion.x;
  36623. this._quaternion.y = this._copy.quaternion.y;
  36624. this._quaternion.z = this._copy.quaternion.z;
  36625. this._quaternion.w = this._copy.quaternion.w;
  36626. }
  36627. else {
  36628. this._yaw = this._copy.rotation.y;
  36629. this._pitch = this._copy.rotation.x;
  36630. this._roll = this._copy.rotation.z;
  36631. this._quaternionRotationYPR();
  36632. }
  36633. this._quaternionToRotationMatrix();
  36634. this._shape = particle._model._shape;
  36635. for (var pt = 0; pt < this._shape.length; pt++) {
  36636. this._vertex.x = this._shape[pt].x;
  36637. this._vertex.y = this._shape[pt].y;
  36638. this._vertex.z = this._shape[pt].z;
  36639. if (particle._model._vertexFunction) {
  36640. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36641. }
  36642. this._vertex.x *= this._copy.scale.x;
  36643. this._vertex.y *= this._copy.scale.y;
  36644. this._vertex.z *= this._copy.scale.z;
  36645. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36646. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36647. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36648. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36649. }
  36650. particle.position.x = 0;
  36651. particle.position.y = 0;
  36652. particle.position.z = 0;
  36653. particle.rotation.x = 0;
  36654. particle.rotation.y = 0;
  36655. particle.rotation.z = 0;
  36656. particle.quaternion = null;
  36657. particle.scale.x = 1;
  36658. particle.scale.y = 1;
  36659. particle.scale.z = 1;
  36660. };
  36661. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36662. SolidParticleSystem.prototype.rebuildMesh = function () {
  36663. for (var p = 0; p < this.particles.length; p++) {
  36664. this._rebuildParticle(this.particles[p]);
  36665. }
  36666. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36667. };
  36668. // sets all the particles : updates the VBO
  36669. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36670. if (start === void 0) { start = 0; }
  36671. if (end === void 0) { end = this.nbParticles - 1; }
  36672. if (update === void 0) { update = true; }
  36673. if (!this._updatable) {
  36674. return;
  36675. }
  36676. // custom beforeUpdate
  36677. this.beforeUpdateParticles(start, end, update);
  36678. this._cam_axisX.x = 1;
  36679. this._cam_axisX.y = 0;
  36680. this._cam_axisX.z = 0;
  36681. this._cam_axisY.x = 0;
  36682. this._cam_axisY.y = 1;
  36683. this._cam_axisY.z = 0;
  36684. this._cam_axisZ.x = 0;
  36685. this._cam_axisZ.y = 0;
  36686. this._cam_axisZ.z = 1;
  36687. // if the particles will always face the camera
  36688. if (this.billboard) {
  36689. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36690. this._yaw = this.mesh.rotation.y;
  36691. this._pitch = this.mesh.rotation.x;
  36692. this._roll = this.mesh.rotation.z;
  36693. this._quaternionRotationYPR();
  36694. this._quaternionToRotationMatrix();
  36695. this._rotMatrix.invertToRef(this._invertMatrix);
  36696. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36697. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36698. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36699. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36700. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36701. this._cam_axisY.normalize();
  36702. this._cam_axisX.normalize();
  36703. this._cam_axisZ.normalize();
  36704. }
  36705. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36706. var idx = 0;
  36707. var index = 0;
  36708. var colidx = 0;
  36709. var colorIndex = 0;
  36710. var uvidx = 0;
  36711. var uvIndex = 0;
  36712. // particle loop
  36713. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36714. for (var p = start; p <= end; p++) {
  36715. this._particle = this.particles[p];
  36716. this._shape = this._particle._model._shape;
  36717. this._shapeUV = this._particle._model._shapeUV;
  36718. // call to custom user function to update the particle properties
  36719. this.updateParticle(this._particle);
  36720. // particle rotation matrix
  36721. if (this.billboard) {
  36722. this._particle.rotation.x = 0.0;
  36723. this._particle.rotation.y = 0.0;
  36724. }
  36725. if (this._computeParticleRotation) {
  36726. if (this._particle.quaternion) {
  36727. this._quaternion.x = this._particle.quaternion.x;
  36728. this._quaternion.y = this._particle.quaternion.y;
  36729. this._quaternion.z = this._particle.quaternion.z;
  36730. this._quaternion.w = this._particle.quaternion.w;
  36731. }
  36732. else {
  36733. this._yaw = this._particle.rotation.y;
  36734. this._pitch = this._particle.rotation.x;
  36735. this._roll = this._particle.rotation.z;
  36736. this._quaternionRotationYPR();
  36737. }
  36738. this._quaternionToRotationMatrix();
  36739. }
  36740. for (var pt = 0; pt < this._shape.length; pt++) {
  36741. idx = index + pt * 3;
  36742. colidx = colorIndex + pt * 4;
  36743. uvidx = uvIndex + pt * 2;
  36744. this._vertex.x = this._shape[pt].x;
  36745. this._vertex.y = this._shape[pt].y;
  36746. this._vertex.z = this._shape[pt].z;
  36747. if (this._computeParticleVertex) {
  36748. this.updateParticleVertex(this._particle, this._vertex, pt);
  36749. }
  36750. // positions
  36751. this._vertex.x *= this._particle.scale.x;
  36752. this._vertex.y *= this._particle.scale.y;
  36753. this._vertex.z *= this._particle.scale.z;
  36754. 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];
  36755. 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;
  36756. 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;
  36757. 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;
  36758. 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;
  36759. 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;
  36760. 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;
  36761. // normals : if the particles can't be morphed then just rotate the normals
  36762. if (!this._computeParticleVertex && !this.billboard) {
  36763. this._normal.x = this._fixedNormal32[idx];
  36764. this._normal.y = this._fixedNormal32[idx + 1];
  36765. this._normal.z = this._fixedNormal32[idx + 2];
  36766. 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];
  36767. 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;
  36768. 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;
  36769. 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;
  36770. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36771. 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;
  36772. 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;
  36773. }
  36774. if (this._computeParticleColor) {
  36775. this._colors32[colidx] = this._particle.color.r;
  36776. this._colors32[colidx + 1] = this._particle.color.g;
  36777. this._colors32[colidx + 2] = this._particle.color.b;
  36778. this._colors32[colidx + 3] = this._particle.color.a;
  36779. }
  36780. if (this._computeParticleTexture) {
  36781. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36782. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36783. }
  36784. }
  36785. index = idx + 3;
  36786. colorIndex = colidx + 4;
  36787. uvIndex = uvidx + 2;
  36788. }
  36789. if (update) {
  36790. if (this._computeParticleColor) {
  36791. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36792. }
  36793. if (this._computeParticleTexture) {
  36794. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36795. }
  36796. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36797. if (!this.mesh.areNormalsFrozen) {
  36798. if (this._computeParticleVertex || this.billboard) {
  36799. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36800. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36801. for (var i = 0; i < this._normals32.length; i++) {
  36802. this._fixedNormal32[i] = this._normals32[i];
  36803. }
  36804. }
  36805. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36806. }
  36807. }
  36808. this.afterUpdateParticles(start, end, update);
  36809. };
  36810. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36811. this._halfroll = this._roll * 0.5;
  36812. this._halfpitch = this._pitch * 0.5;
  36813. this._halfyaw = this._yaw * 0.5;
  36814. this._sinRoll = Math.sin(this._halfroll);
  36815. this._cosRoll = Math.cos(this._halfroll);
  36816. this._sinPitch = Math.sin(this._halfpitch);
  36817. this._cosPitch = Math.cos(this._halfpitch);
  36818. this._sinYaw = Math.sin(this._halfyaw);
  36819. this._cosYaw = Math.cos(this._halfyaw);
  36820. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36821. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36822. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36823. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36824. };
  36825. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36826. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36827. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36828. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36829. this._rotMatrix.m[3] = 0;
  36830. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36831. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36832. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36833. this._rotMatrix.m[7] = 0;
  36834. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36835. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36836. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36837. this._rotMatrix.m[11] = 0;
  36838. this._rotMatrix.m[12] = 0;
  36839. this._rotMatrix.m[13] = 0;
  36840. this._rotMatrix.m[14] = 0;
  36841. this._rotMatrix.m[15] = 1.0;
  36842. };
  36843. // dispose the SPS
  36844. SolidParticleSystem.prototype.dispose = function () {
  36845. this.mesh.dispose();
  36846. this.vars = null;
  36847. // drop references to internal big arrays for the GC
  36848. this._positions = null;
  36849. this._indices = null;
  36850. this._normals = null;
  36851. this._uvs = null;
  36852. this._colors = null;
  36853. this._positions32 = null;
  36854. this._normals32 = null;
  36855. this._fixedNormal32 = null;
  36856. this._uvs32 = null;
  36857. this._colors32 = null;
  36858. this.pickedParticles = null;
  36859. };
  36860. // Visibilty helpers
  36861. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36862. this.mesh.refreshBoundingInfo();
  36863. };
  36864. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36865. // getter and setter
  36866. get: function () {
  36867. return this._alwaysVisible;
  36868. },
  36869. set: function (val) {
  36870. this._alwaysVisible = val;
  36871. this.mesh.alwaysSelectAsActiveMesh = val;
  36872. },
  36873. enumerable: true,
  36874. configurable: true
  36875. });
  36876. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36877. // getters
  36878. get: function () {
  36879. return this._computeParticleRotation;
  36880. },
  36881. // Optimizer setters
  36882. set: function (val) {
  36883. this._computeParticleRotation = val;
  36884. },
  36885. enumerable: true,
  36886. configurable: true
  36887. });
  36888. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36889. get: function () {
  36890. return this._computeParticleColor;
  36891. },
  36892. set: function (val) {
  36893. this._computeParticleColor = val;
  36894. },
  36895. enumerable: true,
  36896. configurable: true
  36897. });
  36898. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36899. get: function () {
  36900. return this._computeParticleTexture;
  36901. },
  36902. set: function (val) {
  36903. this._computeParticleTexture = val;
  36904. },
  36905. enumerable: true,
  36906. configurable: true
  36907. });
  36908. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36909. get: function () {
  36910. return this._computeParticleVertex;
  36911. },
  36912. set: function (val) {
  36913. this._computeParticleVertex = val;
  36914. },
  36915. enumerable: true,
  36916. configurable: true
  36917. });
  36918. // =======================================================================
  36919. // Particle behavior logic
  36920. // these following methods may be overwritten by the user to fit his needs
  36921. // init : sets all particles first values and calls updateParticle to set them in space
  36922. // can be overwritten by the user
  36923. SolidParticleSystem.prototype.initParticles = function () {
  36924. };
  36925. // recycles a particle : can by overwritten by the user
  36926. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36927. return particle;
  36928. };
  36929. // updates a particle : can be overwritten by the user
  36930. // will be called on each particle by setParticles() :
  36931. // ex : just set a particle position or velocity and recycle conditions
  36932. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36933. return particle;
  36934. };
  36935. // updates a vertex of a particle : can be overwritten by the user
  36936. // will be called on each vertex particle by setParticles() :
  36937. // particle : the current particle
  36938. // vertex : the current index of the current particle
  36939. // pt : the index of the current vertex in the particle shape
  36940. // ex : just set a vertex particle position
  36941. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36942. return vertex;
  36943. };
  36944. // will be called before any other treatment by setParticles()
  36945. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36946. };
  36947. // will be called after all setParticles() treatments
  36948. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36949. };
  36950. return SolidParticleSystem;
  36951. })();
  36952. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36953. })(BABYLON || (BABYLON = {}));
  36954. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nuniform vec2 depthValues;\r\n\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform 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\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  36955. 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,W=s*y-h*u,N=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*W)*b,t.m[11]=-(i*S-n*Z+o*N)*b,t.m[15]=(i*D-n*W+r*N)*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.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36956. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36957. module.exports = BABYLON;
  36958. };