babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.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, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.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, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3037. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3038. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3039. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3040. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3041. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3042. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero(),
  3045. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3046. return Tmp;
  3047. })();
  3048. BABYLON.Tmp = Tmp;
  3049. })(BABYLON || (BABYLON = {}));
  3050. var BABYLON;
  3051. (function (BABYLON) {
  3052. function generateSerializableMember(type, sourceName) {
  3053. return function (target, propertyKey) {
  3054. if (!target.__serializableMembers) {
  3055. target.__serializableMembers = {};
  3056. }
  3057. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3058. };
  3059. }
  3060. function serialize(sourceName) {
  3061. return generateSerializableMember(0, sourceName); // value member
  3062. }
  3063. BABYLON.serialize = serialize;
  3064. function serializeAsTexture(sourceName) {
  3065. return generateSerializableMember(1, sourceName); // texture member
  3066. }
  3067. BABYLON.serializeAsTexture = serializeAsTexture;
  3068. function serializeAsColor3(sourceName) {
  3069. return generateSerializableMember(2, sourceName); // color3 member
  3070. }
  3071. BABYLON.serializeAsColor3 = serializeAsColor3;
  3072. function serializeAsFresnelParameters(sourceName) {
  3073. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3074. }
  3075. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3076. function serializeAsVector2(sourceName) {
  3077. return generateSerializableMember(4, sourceName); // vector2 member
  3078. }
  3079. BABYLON.serializeAsVector2 = serializeAsVector2;
  3080. function serializeAsVector3(sourceName) {
  3081. return generateSerializableMember(5, sourceName); // vector3 member
  3082. }
  3083. BABYLON.serializeAsVector3 = serializeAsVector3;
  3084. function serializeAsMeshReference(sourceName) {
  3085. return generateSerializableMember(6, sourceName); // mesh reference member
  3086. }
  3087. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3088. var SerializationHelper = (function () {
  3089. function SerializationHelper() {
  3090. }
  3091. SerializationHelper.Serialize = function (entity, serializationObject) {
  3092. if (!serializationObject) {
  3093. serializationObject = {};
  3094. }
  3095. // Tags
  3096. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3097. // Properties
  3098. for (var property in entity.__serializableMembers) {
  3099. var propertyDescriptor = entity.__serializableMembers[property];
  3100. var targetPropertyName = propertyDescriptor.sourceName || property;
  3101. var propertyType = propertyDescriptor.type;
  3102. var sourceProperty = entity[property];
  3103. if (sourceProperty !== undefined && sourceProperty !== null) {
  3104. switch (propertyType) {
  3105. case 0:
  3106. serializationObject[targetPropertyName] = sourceProperty;
  3107. break;
  3108. case 1:
  3109. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3110. break;
  3111. case 2:
  3112. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3113. break;
  3114. case 3:
  3115. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3116. break;
  3117. case 4:
  3118. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3119. break;
  3120. case 5:
  3121. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3122. break;
  3123. case 6:
  3124. serializationObject[targetPropertyName] = sourceProperty.id;
  3125. break;
  3126. }
  3127. }
  3128. }
  3129. return serializationObject;
  3130. };
  3131. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3132. var destination = creationFunction();
  3133. // Tags
  3134. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3135. // Properties
  3136. for (var property in destination.__serializableMembers) {
  3137. var propertyDescriptor = destination.__serializableMembers[property];
  3138. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3139. var propertyType = propertyDescriptor.type;
  3140. if (sourceProperty !== undefined && sourceProperty !== null) {
  3141. switch (propertyType) {
  3142. case 0:
  3143. destination[property] = sourceProperty;
  3144. break;
  3145. case 1:
  3146. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3147. break;
  3148. case 2:
  3149. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3150. break;
  3151. case 3:
  3152. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3153. break;
  3154. case 4:
  3155. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3156. break;
  3157. case 5:
  3158. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3159. break;
  3160. case 6:
  3161. destination[property] = scene.getLastMeshByID(sourceProperty);
  3162. break;
  3163. }
  3164. }
  3165. }
  3166. return destination;
  3167. };
  3168. SerializationHelper.Clone = function (creationFunction, source) {
  3169. var destination = creationFunction();
  3170. // Tags
  3171. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3172. // Properties
  3173. for (var property in destination.__serializableMembers) {
  3174. var propertyDescriptor = destination.__serializableMembers[property];
  3175. var sourceProperty = source[property];
  3176. var propertyType = propertyDescriptor.type;
  3177. if (sourceProperty !== undefined && sourceProperty !== null) {
  3178. switch (propertyType) {
  3179. case 0: // Value
  3180. case 6:
  3181. destination[property] = sourceProperty;
  3182. break;
  3183. case 1: // Texture
  3184. case 2: // Color3
  3185. case 3: // FresnelParameters
  3186. case 4: // Vector2
  3187. case 5:
  3188. destination[property] = sourceProperty.clone();
  3189. break;
  3190. }
  3191. }
  3192. }
  3193. return destination;
  3194. };
  3195. return SerializationHelper;
  3196. })();
  3197. BABYLON.SerializationHelper = SerializationHelper;
  3198. })(BABYLON || (BABYLON = {}));
  3199. var BABYLON;
  3200. (function (BABYLON) {
  3201. var Database = (function () {
  3202. function Database(urlToScene, callbackManifestChecked) {
  3203. // Handling various flavors of prefixed version of IndexedDB
  3204. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3205. this.callbackManifestChecked = callbackManifestChecked;
  3206. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3207. this.db = null;
  3208. this.enableSceneOffline = false;
  3209. this.enableTexturesOffline = false;
  3210. this.manifestVersionFound = 0;
  3211. this.mustUpdateRessources = false;
  3212. this.hasReachedQuota = false;
  3213. if (!Database.IDBStorageEnabled) {
  3214. this.callbackManifestChecked(true);
  3215. }
  3216. else {
  3217. this.checkManifestFile();
  3218. }
  3219. }
  3220. Database.prototype.checkManifestFile = function () {
  3221. var _this = this;
  3222. function noManifestFile() {
  3223. that.enableSceneOffline = false;
  3224. that.enableTexturesOffline = false;
  3225. that.callbackManifestChecked(false);
  3226. }
  3227. var that = this;
  3228. var timeStampUsed = false;
  3229. var manifestURL = this.currentSceneUrl + ".manifest";
  3230. var xhr = new XMLHttpRequest();
  3231. if (navigator.onLine) {
  3232. // Adding a timestamp to by-pass browsers' cache
  3233. timeStampUsed = true;
  3234. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3235. }
  3236. xhr.open("GET", manifestURL, true);
  3237. xhr.addEventListener("load", function () {
  3238. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3239. try {
  3240. var manifestFile = JSON.parse(xhr.response);
  3241. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3242. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3243. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3244. _this.manifestVersionFound = manifestFile.version;
  3245. }
  3246. if (_this.callbackManifestChecked) {
  3247. _this.callbackManifestChecked(true);
  3248. }
  3249. }
  3250. catch (ex) {
  3251. noManifestFile();
  3252. }
  3253. }
  3254. else {
  3255. noManifestFile();
  3256. }
  3257. }, false);
  3258. xhr.addEventListener("error", function (event) {
  3259. if (timeStampUsed) {
  3260. timeStampUsed = false;
  3261. // Let's retry without the timeStamp
  3262. // It could fail when coupled with HTML5 Offline API
  3263. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3264. xhr.open("GET", retryManifestURL, true);
  3265. xhr.send();
  3266. }
  3267. else {
  3268. noManifestFile();
  3269. }
  3270. }, false);
  3271. try {
  3272. xhr.send();
  3273. }
  3274. catch (ex) {
  3275. BABYLON.Tools.Error("Error on XHR send request.");
  3276. that.callbackManifestChecked(false);
  3277. }
  3278. };
  3279. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3280. var _this = this;
  3281. function handleError() {
  3282. that.isSupported = false;
  3283. if (errorCallback)
  3284. errorCallback();
  3285. }
  3286. var that = this;
  3287. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3288. // Your browser doesn't support IndexedDB
  3289. this.isSupported = false;
  3290. if (errorCallback)
  3291. errorCallback();
  3292. }
  3293. else {
  3294. // If the DB hasn't been opened or created yet
  3295. if (!this.db) {
  3296. this.hasReachedQuota = false;
  3297. this.isSupported = true;
  3298. var request = this.idbFactory.open("babylonjs", 1);
  3299. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3300. request.onerror = function (event) {
  3301. handleError();
  3302. };
  3303. // executes when a version change transaction cannot complete due to other active transactions
  3304. request.onblocked = function (event) {
  3305. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3306. handleError();
  3307. };
  3308. // DB has been opened successfully
  3309. request.onsuccess = function (event) {
  3310. _this.db = request.result;
  3311. successCallback();
  3312. };
  3313. // Initialization of the DB. Creating Scenes & Textures stores
  3314. request.onupgradeneeded = function (event) {
  3315. _this.db = (event.target).result;
  3316. try {
  3317. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3318. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3319. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3323. handleError();
  3324. }
  3325. };
  3326. }
  3327. else {
  3328. if (successCallback)
  3329. successCallback();
  3330. }
  3331. }
  3332. };
  3333. Database.prototype.loadImageFromDB = function (url, image) {
  3334. var _this = this;
  3335. var completeURL = Database.ReturnFullUrlLocation(url);
  3336. var saveAndLoadImage = function () {
  3337. if (!_this.hasReachedQuota && _this.db !== null) {
  3338. // the texture is not yet in the DB, let's try to save it
  3339. _this._saveImageIntoDBAsync(completeURL, image);
  3340. }
  3341. else {
  3342. image.src = url;
  3343. }
  3344. };
  3345. if (!this.mustUpdateRessources) {
  3346. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3347. }
  3348. else {
  3349. saveAndLoadImage();
  3350. }
  3351. };
  3352. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3353. if (this.isSupported && this.db !== null) {
  3354. var texture;
  3355. var transaction = this.db.transaction(["textures"]);
  3356. transaction.onabort = function (event) {
  3357. image.src = url;
  3358. };
  3359. transaction.oncomplete = function (event) {
  3360. var blobTextureURL;
  3361. if (texture) {
  3362. var URL = window.URL || window.webkitURL;
  3363. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3364. image.onerror = function () {
  3365. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3366. image.src = url;
  3367. };
  3368. image.src = blobTextureURL;
  3369. }
  3370. else {
  3371. notInDBCallback();
  3372. }
  3373. };
  3374. var getRequest = transaction.objectStore("textures").get(url);
  3375. getRequest.onsuccess = function (event) {
  3376. texture = (event.target).result;
  3377. };
  3378. getRequest.onerror = function (event) {
  3379. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3380. image.src = url;
  3381. };
  3382. }
  3383. else {
  3384. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3385. image.src = url;
  3386. }
  3387. };
  3388. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3389. var _this = this;
  3390. if (this.isSupported) {
  3391. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3392. var generateBlobUrl = function () {
  3393. var blobTextureURL;
  3394. if (blob) {
  3395. var URL = window.URL || window.webkitURL;
  3396. try {
  3397. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3398. }
  3399. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3400. catch (ex) {
  3401. blobTextureURL = URL.createObjectURL(blob);
  3402. }
  3403. }
  3404. image.src = blobTextureURL;
  3405. };
  3406. if (Database.IsUASupportingBlobStorage) {
  3407. var xhr = new XMLHttpRequest(), blob;
  3408. xhr.open("GET", url, true);
  3409. xhr.responseType = "blob";
  3410. xhr.addEventListener("load", function () {
  3411. if (xhr.status === 200) {
  3412. // Blob as response (XHR2)
  3413. blob = xhr.response;
  3414. var transaction = _this.db.transaction(["textures"], "readwrite");
  3415. // the transaction could abort because of a QuotaExceededError error
  3416. transaction.onabort = function (event) {
  3417. try {
  3418. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3419. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3420. this.hasReachedQuota = true;
  3421. }
  3422. }
  3423. catch (ex) { }
  3424. generateBlobUrl();
  3425. };
  3426. transaction.oncomplete = function (event) {
  3427. generateBlobUrl();
  3428. };
  3429. var newTexture = { textureUrl: url, data: blob };
  3430. try {
  3431. // Put the blob into the dabase
  3432. var addRequest = transaction.objectStore("textures").put(newTexture);
  3433. addRequest.onsuccess = function (event) {
  3434. };
  3435. addRequest.onerror = function (event) {
  3436. generateBlobUrl();
  3437. };
  3438. }
  3439. catch (ex) {
  3440. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3441. if (ex.code === 25) {
  3442. Database.IsUASupportingBlobStorage = false;
  3443. }
  3444. image.src = url;
  3445. }
  3446. }
  3447. else {
  3448. image.src = url;
  3449. }
  3450. }, false);
  3451. xhr.addEventListener("error", function (event) {
  3452. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3453. image.src = url;
  3454. }, false);
  3455. xhr.send();
  3456. }
  3457. else {
  3458. image.src = url;
  3459. }
  3460. }
  3461. else {
  3462. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3463. image.src = url;
  3464. }
  3465. };
  3466. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3467. var _this = this;
  3468. var updateVersion = function (event) {
  3469. // the version is not yet in the DB or we need to update it
  3470. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3471. };
  3472. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3473. };
  3474. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3475. var _this = this;
  3476. if (this.isSupported) {
  3477. var version;
  3478. try {
  3479. var transaction = this.db.transaction(["versions"]);
  3480. transaction.oncomplete = function (event) {
  3481. if (version) {
  3482. // If the version in the JSON file is > than the version in DB
  3483. if (_this.manifestVersionFound > version.data) {
  3484. _this.mustUpdateRessources = true;
  3485. updateInDBCallback();
  3486. }
  3487. else {
  3488. callback(version.data);
  3489. }
  3490. }
  3491. else {
  3492. _this.mustUpdateRessources = true;
  3493. updateInDBCallback();
  3494. }
  3495. };
  3496. transaction.onabort = function (event) {
  3497. callback(-1);
  3498. };
  3499. var getRequest = transaction.objectStore("versions").get(url);
  3500. getRequest.onsuccess = function (event) {
  3501. version = (event.target).result;
  3502. };
  3503. getRequest.onerror = function (event) {
  3504. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3505. callback(-1);
  3506. };
  3507. }
  3508. catch (ex) {
  3509. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3510. callback(-1);
  3511. }
  3512. }
  3513. else {
  3514. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3515. callback(-1);
  3516. }
  3517. };
  3518. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3519. var _this = this;
  3520. if (this.isSupported && !this.hasReachedQuota) {
  3521. try {
  3522. // Open a transaction to the database
  3523. var transaction = this.db.transaction(["versions"], "readwrite");
  3524. // the transaction could abort because of a QuotaExceededError error
  3525. transaction.onabort = function (event) {
  3526. try {
  3527. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3528. _this.hasReachedQuota = true;
  3529. }
  3530. }
  3531. catch (ex) { }
  3532. callback(-1);
  3533. };
  3534. transaction.oncomplete = function (event) {
  3535. callback(_this.manifestVersionFound);
  3536. };
  3537. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3538. // Put the scene into the database
  3539. var addRequest = transaction.objectStore("versions").put(newVersion);
  3540. addRequest.onsuccess = function (event) {
  3541. };
  3542. addRequest.onerror = function (event) {
  3543. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3544. };
  3545. }
  3546. catch (ex) {
  3547. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3548. callback(-1);
  3549. }
  3550. }
  3551. else {
  3552. callback(-1);
  3553. }
  3554. };
  3555. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3556. var _this = this;
  3557. var completeUrl = Database.ReturnFullUrlLocation(url);
  3558. var saveAndLoadFile = function (event) {
  3559. // the scene is not yet in the DB, let's try to save it
  3560. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3561. };
  3562. this._checkVersionFromDB(completeUrl, function (version) {
  3563. if (version !== -1) {
  3564. if (!_this.mustUpdateRessources) {
  3565. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3566. }
  3567. else {
  3568. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3569. }
  3570. }
  3571. else {
  3572. errorCallback();
  3573. }
  3574. });
  3575. };
  3576. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3577. if (this.isSupported) {
  3578. var targetStore;
  3579. if (url.indexOf(".babylon") !== -1) {
  3580. targetStore = "scenes";
  3581. }
  3582. else {
  3583. targetStore = "textures";
  3584. }
  3585. var file;
  3586. var transaction = this.db.transaction([targetStore]);
  3587. transaction.oncomplete = function (event) {
  3588. if (file) {
  3589. callback(file.data);
  3590. }
  3591. else {
  3592. notInDBCallback();
  3593. }
  3594. };
  3595. transaction.onabort = function (event) {
  3596. notInDBCallback();
  3597. };
  3598. var getRequest = transaction.objectStore(targetStore).get(url);
  3599. getRequest.onsuccess = function (event) {
  3600. file = (event.target).result;
  3601. };
  3602. getRequest.onerror = function (event) {
  3603. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3604. notInDBCallback();
  3605. };
  3606. }
  3607. else {
  3608. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3609. callback();
  3610. }
  3611. };
  3612. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3613. var _this = this;
  3614. if (this.isSupported) {
  3615. var targetStore;
  3616. if (url.indexOf(".babylon") !== -1) {
  3617. targetStore = "scenes";
  3618. }
  3619. else {
  3620. targetStore = "textures";
  3621. }
  3622. // Create XHR
  3623. var xhr = new XMLHttpRequest(), fileData;
  3624. xhr.open("GET", url, true);
  3625. if (useArrayBuffer) {
  3626. xhr.responseType = "arraybuffer";
  3627. }
  3628. xhr.onprogress = progressCallback;
  3629. xhr.addEventListener("load", function () {
  3630. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3631. // Blob as response (XHR2)
  3632. //fileData = xhr.responseText;
  3633. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3634. if (!_this.hasReachedQuota) {
  3635. // Open a transaction to the database
  3636. var transaction = _this.db.transaction([targetStore], "readwrite");
  3637. // the transaction could abort because of a QuotaExceededError error
  3638. transaction.onabort = function (event) {
  3639. try {
  3640. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3641. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3642. this.hasReachedQuota = true;
  3643. }
  3644. }
  3645. catch (ex) { }
  3646. callback(fileData);
  3647. };
  3648. transaction.oncomplete = function (event) {
  3649. callback(fileData);
  3650. };
  3651. var newFile;
  3652. if (targetStore === "scenes") {
  3653. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3654. }
  3655. else {
  3656. newFile = { textureUrl: url, data: fileData };
  3657. }
  3658. try {
  3659. // Put the scene into the database
  3660. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3661. addRequest.onsuccess = function (event) {
  3662. };
  3663. addRequest.onerror = function (event) {
  3664. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3665. };
  3666. }
  3667. catch (ex) {
  3668. callback(fileData);
  3669. }
  3670. }
  3671. else {
  3672. callback(fileData);
  3673. }
  3674. }
  3675. else {
  3676. callback();
  3677. }
  3678. }, false);
  3679. xhr.addEventListener("error", function (event) {
  3680. BABYLON.Tools.Error("error on XHR request.");
  3681. callback();
  3682. }, false);
  3683. xhr.send();
  3684. }
  3685. else {
  3686. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3687. callback();
  3688. }
  3689. };
  3690. Database.IsUASupportingBlobStorage = true;
  3691. Database.IDBStorageEnabled = true;
  3692. Database.parseURL = function (url) {
  3693. var a = document.createElement('a');
  3694. a.href = url;
  3695. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3696. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3697. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3698. return absLocation;
  3699. };
  3700. Database.ReturnFullUrlLocation = function (url) {
  3701. if (url.indexOf("http:/") === -1) {
  3702. return (Database.parseURL(window.location.href) + url);
  3703. }
  3704. else {
  3705. return url;
  3706. }
  3707. };
  3708. return Database;
  3709. })();
  3710. BABYLON.Database = Database;
  3711. })(BABYLON || (BABYLON = {}));
  3712. var BABYLON;
  3713. (function (BABYLON) {
  3714. var Internals;
  3715. (function (Internals) {
  3716. /*
  3717. * Based on jsTGALoader - Javascript loader for TGA file
  3718. * By Vincent Thibault
  3719. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3720. */
  3721. var TGATools = (function () {
  3722. function TGATools() {
  3723. }
  3724. TGATools.GetTGAHeader = function (data) {
  3725. var offset = 0;
  3726. var header = {
  3727. id_length: data[offset++],
  3728. colormap_type: data[offset++],
  3729. image_type: data[offset++],
  3730. colormap_index: data[offset++] | data[offset++] << 8,
  3731. colormap_length: data[offset++] | data[offset++] << 8,
  3732. colormap_size: data[offset++],
  3733. origin: [
  3734. data[offset++] | data[offset++] << 8,
  3735. data[offset++] | data[offset++] << 8
  3736. ],
  3737. width: data[offset++] | data[offset++] << 8,
  3738. height: data[offset++] | data[offset++] << 8,
  3739. pixel_size: data[offset++],
  3740. flags: data[offset++]
  3741. };
  3742. return header;
  3743. };
  3744. TGATools.UploadContent = function (gl, data) {
  3745. // Not enough data to contain header ?
  3746. if (data.length < 19) {
  3747. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3748. return;
  3749. }
  3750. // Read Header
  3751. var offset = 18;
  3752. var header = TGATools.GetTGAHeader(data);
  3753. // Assume it's a valid Targa file.
  3754. if (header.id_length + offset > data.length) {
  3755. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3756. return;
  3757. }
  3758. // Skip not needed data
  3759. offset += header.id_length;
  3760. var use_rle = false;
  3761. var use_pal = false;
  3762. var use_rgb = false;
  3763. var use_grey = false;
  3764. // Get some informations.
  3765. switch (header.image_type) {
  3766. case TGATools._TYPE_RLE_INDEXED:
  3767. use_rle = true;
  3768. case TGATools._TYPE_INDEXED:
  3769. use_pal = true;
  3770. break;
  3771. case TGATools._TYPE_RLE_RGB:
  3772. use_rle = true;
  3773. case TGATools._TYPE_RGB:
  3774. use_rgb = true;
  3775. break;
  3776. case TGATools._TYPE_RLE_GREY:
  3777. use_rle = true;
  3778. case TGATools._TYPE_GREY:
  3779. use_grey = true;
  3780. break;
  3781. }
  3782. var pixel_data;
  3783. var numAlphaBits = header.flags & 0xf;
  3784. var pixel_size = header.pixel_size >> 3;
  3785. var pixel_total = header.width * header.height * pixel_size;
  3786. // Read palettes
  3787. var palettes;
  3788. if (use_pal) {
  3789. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3790. }
  3791. // Read LRE
  3792. if (use_rle) {
  3793. pixel_data = new Uint8Array(pixel_total);
  3794. var c, count, i;
  3795. var localOffset = 0;
  3796. var pixels = new Uint8Array(pixel_size);
  3797. while (offset < pixel_total && localOffset < pixel_total) {
  3798. c = data[offset++];
  3799. count = (c & 0x7f) + 1;
  3800. // RLE pixels
  3801. if (c & 0x80) {
  3802. // Bind pixel tmp array
  3803. for (i = 0; i < pixel_size; ++i) {
  3804. pixels[i] = data[offset++];
  3805. }
  3806. // Copy pixel array
  3807. for (i = 0; i < count; ++i) {
  3808. pixel_data.set(pixels, localOffset + i * pixel_size);
  3809. }
  3810. localOffset += pixel_size * count;
  3811. }
  3812. else {
  3813. count *= pixel_size;
  3814. for (i = 0; i < count; ++i) {
  3815. pixel_data[localOffset + i] = data[offset++];
  3816. }
  3817. localOffset += count;
  3818. }
  3819. }
  3820. }
  3821. else {
  3822. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3823. }
  3824. // Load to texture
  3825. var x_start, y_start, x_step, y_step, y_end, x_end;
  3826. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3827. default:
  3828. case TGATools._ORIGIN_UL:
  3829. x_start = 0;
  3830. x_step = 1;
  3831. x_end = header.width;
  3832. y_start = 0;
  3833. y_step = 1;
  3834. y_end = header.height;
  3835. break;
  3836. case TGATools._ORIGIN_BL:
  3837. x_start = 0;
  3838. x_step = 1;
  3839. x_end = header.width;
  3840. y_start = header.height - 1;
  3841. y_step = -1;
  3842. y_end = -1;
  3843. break;
  3844. case TGATools._ORIGIN_UR:
  3845. x_start = header.width - 1;
  3846. x_step = -1;
  3847. x_end = -1;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BR:
  3853. x_start = header.width - 1;
  3854. x_step = -1;
  3855. x_end = -1;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. }
  3861. // Load the specify method
  3862. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3863. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3864. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3865. };
  3866. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3867. var image = pixel_data, colormap = palettes;
  3868. var width = header.width, height = header.height;
  3869. var color, i = 0, x, y;
  3870. var imageData = new Uint8Array(width * height * 4);
  3871. for (y = y_start; y !== y_end; y += y_step) {
  3872. for (x = x_start; x !== x_end; x += x_step, i++) {
  3873. color = image[i];
  3874. imageData[(x + width * y) * 4 + 3] = 255;
  3875. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3876. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3877. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3878. }
  3879. }
  3880. return imageData;
  3881. };
  3882. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3889. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3890. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3891. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3892. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3893. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3905. imageData[(x + width * y) * 4 + 3] = 255;
  3906. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3907. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3908. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3909. }
  3910. }
  3911. return imageData;
  3912. };
  3913. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3914. var image = pixel_data;
  3915. var width = header.width, height = header.height;
  3916. var i = 0, x, y;
  3917. var imageData = new Uint8Array(width * height * 4);
  3918. for (y = y_start; y !== y_end; y += y_step) {
  3919. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3923. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3924. }
  3925. }
  3926. return imageData;
  3927. };
  3928. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3929. var image = pixel_data;
  3930. var width = header.width, height = header.height;
  3931. var color, i = 0, x, y;
  3932. var imageData = new Uint8Array(width * height * 4);
  3933. for (y = y_start; y !== y_end; y += y_step) {
  3934. for (x = x_start; x !== x_end; x += x_step, i++) {
  3935. color = image[i];
  3936. imageData[(x + width * y) * 4 + 0] = color;
  3937. imageData[(x + width * y) * 4 + 1] = color;
  3938. imageData[(x + width * y) * 4 + 2] = color;
  3939. imageData[(x + width * y) * 4 + 3] = 255;
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3951. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3952. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3953. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3954. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3955. }
  3956. }
  3957. return imageData;
  3958. };
  3959. TGATools._TYPE_NO_DATA = 0;
  3960. TGATools._TYPE_INDEXED = 1;
  3961. TGATools._TYPE_RGB = 2;
  3962. TGATools._TYPE_GREY = 3;
  3963. TGATools._TYPE_RLE_INDEXED = 9;
  3964. TGATools._TYPE_RLE_RGB = 10;
  3965. TGATools._TYPE_RLE_GREY = 11;
  3966. TGATools._ORIGIN_MASK = 0x30;
  3967. TGATools._ORIGIN_SHIFT = 0x04;
  3968. TGATools._ORIGIN_BL = 0x00;
  3969. TGATools._ORIGIN_BR = 0x01;
  3970. TGATools._ORIGIN_UL = 0x02;
  3971. TGATools._ORIGIN_UR = 0x03;
  3972. return TGATools;
  3973. })();
  3974. Internals.TGATools = TGATools;
  3975. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3976. })(BABYLON || (BABYLON = {}));
  3977. var BABYLON;
  3978. (function (BABYLON) {
  3979. var SmartArray = (function () {
  3980. function SmartArray(capacity) {
  3981. this.length = 0;
  3982. this._duplicateId = 0;
  3983. this.data = new Array(capacity);
  3984. this._id = SmartArray._GlobalId++;
  3985. }
  3986. SmartArray.prototype.push = function (value) {
  3987. this.data[this.length++] = value;
  3988. if (this.length > this.data.length) {
  3989. this.data.length *= 2;
  3990. }
  3991. if (!value.__smartArrayFlags) {
  3992. value.__smartArrayFlags = {};
  3993. }
  3994. value.__smartArrayFlags[this._id] = this._duplicateId;
  3995. };
  3996. SmartArray.prototype.pushNoDuplicate = function (value) {
  3997. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3998. return;
  3999. }
  4000. this.push(value);
  4001. };
  4002. SmartArray.prototype.sort = function (compareFn) {
  4003. this.data.sort(compareFn);
  4004. };
  4005. SmartArray.prototype.reset = function () {
  4006. this.length = 0;
  4007. this._duplicateId++;
  4008. };
  4009. SmartArray.prototype.concat = function (array) {
  4010. if (array.length === 0) {
  4011. return;
  4012. }
  4013. if (this.length + array.length > this.data.length) {
  4014. this.data.length = (this.length + array.length) * 2;
  4015. }
  4016. for (var index = 0; index < array.length; index++) {
  4017. this.data[this.length++] = (array.data || array)[index];
  4018. }
  4019. };
  4020. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4021. if (array.length === 0) {
  4022. return;
  4023. }
  4024. if (this.length + array.length > this.data.length) {
  4025. this.data.length = (this.length + array.length) * 2;
  4026. }
  4027. for (var index = 0; index < array.length; index++) {
  4028. var item = (array.data || array)[index];
  4029. this.pushNoDuplicate(item);
  4030. }
  4031. };
  4032. SmartArray.prototype.indexOf = function (value) {
  4033. var position = this.data.indexOf(value);
  4034. if (position >= this.length) {
  4035. return -1;
  4036. }
  4037. return position;
  4038. };
  4039. // Statics
  4040. SmartArray._GlobalId = 0;
  4041. return SmartArray;
  4042. })();
  4043. BABYLON.SmartArray = SmartArray;
  4044. })(BABYLON || (BABYLON = {}));
  4045. var BABYLON;
  4046. (function (BABYLON) {
  4047. var SmartCollection = (function () {
  4048. function SmartCollection(capacity) {
  4049. if (capacity === void 0) { capacity = 10; }
  4050. this.count = 0;
  4051. this._initialCapacity = capacity;
  4052. this.items = {};
  4053. this._keys = new Array(this._initialCapacity);
  4054. }
  4055. SmartCollection.prototype.add = function (key, item) {
  4056. if (this.items[key] != undefined) {
  4057. return -1;
  4058. }
  4059. this.items[key] = item;
  4060. //literal keys are always strings, but we keep source type of key in _keys array
  4061. this._keys[this.count++] = key;
  4062. if (this.count > this._keys.length) {
  4063. this._keys.length *= 2;
  4064. }
  4065. return this.count;
  4066. };
  4067. SmartCollection.prototype.remove = function (key) {
  4068. if (this.items[key] == undefined) {
  4069. return -1;
  4070. }
  4071. return this.removeItemOfIndex(this.indexOf(key));
  4072. };
  4073. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4074. if (index < this.count && index > -1) {
  4075. delete this.items[this._keys[index]];
  4076. //here, shifting by hand is better optimised than .splice
  4077. while (index < this.count) {
  4078. this._keys[index] = this._keys[index + 1];
  4079. index++;
  4080. }
  4081. }
  4082. else {
  4083. return -1;
  4084. }
  4085. return --this.count;
  4086. };
  4087. SmartCollection.prototype.indexOf = function (key) {
  4088. for (var i = 0; i !== this.count; i++) {
  4089. if (this._keys[i] === key) {
  4090. return i;
  4091. }
  4092. }
  4093. return -1;
  4094. };
  4095. SmartCollection.prototype.item = function (key) {
  4096. return this.items[key];
  4097. };
  4098. SmartCollection.prototype.getAllKeys = function () {
  4099. if (this.count > 0) {
  4100. var keys = new Array(this.count);
  4101. for (var i = 0; i < this.count; i++) {
  4102. keys[i] = this._keys[i];
  4103. }
  4104. return keys;
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getKeyByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this._keys[index];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.getItemByIndex = function (index) {
  4119. if (index < this.count && index > -1) {
  4120. return this.items[this._keys[index]];
  4121. }
  4122. else {
  4123. return undefined;
  4124. }
  4125. };
  4126. SmartCollection.prototype.empty = function () {
  4127. if (this.count > 0) {
  4128. this.count = 0;
  4129. this.items = {};
  4130. this._keys = new Array(this._initialCapacity);
  4131. }
  4132. };
  4133. SmartCollection.prototype.forEach = function (block) {
  4134. var key;
  4135. for (key in this.items) {
  4136. if (this.items.hasOwnProperty(key)) {
  4137. block(this.items[key]);
  4138. }
  4139. }
  4140. };
  4141. return SmartCollection;
  4142. })();
  4143. BABYLON.SmartCollection = SmartCollection;
  4144. })(BABYLON || (BABYLON = {}));
  4145. var BABYLON;
  4146. (function (BABYLON) {
  4147. // Screenshots
  4148. var screenshotCanvas;
  4149. var cloneValue = function (source, destinationObject) {
  4150. if (!source)
  4151. return null;
  4152. if (source instanceof BABYLON.Mesh) {
  4153. return null;
  4154. }
  4155. if (source instanceof BABYLON.SubMesh) {
  4156. return source.clone(destinationObject);
  4157. }
  4158. else if (source.clone) {
  4159. return source.clone();
  4160. }
  4161. return null;
  4162. };
  4163. var Tools = (function () {
  4164. function Tools() {
  4165. }
  4166. Tools.Instantiate = function (className) {
  4167. var arr = className.split(".");
  4168. var fn = (window || this);
  4169. for (var i = 0, len = arr.length; i < len; i++) {
  4170. fn = fn[arr[i]];
  4171. }
  4172. if (typeof fn !== "function") {
  4173. return null;
  4174. }
  4175. return fn;
  4176. };
  4177. Tools.ToHex = function (i) {
  4178. var str = i.toString(16);
  4179. if (i <= 15) {
  4180. return ("0" + str).toUpperCase();
  4181. }
  4182. return str.toUpperCase();
  4183. };
  4184. Tools.SetImmediate = function (action) {
  4185. if (window.setImmediate) {
  4186. window.setImmediate(action);
  4187. }
  4188. else {
  4189. setTimeout(action, 1);
  4190. }
  4191. };
  4192. Tools.IsExponentOfTwo = function (value) {
  4193. var count = 1;
  4194. do {
  4195. count *= 2;
  4196. } while (count < value);
  4197. return count === value;
  4198. };
  4199. Tools.GetExponentOfTwo = function (value, max) {
  4200. var count = 1;
  4201. do {
  4202. count *= 2;
  4203. } while (count < value);
  4204. if (count > max)
  4205. count = max;
  4206. return count;
  4207. };
  4208. Tools.GetFilename = function (path) {
  4209. var index = path.lastIndexOf("/");
  4210. if (index < 0)
  4211. return path;
  4212. return path.substring(index + 1);
  4213. };
  4214. Tools.GetDOMTextContent = function (element) {
  4215. var result = "";
  4216. var child = element.firstChild;
  4217. while (child) {
  4218. if (child.nodeType === 3) {
  4219. result += child.textContent;
  4220. }
  4221. child = child.nextSibling;
  4222. }
  4223. return result;
  4224. };
  4225. Tools.ToDegrees = function (angle) {
  4226. return angle * 180 / Math.PI;
  4227. };
  4228. Tools.ToRadians = function (angle) {
  4229. return angle * Math.PI / 180;
  4230. };
  4231. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4232. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4233. var output = "";
  4234. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4235. var i = 0;
  4236. var bytes = new Uint8Array(buffer);
  4237. while (i < bytes.length) {
  4238. chr1 = bytes[i++];
  4239. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4240. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4241. enc1 = chr1 >> 2;
  4242. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4243. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4244. enc4 = chr3 & 63;
  4245. if (isNaN(chr2)) {
  4246. enc3 = enc4 = 64;
  4247. }
  4248. else if (isNaN(chr3)) {
  4249. enc4 = 64;
  4250. }
  4251. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4252. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4253. }
  4254. return "data:image/png;base64," + output;
  4255. };
  4256. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4257. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4258. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4259. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4260. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4261. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4262. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4263. }
  4264. return {
  4265. minimum: minimum,
  4266. maximum: maximum
  4267. };
  4268. };
  4269. Tools.ExtractMinAndMax = function (positions, start, count) {
  4270. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4271. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4272. for (var index = start; index < start + count; index++) {
  4273. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4274. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4275. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4276. }
  4277. return {
  4278. minimum: minimum,
  4279. maximum: maximum
  4280. };
  4281. };
  4282. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4283. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4284. return undefined;
  4285. return Array.isArray(obj) ? obj : [obj];
  4286. };
  4287. // Misc.
  4288. Tools.GetPointerPrefix = function () {
  4289. var eventPrefix = "pointer";
  4290. // Check if pointer events are supported
  4291. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4292. eventPrefix = "mouse";
  4293. }
  4294. return eventPrefix;
  4295. };
  4296. Tools.QueueNewFrame = function (func) {
  4297. if (window.requestAnimationFrame)
  4298. window.requestAnimationFrame(func);
  4299. else if (window.msRequestAnimationFrame)
  4300. window.msRequestAnimationFrame(func);
  4301. else if (window.webkitRequestAnimationFrame)
  4302. window.webkitRequestAnimationFrame(func);
  4303. else if (window.mozRequestAnimationFrame)
  4304. window.mozRequestAnimationFrame(func);
  4305. else if (window.oRequestAnimationFrame)
  4306. window.oRequestAnimationFrame(func);
  4307. else {
  4308. window.setTimeout(func, 16);
  4309. }
  4310. };
  4311. Tools.RequestFullscreen = function (element) {
  4312. if (element.requestFullscreen)
  4313. element.requestFullscreen();
  4314. else if (element.msRequestFullscreen)
  4315. element.msRequestFullscreen();
  4316. else if (element.webkitRequestFullscreen)
  4317. element.webkitRequestFullscreen();
  4318. else if (element.mozRequestFullScreen)
  4319. element.mozRequestFullScreen();
  4320. };
  4321. Tools.ExitFullscreen = function () {
  4322. if (document.exitFullscreen) {
  4323. document.exitFullscreen();
  4324. }
  4325. else if (document.mozCancelFullScreen) {
  4326. document.mozCancelFullScreen();
  4327. }
  4328. else if (document.webkitCancelFullScreen) {
  4329. document.webkitCancelFullScreen();
  4330. }
  4331. else if (document.msCancelFullScreen) {
  4332. document.msCancelFullScreen();
  4333. }
  4334. };
  4335. // External files
  4336. Tools.CleanUrl = function (url) {
  4337. url = url.replace(/#/mg, "%23");
  4338. return url;
  4339. };
  4340. Tools.LoadImage = function (url, onload, onerror, database) {
  4341. if (url instanceof ArrayBuffer) {
  4342. url = Tools.EncodeArrayBufferTobase64(url);
  4343. }
  4344. url = Tools.CleanUrl(url);
  4345. var img = new Image();
  4346. if (url.substr(0, 5) !== "data:") {
  4347. if (Tools.CorsBehavior) {
  4348. switch (typeof (Tools.CorsBehavior)) {
  4349. case "function":
  4350. var result = Tools.CorsBehavior(url);
  4351. if (result) {
  4352. img.crossOrigin = result;
  4353. }
  4354. break;
  4355. case "string":
  4356. default:
  4357. img.crossOrigin = Tools.CorsBehavior;
  4358. break;
  4359. }
  4360. }
  4361. }
  4362. img.onload = function () {
  4363. onload(img);
  4364. };
  4365. img.onerror = function (err) {
  4366. Tools.Error("Error while trying to load texture: " + url);
  4367. if (Tools.UseFallbackTexture) {
  4368. 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";
  4369. onload(img);
  4370. }
  4371. else {
  4372. onerror();
  4373. }
  4374. };
  4375. var noIndexedDB = function () {
  4376. img.src = url;
  4377. };
  4378. var loadFromIndexedDB = function () {
  4379. database.loadImageFromDB(url, img);
  4380. };
  4381. //ANY database to do!
  4382. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4383. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4384. }
  4385. else {
  4386. if (url.indexOf("file:") === -1) {
  4387. noIndexedDB();
  4388. }
  4389. else {
  4390. try {
  4391. var textureName = url.substring(5);
  4392. var blobURL;
  4393. try {
  4394. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4395. }
  4396. catch (ex) {
  4397. // Chrome doesn't support oneTimeOnly parameter
  4398. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4399. }
  4400. img.src = blobURL;
  4401. }
  4402. catch (e) {
  4403. img.src = null;
  4404. }
  4405. }
  4406. }
  4407. return img;
  4408. };
  4409. //ANY
  4410. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4411. url = Tools.CleanUrl(url);
  4412. var noIndexedDB = function () {
  4413. var request = new XMLHttpRequest();
  4414. var loadUrl = Tools.BaseUrl + url;
  4415. request.open('GET', loadUrl, true);
  4416. if (useArrayBuffer) {
  4417. request.responseType = "arraybuffer";
  4418. }
  4419. request.onprogress = progressCallBack;
  4420. request.onreadystatechange = function () {
  4421. if (request.readyState === 4) {
  4422. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4423. callback(!useArrayBuffer ? request.responseText : request.response);
  4424. }
  4425. else {
  4426. if (onError) {
  4427. onError();
  4428. }
  4429. else {
  4430. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4431. }
  4432. }
  4433. }
  4434. };
  4435. request.send(null);
  4436. };
  4437. var loadFromIndexedDB = function () {
  4438. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4439. };
  4440. if (url.indexOf("file:") !== -1) {
  4441. var fileName = url.substring(5);
  4442. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4443. }
  4444. else {
  4445. // Caching all files
  4446. if (database && database.enableSceneOffline) {
  4447. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4448. }
  4449. else {
  4450. noIndexedDB();
  4451. }
  4452. }
  4453. };
  4454. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4455. var reader = new FileReader();
  4456. reader.onload = function (e) {
  4457. //target doesn't have result from ts 1.3
  4458. callback(e.target['result']);
  4459. };
  4460. reader.onprogress = progressCallback;
  4461. reader.readAsDataURL(fileToLoad);
  4462. };
  4463. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4464. var reader = new FileReader();
  4465. reader.onerror = function (e) {
  4466. Tools.Log("Error while reading file: " + fileToLoad.name);
  4467. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4468. };
  4469. reader.onload = function (e) {
  4470. //target doesn't have result from ts 1.3
  4471. callback(e.target['result']);
  4472. };
  4473. reader.onprogress = progressCallBack;
  4474. if (!useArrayBuffer) {
  4475. // Asynchronous read
  4476. reader.readAsText(fileToLoad);
  4477. }
  4478. else {
  4479. reader.readAsArrayBuffer(fileToLoad);
  4480. }
  4481. };
  4482. //returns a downloadable url to a file content.
  4483. Tools.FileAsURL = function (content) {
  4484. var fileBlob = new Blob([content]);
  4485. var url = window.URL || window.webkitURL;
  4486. var link = url.createObjectURL(fileBlob);
  4487. return link;
  4488. };
  4489. // Misc.
  4490. Tools.Clamp = function (value, min, max) {
  4491. if (min === void 0) { min = 0; }
  4492. if (max === void 0) { max = 1; }
  4493. return Math.min(max, Math.max(min, value));
  4494. };
  4495. // Returns -1 when value is a negative number and
  4496. // +1 when value is a positive number.
  4497. Tools.Sign = function (value) {
  4498. value = +value; // convert to a number
  4499. if (value === 0 || isNaN(value))
  4500. return value;
  4501. return value > 0 ? 1 : -1;
  4502. };
  4503. Tools.Format = function (value, decimals) {
  4504. if (decimals === void 0) { decimals = 2; }
  4505. return value.toFixed(decimals);
  4506. };
  4507. Tools.CheckExtends = function (v, min, max) {
  4508. if (v.x < min.x)
  4509. min.x = v.x;
  4510. if (v.y < min.y)
  4511. min.y = v.y;
  4512. if (v.z < min.z)
  4513. min.z = v.z;
  4514. if (v.x > max.x)
  4515. max.x = v.x;
  4516. if (v.y > max.y)
  4517. max.y = v.y;
  4518. if (v.z > max.z)
  4519. max.z = v.z;
  4520. };
  4521. Tools.WithinEpsilon = function (a, b, epsilon) {
  4522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4523. var num = a - b;
  4524. return -epsilon <= num && num <= epsilon;
  4525. };
  4526. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4527. for (var prop in source) {
  4528. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4529. continue;
  4530. }
  4531. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4532. continue;
  4533. }
  4534. var sourceValue = source[prop];
  4535. var typeOfSourceValue = typeof sourceValue;
  4536. if (typeOfSourceValue === "function") {
  4537. continue;
  4538. }
  4539. if (typeOfSourceValue === "object") {
  4540. if (sourceValue instanceof Array) {
  4541. destination[prop] = [];
  4542. if (sourceValue.length > 0) {
  4543. if (typeof sourceValue[0] == "object") {
  4544. for (var index = 0; index < sourceValue.length; index++) {
  4545. var clonedValue = cloneValue(sourceValue[index], destination);
  4546. if (destination[prop].indexOf(clonedValue) === -1) {
  4547. destination[prop].push(clonedValue);
  4548. }
  4549. }
  4550. }
  4551. else {
  4552. destination[prop] = sourceValue.slice(0);
  4553. }
  4554. }
  4555. }
  4556. else {
  4557. destination[prop] = cloneValue(sourceValue, destination);
  4558. }
  4559. }
  4560. else {
  4561. destination[prop] = sourceValue;
  4562. }
  4563. }
  4564. };
  4565. Tools.IsEmpty = function (obj) {
  4566. for (var i in obj) {
  4567. return false;
  4568. }
  4569. return true;
  4570. };
  4571. Tools.RegisterTopRootEvents = function (events) {
  4572. for (var index = 0; index < events.length; index++) {
  4573. var event = events[index];
  4574. window.addEventListener(event.name, event.handler, false);
  4575. try {
  4576. if (window.parent) {
  4577. window.parent.addEventListener(event.name, event.handler, false);
  4578. }
  4579. }
  4580. catch (e) {
  4581. }
  4582. }
  4583. };
  4584. Tools.UnregisterTopRootEvents = function (events) {
  4585. for (var index = 0; index < events.length; index++) {
  4586. var event = events[index];
  4587. window.removeEventListener(event.name, event.handler);
  4588. try {
  4589. if (window.parent) {
  4590. window.parent.removeEventListener(event.name, event.handler);
  4591. }
  4592. }
  4593. catch (e) {
  4594. }
  4595. }
  4596. };
  4597. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4598. // Read the contents of the framebuffer
  4599. var numberOfChannelsByLine = width * 4;
  4600. var halfHeight = height / 2;
  4601. //Reading datas from WebGL
  4602. var data = engine.readPixels(0, 0, width, height);
  4603. //To flip image on Y axis.
  4604. for (var i = 0; i < halfHeight; i++) {
  4605. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4606. var currentCell = j + i * numberOfChannelsByLine;
  4607. var targetLine = height - i - 1;
  4608. var targetCell = j + targetLine * numberOfChannelsByLine;
  4609. var temp = data[currentCell];
  4610. data[currentCell] = data[targetCell];
  4611. data[targetCell] = temp;
  4612. }
  4613. }
  4614. // Create a 2D canvas to store the result
  4615. if (!screenshotCanvas) {
  4616. screenshotCanvas = document.createElement('canvas');
  4617. }
  4618. screenshotCanvas.width = width;
  4619. screenshotCanvas.height = height;
  4620. var context = screenshotCanvas.getContext('2d');
  4621. // Copy the pixels to a 2D canvas
  4622. var imageData = context.createImageData(width, height);
  4623. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4624. var castData = imageData.data;
  4625. castData.set(data);
  4626. context.putImageData(imageData, 0, 0);
  4627. var base64Image = screenshotCanvas.toDataURL();
  4628. if (successCallback) {
  4629. successCallback(base64Image);
  4630. }
  4631. else {
  4632. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4633. if (("download" in document.createElement("a"))) {
  4634. var a = window.document.createElement("a");
  4635. a.href = base64Image;
  4636. var date = new Date();
  4637. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4638. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4639. window.document.body.appendChild(a);
  4640. a.addEventListener("click", function () {
  4641. a.parentElement.removeChild(a);
  4642. });
  4643. a.click();
  4644. }
  4645. else {
  4646. var newWindow = window.open("");
  4647. var img = newWindow.document.createElement("img");
  4648. img.src = base64Image;
  4649. newWindow.document.body.appendChild(img);
  4650. }
  4651. }
  4652. };
  4653. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4654. var width;
  4655. var height;
  4656. //If a precision value is specified
  4657. if (size.precision) {
  4658. width = Math.round(engine.getRenderWidth() * size.precision);
  4659. height = Math.round(width / engine.getAspectRatio(camera));
  4660. size = { width: width, height: height };
  4661. }
  4662. else if (size.width && size.height) {
  4663. width = size.width;
  4664. height = size.height;
  4665. }
  4666. else if (size.width && !size.height) {
  4667. width = size.width;
  4668. height = Math.round(width / engine.getAspectRatio(camera));
  4669. size = { width: width, height: height };
  4670. }
  4671. else if (size.height && !size.width) {
  4672. height = size.height;
  4673. width = Math.round(height * engine.getAspectRatio(camera));
  4674. size = { width: width, height: height };
  4675. }
  4676. else if (!isNaN(size)) {
  4677. height = size;
  4678. width = size;
  4679. }
  4680. else {
  4681. Tools.Error("Invalid 'size' parameter !");
  4682. return;
  4683. }
  4684. var scene = camera.getScene();
  4685. var previousCamera = null;
  4686. if (scene.activeCamera !== camera) {
  4687. previousCamera = scene.activeCamera;
  4688. scene.activeCamera = camera;
  4689. }
  4690. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4691. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4692. texture.renderList = scene.meshes;
  4693. texture.onAfterRender = function () {
  4694. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4695. };
  4696. scene.incrementRenderId();
  4697. texture.render(true);
  4698. texture.dispose();
  4699. if (previousCamera) {
  4700. scene.activeCamera = previousCamera;
  4701. }
  4702. camera.getProjectionMatrix(true); // Force cache refresh;
  4703. };
  4704. // XHR response validator for local file scenario
  4705. Tools.ValidateXHRData = function (xhr, dataType) {
  4706. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4707. if (dataType === void 0) { dataType = 7; }
  4708. try {
  4709. if (dataType & 1) {
  4710. if (xhr.responseText && xhr.responseText.length > 0) {
  4711. return true;
  4712. }
  4713. else if (dataType === 1) {
  4714. return false;
  4715. }
  4716. }
  4717. if (dataType & 2) {
  4718. // Check header width and height since there is no "TGA" magic number
  4719. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4720. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 2) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 4) {
  4728. // Check for the "DDS" magic number
  4729. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4730. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4731. return true;
  4732. }
  4733. else {
  4734. return false;
  4735. }
  4736. }
  4737. }
  4738. catch (e) {
  4739. }
  4740. return false;
  4741. };
  4742. Object.defineProperty(Tools, "NoneLogLevel", {
  4743. get: function () {
  4744. return Tools._NoneLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "MessageLogLevel", {
  4750. get: function () {
  4751. return Tools._MessageLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "WarningLogLevel", {
  4757. get: function () {
  4758. return Tools._WarningLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "ErrorLogLevel", {
  4764. get: function () {
  4765. return Tools._ErrorLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "AllLogLevel", {
  4771. get: function () {
  4772. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Tools._AddLogEntry = function (entry) {
  4778. Tools._LogCache = entry + Tools._LogCache;
  4779. if (Tools.OnNewCacheEntry) {
  4780. Tools.OnNewCacheEntry(entry);
  4781. }
  4782. };
  4783. Tools._FormatMessage = function (message) {
  4784. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4785. var date = new Date();
  4786. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4787. };
  4788. Tools._LogDisabled = function (message) {
  4789. // nothing to do
  4790. };
  4791. Tools._LogEnabled = function (message) {
  4792. var formattedMessage = Tools._FormatMessage(message);
  4793. console.log("BJS - " + formattedMessage);
  4794. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4795. Tools._AddLogEntry(entry);
  4796. };
  4797. Tools._WarnDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._WarnEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.warn("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._ErrorDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._ErrorEnabled = function (message) {
  4810. Tools.errorsCount++;
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.error("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Object.defineProperty(Tools, "LogCache", {
  4817. get: function () {
  4818. return Tools._LogCache;
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Tools.ClearLogCache = function () {
  4824. Tools._LogCache = "";
  4825. Tools.errorsCount = 0;
  4826. };
  4827. Object.defineProperty(Tools, "LogLevels", {
  4828. set: function (level) {
  4829. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4830. Tools.Log = Tools._LogEnabled;
  4831. }
  4832. else {
  4833. Tools.Log = Tools._LogDisabled;
  4834. }
  4835. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4836. Tools.Warn = Tools._WarnEnabled;
  4837. }
  4838. else {
  4839. Tools.Warn = Tools._WarnDisabled;
  4840. }
  4841. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4842. Tools.Error = Tools._ErrorEnabled;
  4843. }
  4844. else {
  4845. Tools.Error = Tools._ErrorDisabled;
  4846. }
  4847. },
  4848. enumerable: true,
  4849. configurable: true
  4850. });
  4851. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4852. get: function () {
  4853. return Tools._PerformanceNoneLogLevel;
  4854. },
  4855. enumerable: true,
  4856. configurable: true
  4857. });
  4858. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4859. get: function () {
  4860. return Tools._PerformanceUserMarkLogLevel;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceConsoleLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4873. set: function (level) {
  4874. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4875. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4876. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4877. return;
  4878. }
  4879. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4880. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4881. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4882. return;
  4883. }
  4884. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4885. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4891. };
  4892. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4893. };
  4894. Tools._StartUserMark = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition || !Tools._performance.mark) {
  4897. return;
  4898. }
  4899. Tools._performance.mark(counterName + "-Begin");
  4900. };
  4901. Tools._EndUserMark = function (counterName, condition) {
  4902. if (condition === void 0) { condition = true; }
  4903. if (!condition || !Tools._performance.mark) {
  4904. return;
  4905. }
  4906. Tools._performance.mark(counterName + "-End");
  4907. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4908. };
  4909. Tools._StartPerformanceConsole = function (counterName, condition) {
  4910. if (condition === void 0) { condition = true; }
  4911. if (!condition) {
  4912. return;
  4913. }
  4914. Tools._StartUserMark(counterName, condition);
  4915. if (console.time) {
  4916. console.time(counterName);
  4917. }
  4918. };
  4919. Tools._EndPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._EndUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.timeEnd(counterName);
  4927. }
  4928. };
  4929. Object.defineProperty(Tools, "Now", {
  4930. get: function () {
  4931. if (window.performance && window.performance.now) {
  4932. return window.performance.now();
  4933. }
  4934. return new Date().getTime();
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools.BaseUrl = "";
  4940. Tools.CorsBehavior = "anonymous";
  4941. Tools.UseFallbackTexture = true;
  4942. // Logs
  4943. Tools._NoneLogLevel = 0;
  4944. Tools._MessageLogLevel = 1;
  4945. Tools._WarningLogLevel = 2;
  4946. Tools._ErrorLogLevel = 4;
  4947. Tools._LogCache = "";
  4948. Tools.errorsCount = 0;
  4949. Tools.Log = Tools._LogEnabled;
  4950. Tools.Warn = Tools._WarnEnabled;
  4951. Tools.Error = Tools._ErrorEnabled;
  4952. // Performances
  4953. Tools._PerformanceNoneLogLevel = 0;
  4954. Tools._PerformanceUserMarkLogLevel = 1;
  4955. Tools._PerformanceConsoleLogLevel = 2;
  4956. Tools._performance = window.performance;
  4957. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4958. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4959. return Tools;
  4960. })();
  4961. BABYLON.Tools = Tools;
  4962. /**
  4963. * An implementation of a loop for asynchronous functions.
  4964. */
  4965. var AsyncLoop = (function () {
  4966. /**
  4967. * Constroctor.
  4968. * @param iterations the number of iterations.
  4969. * @param _fn the function to run each iteration
  4970. * @param _successCallback the callback that will be called upon succesful execution
  4971. * @param offset starting offset.
  4972. */
  4973. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4974. if (offset === void 0) { offset = 0; }
  4975. this.iterations = iterations;
  4976. this._fn = _fn;
  4977. this._successCallback = _successCallback;
  4978. this.index = offset - 1;
  4979. this._done = false;
  4980. }
  4981. /**
  4982. * Execute the next iteration. Must be called after the last iteration was finished.
  4983. */
  4984. AsyncLoop.prototype.executeNext = function () {
  4985. if (!this._done) {
  4986. if (this.index + 1 < this.iterations) {
  4987. ++this.index;
  4988. this._fn(this);
  4989. }
  4990. else {
  4991. this.breakLoop();
  4992. }
  4993. }
  4994. };
  4995. /**
  4996. * Break the loop and run the success callback.
  4997. */
  4998. AsyncLoop.prototype.breakLoop = function () {
  4999. this._done = true;
  5000. this._successCallback();
  5001. };
  5002. /**
  5003. * Helper function
  5004. */
  5005. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5006. if (offset === void 0) { offset = 0; }
  5007. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5008. loop.executeNext();
  5009. return loop;
  5010. };
  5011. /**
  5012. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5013. * @param iterations total number of iterations
  5014. * @param syncedIterations number of synchronous iterations in each async iteration.
  5015. * @param fn the function to call each iteration.
  5016. * @param callback a success call back that will be called when iterating stops.
  5017. * @param breakFunction a break condition (optional)
  5018. * @param timeout timeout settings for the setTimeout function. default - 0.
  5019. * @constructor
  5020. */
  5021. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5022. if (timeout === void 0) { timeout = 0; }
  5023. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5024. if (breakFunction && breakFunction())
  5025. loop.breakLoop();
  5026. else {
  5027. setTimeout(function () {
  5028. for (var i = 0; i < syncedIterations; ++i) {
  5029. var iteration = (loop.index * syncedIterations) + i;
  5030. if (iteration >= iterations)
  5031. break;
  5032. fn(iteration);
  5033. if (breakFunction && breakFunction()) {
  5034. loop.breakLoop();
  5035. break;
  5036. }
  5037. }
  5038. loop.executeNext();
  5039. }, timeout);
  5040. }
  5041. }, callback);
  5042. };
  5043. return AsyncLoop;
  5044. })();
  5045. BABYLON.AsyncLoop = AsyncLoop;
  5046. })(BABYLON || (BABYLON = {}));
  5047. var BABYLON;
  5048. (function (BABYLON) {
  5049. var _DepthCullingState = (function () {
  5050. function _DepthCullingState() {
  5051. this._isDepthTestDirty = false;
  5052. this._isDepthMaskDirty = false;
  5053. this._isDepthFuncDirty = false;
  5054. this._isCullFaceDirty = false;
  5055. this._isCullDirty = false;
  5056. this._isZOffsetDirty = false;
  5057. }
  5058. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5059. get: function () {
  5060. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5061. },
  5062. enumerable: true,
  5063. configurable: true
  5064. });
  5065. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5066. get: function () {
  5067. return this._zOffset;
  5068. },
  5069. set: function (value) {
  5070. if (this._zOffset === value) {
  5071. return;
  5072. }
  5073. this._zOffset = value;
  5074. this._isZOffsetDirty = true;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5080. get: function () {
  5081. return this._cullFace;
  5082. },
  5083. set: function (value) {
  5084. if (this._cullFace === value) {
  5085. return;
  5086. }
  5087. this._cullFace = value;
  5088. this._isCullFaceDirty = true;
  5089. },
  5090. enumerable: true,
  5091. configurable: true
  5092. });
  5093. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5094. get: function () {
  5095. return this._cull;
  5096. },
  5097. set: function (value) {
  5098. if (this._cull === value) {
  5099. return;
  5100. }
  5101. this._cull = value;
  5102. this._isCullDirty = true;
  5103. },
  5104. enumerable: true,
  5105. configurable: true
  5106. });
  5107. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5108. get: function () {
  5109. return this._depthFunc;
  5110. },
  5111. set: function (value) {
  5112. if (this._depthFunc === value) {
  5113. return;
  5114. }
  5115. this._depthFunc = value;
  5116. this._isDepthFuncDirty = true;
  5117. },
  5118. enumerable: true,
  5119. configurable: true
  5120. });
  5121. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5122. get: function () {
  5123. return this._depthMask;
  5124. },
  5125. set: function (value) {
  5126. if (this._depthMask === value) {
  5127. return;
  5128. }
  5129. this._depthMask = value;
  5130. this._isDepthMaskDirty = true;
  5131. },
  5132. enumerable: true,
  5133. configurable: true
  5134. });
  5135. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5136. get: function () {
  5137. return this._depthTest;
  5138. },
  5139. set: function (value) {
  5140. if (this._depthTest === value) {
  5141. return;
  5142. }
  5143. this._depthTest = value;
  5144. this._isDepthTestDirty = true;
  5145. },
  5146. enumerable: true,
  5147. configurable: true
  5148. });
  5149. _DepthCullingState.prototype.reset = function () {
  5150. this._depthMask = true;
  5151. this._depthTest = true;
  5152. this._depthFunc = null;
  5153. this._cull = null;
  5154. this._cullFace = null;
  5155. this._zOffset = 0;
  5156. this._isDepthTestDirty = true;
  5157. this._isDepthMaskDirty = true;
  5158. this._isDepthFuncDirty = false;
  5159. this._isCullFaceDirty = false;
  5160. this._isCullDirty = false;
  5161. this._isZOffsetDirty = false;
  5162. };
  5163. _DepthCullingState.prototype.apply = function (gl) {
  5164. if (!this.isDirty) {
  5165. return;
  5166. }
  5167. // Cull
  5168. if (this._isCullDirty) {
  5169. if (this.cull) {
  5170. gl.enable(gl.CULL_FACE);
  5171. }
  5172. else {
  5173. gl.disable(gl.CULL_FACE);
  5174. }
  5175. this._isCullDirty = false;
  5176. }
  5177. // Cull face
  5178. if (this._isCullFaceDirty) {
  5179. gl.cullFace(this.cullFace);
  5180. this._isCullFaceDirty = false;
  5181. }
  5182. // Depth mask
  5183. if (this._isDepthMaskDirty) {
  5184. gl.depthMask(this.depthMask);
  5185. this._isDepthMaskDirty = false;
  5186. }
  5187. // Depth test
  5188. if (this._isDepthTestDirty) {
  5189. if (this.depthTest) {
  5190. gl.enable(gl.DEPTH_TEST);
  5191. }
  5192. else {
  5193. gl.disable(gl.DEPTH_TEST);
  5194. }
  5195. this._isDepthTestDirty = false;
  5196. }
  5197. // Depth func
  5198. if (this._isDepthFuncDirty) {
  5199. gl.depthFunc(this.depthFunc);
  5200. this._isDepthFuncDirty = false;
  5201. }
  5202. // zOffset
  5203. if (this._isZOffsetDirty) {
  5204. if (this.zOffset) {
  5205. gl.enable(gl.POLYGON_OFFSET_FILL);
  5206. gl.polygonOffset(this.zOffset, 0);
  5207. }
  5208. else {
  5209. gl.disable(gl.POLYGON_OFFSET_FILL);
  5210. }
  5211. this._isZOffsetDirty = false;
  5212. }
  5213. };
  5214. return _DepthCullingState;
  5215. })();
  5216. BABYLON._DepthCullingState = _DepthCullingState;
  5217. var _AlphaState = (function () {
  5218. function _AlphaState() {
  5219. this._isAlphaBlendDirty = false;
  5220. this._isBlendFunctionParametersDirty = false;
  5221. this._alphaBlend = false;
  5222. this._blendFunctionParameters = new Array(4);
  5223. }
  5224. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5225. get: function () {
  5226. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5232. get: function () {
  5233. return this._alphaBlend;
  5234. },
  5235. set: function (value) {
  5236. if (this._alphaBlend === value) {
  5237. return;
  5238. }
  5239. this._alphaBlend = value;
  5240. this._isAlphaBlendDirty = true;
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5246. if (this._blendFunctionParameters[0] === value0 &&
  5247. this._blendFunctionParameters[1] === value1 &&
  5248. this._blendFunctionParameters[2] === value2 &&
  5249. this._blendFunctionParameters[3] === value3) {
  5250. return;
  5251. }
  5252. this._blendFunctionParameters[0] = value0;
  5253. this._blendFunctionParameters[1] = value1;
  5254. this._blendFunctionParameters[2] = value2;
  5255. this._blendFunctionParameters[3] = value3;
  5256. this._isBlendFunctionParametersDirty = true;
  5257. };
  5258. _AlphaState.prototype.reset = function () {
  5259. this._alphaBlend = false;
  5260. this._blendFunctionParameters[0] = null;
  5261. this._blendFunctionParameters[1] = null;
  5262. this._blendFunctionParameters[2] = null;
  5263. this._blendFunctionParameters[3] = null;
  5264. this._isAlphaBlendDirty = true;
  5265. this._isBlendFunctionParametersDirty = false;
  5266. };
  5267. _AlphaState.prototype.apply = function (gl) {
  5268. if (!this.isDirty) {
  5269. return;
  5270. }
  5271. // Alpha blend
  5272. if (this._isAlphaBlendDirty) {
  5273. if (this._alphaBlend) {
  5274. gl.enable(gl.BLEND);
  5275. }
  5276. else {
  5277. gl.disable(gl.BLEND);
  5278. }
  5279. this._isAlphaBlendDirty = false;
  5280. }
  5281. // Alpha function
  5282. if (this._isBlendFunctionParametersDirty) {
  5283. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5284. this._isBlendFunctionParametersDirty = false;
  5285. }
  5286. };
  5287. return _AlphaState;
  5288. })();
  5289. BABYLON._AlphaState = _AlphaState;
  5290. var compileShader = function (gl, source, type, defines) {
  5291. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5292. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5293. gl.compileShader(shader);
  5294. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5295. throw new Error(gl.getShaderInfoLog(shader));
  5296. }
  5297. return shader;
  5298. };
  5299. var getWebGLTextureType = function (gl, type) {
  5300. var textureType = gl.UNSIGNED_BYTE;
  5301. if (type === Engine.TEXTURETYPE_FLOAT)
  5302. textureType = gl.FLOAT;
  5303. return textureType;
  5304. };
  5305. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5306. var magFilter = gl.NEAREST;
  5307. var minFilter = gl.NEAREST;
  5308. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5309. magFilter = gl.LINEAR;
  5310. if (generateMipMaps) {
  5311. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5312. }
  5313. else {
  5314. minFilter = gl.LINEAR;
  5315. }
  5316. }
  5317. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5318. magFilter = gl.LINEAR;
  5319. if (generateMipMaps) {
  5320. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5321. }
  5322. else {
  5323. minFilter = gl.LINEAR;
  5324. }
  5325. }
  5326. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5327. magFilter = gl.NEAREST;
  5328. if (generateMipMaps) {
  5329. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5330. }
  5331. else {
  5332. minFilter = gl.NEAREST;
  5333. }
  5334. }
  5335. return {
  5336. min: minFilter,
  5337. mag: magFilter
  5338. };
  5339. };
  5340. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5342. var engine = scene.getEngine();
  5343. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5344. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5345. gl.bindTexture(gl.TEXTURE_2D, texture);
  5346. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5347. texture._baseWidth = width;
  5348. texture._baseHeight = height;
  5349. texture._width = potWidth;
  5350. texture._height = potHeight;
  5351. texture.isReady = true;
  5352. processFunction(potWidth, potHeight);
  5353. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5356. if (!noMipmap && !isCompressed) {
  5357. gl.generateMipmap(gl.TEXTURE_2D);
  5358. }
  5359. gl.bindTexture(gl.TEXTURE_2D, null);
  5360. engine.resetTextureCache();
  5361. scene._removePendingData(texture);
  5362. if (onLoad) {
  5363. onLoad();
  5364. }
  5365. };
  5366. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5367. var img;
  5368. var onload = function () {
  5369. loadedImages[index] = img;
  5370. loadedImages._internalCount++;
  5371. scene._removePendingData(img);
  5372. if (loadedImages._internalCount === 6) {
  5373. onfinish(loadedImages);
  5374. }
  5375. };
  5376. var onerror = function () {
  5377. scene._removePendingData(img);
  5378. };
  5379. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5380. scene._addPendingData(img);
  5381. };
  5382. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5383. var loadedImages = [];
  5384. loadedImages._internalCount = 0;
  5385. for (var index = 0; index < 6; index++) {
  5386. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5387. }
  5388. };
  5389. var EngineCapabilities = (function () {
  5390. function EngineCapabilities() {
  5391. }
  5392. return EngineCapabilities;
  5393. })();
  5394. BABYLON.EngineCapabilities = EngineCapabilities;
  5395. /**
  5396. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5397. */
  5398. var Engine = (function () {
  5399. /**
  5400. * @constructor
  5401. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5402. * @param {boolean} [antialias] - enable antialias
  5403. * @param options - further options to be sent to the getContext function
  5404. */
  5405. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5406. var _this = this;
  5407. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5408. // Public members
  5409. this.isFullscreen = false;
  5410. this.isPointerLock = false;
  5411. this.cullBackFaces = true;
  5412. this.renderEvenInBackground = true;
  5413. // To enable/disable IDB support and avoid XHR on .manifest
  5414. this.enableOfflineSupport = true;
  5415. this.scenes = new Array();
  5416. this._windowIsBackground = false;
  5417. this._webGLVersion = "1.0";
  5418. this._drawCalls = 0;
  5419. this._renderingQueueLaunched = false;
  5420. this._activeRenderLoops = [];
  5421. // FPS
  5422. this.fpsRange = 60;
  5423. this.previousFramesDuration = [];
  5424. this.fps = 60;
  5425. this.deltaTime = 0;
  5426. // States
  5427. this._depthCullingState = new _DepthCullingState();
  5428. this._alphaState = new _AlphaState();
  5429. this._alphaMode = Engine.ALPHA_DISABLE;
  5430. // Cache
  5431. this._loadedTexturesCache = new Array();
  5432. this._maxTextureChannels = 16;
  5433. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5434. this._compiledEffects = {};
  5435. this._uintIndicesCurrentlySet = false;
  5436. this._renderingCanvas = canvas;
  5437. options = options || {};
  5438. options.antialias = antialias;
  5439. if (options.preserveDrawingBuffer === undefined) {
  5440. options.preserveDrawingBuffer = false;
  5441. }
  5442. // GL
  5443. //try {
  5444. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5445. // if (this._gl) {
  5446. // this._webGLVersion = "2.0";
  5447. // }
  5448. //} catch (e) {
  5449. // // Do nothing
  5450. //}
  5451. if (!this._gl) {
  5452. try {
  5453. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5454. }
  5455. catch (e) {
  5456. throw new Error("WebGL not supported");
  5457. }
  5458. }
  5459. if (!this._gl) {
  5460. throw new Error("WebGL not supported");
  5461. }
  5462. this._onBlur = function () {
  5463. _this._windowIsBackground = true;
  5464. };
  5465. this._onFocus = function () {
  5466. _this._windowIsBackground = false;
  5467. };
  5468. window.addEventListener("blur", this._onBlur);
  5469. window.addEventListener("focus", this._onFocus);
  5470. // Viewport
  5471. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5472. this.resize();
  5473. // Caps
  5474. this._caps = new EngineCapabilities();
  5475. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5476. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5477. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5478. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5479. // Infos
  5480. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5481. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5482. if (rendererInfo != null) {
  5483. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5484. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5485. }
  5486. if (!this._glVendor) {
  5487. this._glVendor = "Unknown vendor";
  5488. }
  5489. if (!this._glRenderer) {
  5490. this._glRenderer = "Unknown renderer";
  5491. }
  5492. // Extensions
  5493. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5494. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5495. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5496. 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');
  5497. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5498. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5499. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5500. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5501. this._caps.highPrecisionShaderSupported = true;
  5502. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5503. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5504. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5505. if (this._gl.getShaderPrecisionFormat) {
  5506. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5507. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5508. }
  5509. // Depth buffer
  5510. this.setDepthBuffer(true);
  5511. this.setDepthFunctionToLessOrEqual();
  5512. this.setDepthWrite(true);
  5513. // Fullscreen
  5514. this._onFullscreenChange = function () {
  5515. if (document.fullscreen !== undefined) {
  5516. _this.isFullscreen = document.fullscreen;
  5517. }
  5518. else if (document.mozFullScreen !== undefined) {
  5519. _this.isFullscreen = document.mozFullScreen;
  5520. }
  5521. else if (document.webkitIsFullScreen !== undefined) {
  5522. _this.isFullscreen = document.webkitIsFullScreen;
  5523. }
  5524. else if (document.msIsFullScreen !== undefined) {
  5525. _this.isFullscreen = document.msIsFullScreen;
  5526. }
  5527. // Pointer lock
  5528. if (_this.isFullscreen && _this._pointerLockRequested) {
  5529. canvas.requestPointerLock = canvas.requestPointerLock ||
  5530. canvas.msRequestPointerLock ||
  5531. canvas.mozRequestPointerLock ||
  5532. canvas.webkitRequestPointerLock;
  5533. if (canvas.requestPointerLock) {
  5534. canvas.requestPointerLock();
  5535. }
  5536. }
  5537. };
  5538. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5539. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5540. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5541. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5542. // Pointer lock
  5543. this._onPointerLockChange = function () {
  5544. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5545. document.webkitPointerLockElement === canvas ||
  5546. document.msPointerLockElement === canvas ||
  5547. document.pointerLockElement === canvas);
  5548. };
  5549. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5550. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5551. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5552. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5553. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5554. Engine.audioEngine = new BABYLON.AudioEngine();
  5555. }
  5556. //default loading screen
  5557. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5558. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5559. }
  5560. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5561. get: function () {
  5562. return Engine._ALPHA_DISABLE;
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5568. get: function () {
  5569. return Engine._ALPHA_ONEONE;
  5570. },
  5571. enumerable: true,
  5572. configurable: true
  5573. });
  5574. Object.defineProperty(Engine, "ALPHA_ADD", {
  5575. get: function () {
  5576. return Engine._ALPHA_ADD;
  5577. },
  5578. enumerable: true,
  5579. configurable: true
  5580. });
  5581. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5582. get: function () {
  5583. return Engine._ALPHA_COMBINE;
  5584. },
  5585. enumerable: true,
  5586. configurable: true
  5587. });
  5588. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5589. get: function () {
  5590. return Engine._ALPHA_SUBTRACT;
  5591. },
  5592. enumerable: true,
  5593. configurable: true
  5594. });
  5595. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5596. get: function () {
  5597. return Engine._ALPHA_MULTIPLY;
  5598. },
  5599. enumerable: true,
  5600. configurable: true
  5601. });
  5602. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5603. get: function () {
  5604. return Engine._ALPHA_MAXIMIZED;
  5605. },
  5606. enumerable: true,
  5607. configurable: true
  5608. });
  5609. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5610. get: function () {
  5611. return Engine._DELAYLOADSTATE_NONE;
  5612. },
  5613. enumerable: true,
  5614. configurable: true
  5615. });
  5616. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5617. get: function () {
  5618. return Engine._DELAYLOADSTATE_LOADED;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5624. get: function () {
  5625. return Engine._DELAYLOADSTATE_LOADING;
  5626. },
  5627. enumerable: true,
  5628. configurable: true
  5629. });
  5630. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5631. get: function () {
  5632. return Engine._DELAYLOADSTATE_NOTLOADED;
  5633. },
  5634. enumerable: true,
  5635. configurable: true
  5636. });
  5637. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5638. get: function () {
  5639. return Engine._TEXTUREFORMAT_ALPHA;
  5640. },
  5641. enumerable: true,
  5642. configurable: true
  5643. });
  5644. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5645. get: function () {
  5646. return Engine._TEXTUREFORMAT_LUMINANCE;
  5647. },
  5648. enumerable: true,
  5649. configurable: true
  5650. });
  5651. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5652. get: function () {
  5653. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5654. },
  5655. enumerable: true,
  5656. configurable: true
  5657. });
  5658. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5659. get: function () {
  5660. return Engine._TEXTUREFORMAT_RGB;
  5661. },
  5662. enumerable: true,
  5663. configurable: true
  5664. });
  5665. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5666. get: function () {
  5667. return Engine._TEXTUREFORMAT_RGBA;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5673. get: function () {
  5674. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5675. },
  5676. enumerable: true,
  5677. configurable: true
  5678. });
  5679. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5680. get: function () {
  5681. return Engine._TEXTURETYPE_FLOAT;
  5682. },
  5683. enumerable: true,
  5684. configurable: true
  5685. });
  5686. Object.defineProperty(Engine, "Version", {
  5687. get: function () {
  5688. return "2.4.0-alpha";
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5694. get: function () {
  5695. return this._webGLVersion;
  5696. },
  5697. enumerable: true,
  5698. configurable: true
  5699. });
  5700. Engine.prototype._prepareWorkingCanvas = function () {
  5701. if (this._workingCanvas) {
  5702. return;
  5703. }
  5704. this._workingCanvas = document.createElement("canvas");
  5705. this._workingContext = this._workingCanvas.getContext("2d");
  5706. };
  5707. Engine.prototype.resetTextureCache = function () {
  5708. for (var index = 0; index < this._maxTextureChannels; index++) {
  5709. this._activeTexturesCache[index] = null;
  5710. }
  5711. };
  5712. Engine.prototype.getGlInfo = function () {
  5713. return {
  5714. vendor: this._glVendor,
  5715. renderer: this._glRenderer,
  5716. version: this._glVersion
  5717. };
  5718. };
  5719. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5720. if (useScreen === void 0) { useScreen = false; }
  5721. var viewport = camera.viewport;
  5722. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5723. };
  5724. Engine.prototype.getRenderWidth = function (useScreen) {
  5725. if (useScreen === void 0) { useScreen = false; }
  5726. if (!useScreen && this._currentRenderTarget) {
  5727. return this._currentRenderTarget._width;
  5728. }
  5729. return this._renderingCanvas.width;
  5730. };
  5731. Engine.prototype.getRenderHeight = function (useScreen) {
  5732. if (useScreen === void 0) { useScreen = false; }
  5733. if (!useScreen && this._currentRenderTarget) {
  5734. return this._currentRenderTarget._height;
  5735. }
  5736. return this._renderingCanvas.height;
  5737. };
  5738. Engine.prototype.getRenderingCanvas = function () {
  5739. return this._renderingCanvas;
  5740. };
  5741. Engine.prototype.getRenderingCanvasClientRect = function () {
  5742. return this._renderingCanvas.getBoundingClientRect();
  5743. };
  5744. Engine.prototype.setHardwareScalingLevel = function (level) {
  5745. this._hardwareScalingLevel = level;
  5746. this.resize();
  5747. };
  5748. Engine.prototype.getHardwareScalingLevel = function () {
  5749. return this._hardwareScalingLevel;
  5750. };
  5751. Engine.prototype.getLoadedTexturesCache = function () {
  5752. return this._loadedTexturesCache;
  5753. };
  5754. Engine.prototype.getCaps = function () {
  5755. return this._caps;
  5756. };
  5757. Object.defineProperty(Engine.prototype, "drawCalls", {
  5758. get: function () {
  5759. return this._drawCalls;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. // Methods
  5765. Engine.prototype.resetDrawCalls = function () {
  5766. this._drawCalls = 0;
  5767. };
  5768. Engine.prototype.setDepthFunctionToGreater = function () {
  5769. this._depthCullingState.depthFunc = this._gl.GREATER;
  5770. };
  5771. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5772. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5773. };
  5774. Engine.prototype.setDepthFunctionToLess = function () {
  5775. this._depthCullingState.depthFunc = this._gl.LESS;
  5776. };
  5777. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5778. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5779. };
  5780. /**
  5781. * stop executing a render loop function and remove it from the execution array
  5782. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5783. */
  5784. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5785. if (!renderFunction) {
  5786. this._activeRenderLoops = [];
  5787. return;
  5788. }
  5789. var index = this._activeRenderLoops.indexOf(renderFunction);
  5790. if (index >= 0) {
  5791. this._activeRenderLoops.splice(index, 1);
  5792. }
  5793. };
  5794. Engine.prototype._renderLoop = function () {
  5795. var shouldRender = true;
  5796. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5797. shouldRender = false;
  5798. }
  5799. if (shouldRender) {
  5800. // Start new frame
  5801. this.beginFrame();
  5802. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5803. var renderFunction = this._activeRenderLoops[index];
  5804. renderFunction();
  5805. }
  5806. // Present
  5807. this.endFrame();
  5808. }
  5809. if (this._activeRenderLoops.length > 0) {
  5810. // Register new frame
  5811. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5812. }
  5813. else {
  5814. this._renderingQueueLaunched = false;
  5815. }
  5816. };
  5817. /**
  5818. * Register and execute a render loop. The engine can have more than one render function.
  5819. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5820. * @example
  5821. * engine.runRenderLoop(function () {
  5822. * scene.render()
  5823. * })
  5824. */
  5825. Engine.prototype.runRenderLoop = function (renderFunction) {
  5826. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5827. return;
  5828. }
  5829. this._activeRenderLoops.push(renderFunction);
  5830. if (!this._renderingQueueLaunched) {
  5831. this._renderingQueueLaunched = true;
  5832. this._bindedRenderFunction = this._renderLoop.bind(this);
  5833. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5834. }
  5835. };
  5836. /**
  5837. * Toggle full screen mode.
  5838. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5839. */
  5840. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5841. if (this.isFullscreen) {
  5842. BABYLON.Tools.ExitFullscreen();
  5843. }
  5844. else {
  5845. this._pointerLockRequested = requestPointerLock;
  5846. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5847. }
  5848. };
  5849. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5850. this.applyStates();
  5851. if (backBuffer) {
  5852. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5853. }
  5854. if (depthStencil && this._depthCullingState.depthMask) {
  5855. this._gl.clearDepth(1.0);
  5856. }
  5857. var mode = 0;
  5858. if (backBuffer) {
  5859. mode |= this._gl.COLOR_BUFFER_BIT;
  5860. }
  5861. if (depthStencil && this._depthCullingState.depthMask) {
  5862. mode |= this._gl.DEPTH_BUFFER_BIT;
  5863. }
  5864. this._gl.clear(mode);
  5865. };
  5866. /**
  5867. * Set the WebGL's viewport
  5868. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5869. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5870. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5871. */
  5872. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5873. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5874. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5875. var x = viewport.x || 0;
  5876. var y = viewport.y || 0;
  5877. this._cachedViewport = viewport;
  5878. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5879. };
  5880. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5881. this._cachedViewport = null;
  5882. this._gl.viewport(x, y, width, height);
  5883. };
  5884. Engine.prototype.beginFrame = function () {
  5885. this._measureFps();
  5886. };
  5887. Engine.prototype.endFrame = function () {
  5888. //this.flushFramebuffer();
  5889. };
  5890. /**
  5891. * resize the view according to the canvas' size.
  5892. * @example
  5893. * window.addEventListener("resize", function () {
  5894. * engine.resize();
  5895. * });
  5896. */
  5897. Engine.prototype.resize = function () {
  5898. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5899. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5900. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5901. for (var index = 0; index < this.scenes.length; index++) {
  5902. var scene = this.scenes[index];
  5903. if (scene.debugLayer.isVisible()) {
  5904. scene.debugLayer._syncPositions();
  5905. }
  5906. }
  5907. };
  5908. /**
  5909. * force a specific size of the canvas
  5910. * @param {number} width - the new canvas' width
  5911. * @param {number} height - the new canvas' height
  5912. */
  5913. Engine.prototype.setSize = function (width, height) {
  5914. this._renderingCanvas.width = width;
  5915. this._renderingCanvas.height = height;
  5916. for (var index = 0; index < this.scenes.length; index++) {
  5917. var scene = this.scenes[index];
  5918. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5919. var cam = scene.cameras[camIndex];
  5920. cam._currentRenderId = 0;
  5921. }
  5922. }
  5923. };
  5924. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5925. this._currentRenderTarget = texture;
  5926. var gl = this._gl;
  5927. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5928. if (texture.isCube) {
  5929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5930. }
  5931. else {
  5932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5933. }
  5934. this._gl.viewport(0, 0, texture._width, texture._height);
  5935. this.wipeCaches();
  5936. };
  5937. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5938. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5939. this._currentRenderTarget = null;
  5940. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5941. var gl = this._gl;
  5942. gl.bindTexture(gl.TEXTURE_2D, texture);
  5943. gl.generateMipmap(gl.TEXTURE_2D);
  5944. gl.bindTexture(gl.TEXTURE_2D, null);
  5945. }
  5946. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5947. };
  5948. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5949. if (texture.generateMipMaps) {
  5950. var gl = this._gl;
  5951. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5952. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5953. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5954. }
  5955. };
  5956. Engine.prototype.flushFramebuffer = function () {
  5957. this._gl.flush();
  5958. };
  5959. Engine.prototype.restoreDefaultFramebuffer = function () {
  5960. this._currentRenderTarget = null;
  5961. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5962. this.setViewport(this._cachedViewport);
  5963. this.wipeCaches();
  5964. };
  5965. // VBOs
  5966. Engine.prototype._resetVertexBufferBinding = function () {
  5967. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5968. this._cachedVertexBuffers = null;
  5969. };
  5970. Engine.prototype.createVertexBuffer = function (vertices) {
  5971. var vbo = this._gl.createBuffer();
  5972. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5973. if (vertices instanceof Float32Array) {
  5974. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5975. }
  5976. else {
  5977. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5978. }
  5979. this._resetVertexBufferBinding();
  5980. vbo.references = 1;
  5981. return vbo;
  5982. };
  5983. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5984. var vbo = this._gl.createBuffer();
  5985. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5986. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5987. this._resetVertexBufferBinding();
  5988. vbo.references = 1;
  5989. return vbo;
  5990. };
  5991. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5992. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5993. if (offset === undefined) {
  5994. offset = 0;
  5995. }
  5996. if (vertices instanceof Float32Array) {
  5997. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5998. }
  5999. else {
  6000. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6001. }
  6002. this._resetVertexBufferBinding();
  6003. };
  6004. Engine.prototype._resetIndexBufferBinding = function () {
  6005. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6006. this._cachedIndexBuffer = null;
  6007. };
  6008. Engine.prototype.createIndexBuffer = function (indices) {
  6009. var vbo = this._gl.createBuffer();
  6010. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6011. // Check for 32 bits indices
  6012. var arrayBuffer;
  6013. var need32Bits = false;
  6014. if (this._caps.uintIndices) {
  6015. for (var index = 0; index < indices.length; index++) {
  6016. if (indices[index] > 65535) {
  6017. need32Bits = true;
  6018. break;
  6019. }
  6020. }
  6021. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6022. }
  6023. else {
  6024. arrayBuffer = new Uint16Array(indices);
  6025. }
  6026. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6027. this._resetIndexBufferBinding();
  6028. vbo.references = 1;
  6029. vbo.is32Bits = need32Bits;
  6030. return vbo;
  6031. };
  6032. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6033. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6034. this._cachedVertexBuffers = vertexBuffer;
  6035. this._cachedEffectForVertexBuffers = effect;
  6036. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6037. var offset = 0;
  6038. for (var index = 0; index < vertexDeclaration.length; index++) {
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6042. }
  6043. offset += vertexDeclaration[index] * 4;
  6044. }
  6045. }
  6046. if (this._cachedIndexBuffer !== indexBuffer) {
  6047. this._cachedIndexBuffer = indexBuffer;
  6048. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6049. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6050. }
  6051. };
  6052. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6053. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6054. this._cachedVertexBuffers = vertexBuffers;
  6055. this._cachedEffectForVertexBuffers = effect;
  6056. var attributes = effect.getAttributesNames();
  6057. for (var index = 0; index < attributes.length; index++) {
  6058. var order = effect.getAttributeLocation(index);
  6059. if (order >= 0) {
  6060. var vertexBuffer = vertexBuffers[attributes[index]];
  6061. if (!vertexBuffer) {
  6062. continue;
  6063. }
  6064. var stride = vertexBuffer.getStrideSize();
  6065. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6066. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6067. }
  6068. }
  6069. }
  6070. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6071. this._cachedIndexBuffer = indexBuffer;
  6072. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6073. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6074. }
  6075. };
  6076. Engine.prototype._releaseBuffer = function (buffer) {
  6077. buffer.references--;
  6078. if (buffer.references === 0) {
  6079. this._gl.deleteBuffer(buffer);
  6080. return true;
  6081. }
  6082. return false;
  6083. };
  6084. Engine.prototype.createInstancesBuffer = function (capacity) {
  6085. var buffer = this._gl.createBuffer();
  6086. buffer.capacity = capacity;
  6087. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6088. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6089. return buffer;
  6090. };
  6091. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6092. this._gl.deleteBuffer(buffer);
  6093. };
  6094. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6095. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6097. for (var index = 0; index < 4; index++) {
  6098. var offsetLocation = offsetLocations[index];
  6099. this._gl.enableVertexAttribArray(offsetLocation);
  6100. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6101. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6102. }
  6103. };
  6104. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6105. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6106. for (var index = 0; index < 4; index++) {
  6107. var offsetLocation = offsetLocations[index];
  6108. this._gl.disableVertexAttribArray(offsetLocation);
  6109. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6110. }
  6111. };
  6112. Engine.prototype.applyStates = function () {
  6113. this._depthCullingState.apply(this._gl);
  6114. this._alphaState.apply(this._gl);
  6115. };
  6116. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6117. // Apply states
  6118. this.applyStates();
  6119. this._drawCalls++;
  6120. // Render
  6121. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6122. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6123. if (instancesCount) {
  6124. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6125. return;
  6126. }
  6127. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6128. };
  6129. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6130. // Apply states
  6131. this.applyStates();
  6132. this._drawCalls++;
  6133. if (instancesCount) {
  6134. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6135. return;
  6136. }
  6137. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6138. };
  6139. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6140. // Apply states
  6141. this.applyStates();
  6142. this._drawCalls++;
  6143. if (instancesCount) {
  6144. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6145. return;
  6146. }
  6147. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6148. };
  6149. // Shaders
  6150. Engine.prototype._releaseEffect = function (effect) {
  6151. if (this._compiledEffects[effect._key]) {
  6152. delete this._compiledEffects[effect._key];
  6153. if (effect.getProgram()) {
  6154. this._gl.deleteProgram(effect.getProgram());
  6155. }
  6156. }
  6157. };
  6158. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6159. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6160. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6161. var name = vertex + "+" + fragment + "@" + defines;
  6162. if (this._compiledEffects[name]) {
  6163. return this._compiledEffects[name];
  6164. }
  6165. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6166. effect._key = name;
  6167. this._compiledEffects[name] = effect;
  6168. return effect;
  6169. };
  6170. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6171. if (uniformsNames === void 0) { uniformsNames = []; }
  6172. if (samplers === void 0) { samplers = []; }
  6173. if (defines === void 0) { defines = ""; }
  6174. return this.createEffect({
  6175. vertex: "particles",
  6176. fragmentElement: fragmentName
  6177. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6178. };
  6179. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6180. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6181. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6182. var shaderProgram = this._gl.createProgram();
  6183. this._gl.attachShader(shaderProgram, vertexShader);
  6184. this._gl.attachShader(shaderProgram, fragmentShader);
  6185. this._gl.linkProgram(shaderProgram);
  6186. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6187. if (!linked) {
  6188. var error = this._gl.getProgramInfoLog(shaderProgram);
  6189. if (error) {
  6190. throw new Error(error);
  6191. }
  6192. }
  6193. this._gl.deleteShader(vertexShader);
  6194. this._gl.deleteShader(fragmentShader);
  6195. return shaderProgram;
  6196. };
  6197. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6198. var results = [];
  6199. for (var index = 0; index < uniformsNames.length; index++) {
  6200. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6201. }
  6202. return results;
  6203. };
  6204. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6205. var results = [];
  6206. for (var index = 0; index < attributesNames.length; index++) {
  6207. try {
  6208. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6209. }
  6210. catch (e) {
  6211. results.push(-1);
  6212. }
  6213. }
  6214. return results;
  6215. };
  6216. Engine.prototype.enableEffect = function (effect) {
  6217. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6218. if (effect && effect.onBind) {
  6219. effect.onBind(effect);
  6220. }
  6221. return;
  6222. }
  6223. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6224. // Use program
  6225. this._gl.useProgram(effect.getProgram());
  6226. for (var i in this._vertexAttribArrays) {
  6227. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6228. continue;
  6229. }
  6230. this._vertexAttribArrays[i] = false;
  6231. this._gl.disableVertexAttribArray(i);
  6232. }
  6233. var attributesCount = effect.getAttributesCount();
  6234. for (var index = 0; index < attributesCount; index++) {
  6235. // Attributes
  6236. var order = effect.getAttributeLocation(index);
  6237. if (order >= 0) {
  6238. this._vertexAttribArrays[order] = true;
  6239. this._gl.enableVertexAttribArray(order);
  6240. }
  6241. }
  6242. this._currentEffect = effect;
  6243. if (effect.onBind) {
  6244. effect.onBind(effect);
  6245. }
  6246. };
  6247. Engine.prototype.setArray = function (uniform, array) {
  6248. if (!uniform)
  6249. return;
  6250. this._gl.uniform1fv(uniform, array);
  6251. };
  6252. Engine.prototype.setArray2 = function (uniform, array) {
  6253. if (!uniform || array.length % 2 !== 0)
  6254. return;
  6255. this._gl.uniform2fv(uniform, array);
  6256. };
  6257. Engine.prototype.setArray3 = function (uniform, array) {
  6258. if (!uniform || array.length % 3 !== 0)
  6259. return;
  6260. this._gl.uniform3fv(uniform, array);
  6261. };
  6262. Engine.prototype.setArray4 = function (uniform, array) {
  6263. if (!uniform || array.length % 4 !== 0)
  6264. return;
  6265. this._gl.uniform4fv(uniform, array);
  6266. };
  6267. Engine.prototype.setMatrices = function (uniform, matrices) {
  6268. if (!uniform)
  6269. return;
  6270. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6271. };
  6272. Engine.prototype.setMatrix = function (uniform, matrix) {
  6273. if (!uniform)
  6274. return;
  6275. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6276. };
  6277. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6278. if (!uniform)
  6279. return;
  6280. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6281. };
  6282. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6286. };
  6287. Engine.prototype.setFloat = function (uniform, value) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniform1f(uniform, value);
  6291. };
  6292. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniform2f(uniform, x, y);
  6296. };
  6297. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniform3f(uniform, x, y, z);
  6301. };
  6302. Engine.prototype.setBool = function (uniform, bool) {
  6303. if (!uniform)
  6304. return;
  6305. this._gl.uniform1i(uniform, bool);
  6306. };
  6307. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6308. if (!uniform)
  6309. return;
  6310. this._gl.uniform4f(uniform, x, y, z, w);
  6311. };
  6312. Engine.prototype.setColor3 = function (uniform, color3) {
  6313. if (!uniform)
  6314. return;
  6315. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6316. };
  6317. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6318. if (!uniform)
  6319. return;
  6320. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6321. };
  6322. // States
  6323. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6324. if (zOffset === void 0) { zOffset = 0; }
  6325. if (reverseSide === void 0) { reverseSide = false; }
  6326. // Culling
  6327. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6328. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6329. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6330. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6331. if (culling) {
  6332. this._depthCullingState.cullFace = cullFace;
  6333. this._depthCullingState.cull = true;
  6334. }
  6335. else {
  6336. this._depthCullingState.cull = false;
  6337. }
  6338. }
  6339. // Z offset
  6340. this._depthCullingState.zOffset = zOffset;
  6341. };
  6342. Engine.prototype.setDepthBuffer = function (enable) {
  6343. this._depthCullingState.depthTest = enable;
  6344. };
  6345. Engine.prototype.getDepthWrite = function () {
  6346. return this._depthCullingState.depthMask;
  6347. };
  6348. Engine.prototype.setDepthWrite = function (enable) {
  6349. this._depthCullingState.depthMask = enable;
  6350. };
  6351. Engine.prototype.setColorWrite = function (enable) {
  6352. this._gl.colorMask(enable, enable, enable, enable);
  6353. };
  6354. Engine.prototype.setAlphaMode = function (mode) {
  6355. if (this._alphaMode === mode) {
  6356. return;
  6357. }
  6358. switch (mode) {
  6359. case Engine.ALPHA_DISABLE:
  6360. this.setDepthWrite(true);
  6361. this._alphaState.alphaBlend = false;
  6362. break;
  6363. case Engine.ALPHA_COMBINE:
  6364. this.setDepthWrite(false);
  6365. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6366. this._alphaState.alphaBlend = true;
  6367. break;
  6368. case Engine.ALPHA_ONEONE:
  6369. this.setDepthWrite(false);
  6370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6371. this._alphaState.alphaBlend = true;
  6372. break;
  6373. case Engine.ALPHA_ADD:
  6374. this.setDepthWrite(false);
  6375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6376. this._alphaState.alphaBlend = true;
  6377. break;
  6378. case Engine.ALPHA_SUBTRACT:
  6379. this.setDepthWrite(false);
  6380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6381. this._alphaState.alphaBlend = true;
  6382. break;
  6383. case Engine.ALPHA_MULTIPLY:
  6384. this.setDepthWrite(false);
  6385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6386. this._alphaState.alphaBlend = true;
  6387. break;
  6388. case Engine.ALPHA_MAXIMIZED:
  6389. this.setDepthWrite(false);
  6390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6391. this._alphaState.alphaBlend = true;
  6392. break;
  6393. }
  6394. this._alphaMode = mode;
  6395. };
  6396. Engine.prototype.getAlphaMode = function () {
  6397. return this._alphaMode;
  6398. };
  6399. Engine.prototype.setAlphaTesting = function (enable) {
  6400. this._alphaTest = enable;
  6401. };
  6402. Engine.prototype.getAlphaTesting = function () {
  6403. return this._alphaTest;
  6404. };
  6405. // Textures
  6406. Engine.prototype.wipeCaches = function () {
  6407. this.resetTextureCache();
  6408. this._currentEffect = null;
  6409. this._depthCullingState.reset();
  6410. this._alphaState.reset();
  6411. this._cachedVertexBuffers = null;
  6412. this._cachedIndexBuffer = null;
  6413. this._cachedEffectForVertexBuffers = null;
  6414. };
  6415. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6416. var gl = this._gl;
  6417. gl.bindTexture(gl.TEXTURE_2D, texture);
  6418. var magFilter = gl.NEAREST;
  6419. var minFilter = gl.NEAREST;
  6420. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6421. magFilter = gl.LINEAR;
  6422. minFilter = gl.LINEAR;
  6423. }
  6424. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6425. magFilter = gl.LINEAR;
  6426. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6427. }
  6428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6429. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6430. gl.bindTexture(gl.TEXTURE_2D, null);
  6431. texture.samplingMode = samplingMode;
  6432. };
  6433. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6434. var _this = this;
  6435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6436. if (onLoad === void 0) { onLoad = null; }
  6437. if (onError === void 0) { onError = null; }
  6438. if (buffer === void 0) { buffer = null; }
  6439. var texture = this._gl.createTexture();
  6440. var extension;
  6441. var fromData = false;
  6442. if (url.substr(0, 5) === "data:") {
  6443. fromData = true;
  6444. }
  6445. if (!fromData)
  6446. extension = url.substr(url.length - 4, 4).toLowerCase();
  6447. else {
  6448. var oldUrl = url;
  6449. fromData = oldUrl.split(':');
  6450. url = oldUrl;
  6451. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6452. }
  6453. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6454. var isTGA = (extension === ".tga");
  6455. scene._addPendingData(texture);
  6456. texture.url = url;
  6457. texture.noMipmap = noMipmap;
  6458. texture.references = 1;
  6459. texture.samplingMode = samplingMode;
  6460. this._loadedTexturesCache.push(texture);
  6461. var onerror = function () {
  6462. scene._removePendingData(texture);
  6463. if (onError) {
  6464. onError();
  6465. }
  6466. };
  6467. var callback;
  6468. if (isTGA) {
  6469. callback = function (arrayBuffer) {
  6470. var data = new Uint8Array(arrayBuffer);
  6471. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6472. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6473. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6474. }, onLoad, samplingMode);
  6475. };
  6476. if (!(fromData instanceof Array))
  6477. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6478. callback(arrayBuffer);
  6479. }, onerror, scene.database, true);
  6480. else
  6481. callback(buffer);
  6482. }
  6483. else if (isDDS) {
  6484. callback = function (data) {
  6485. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6486. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6487. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6488. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6489. }, onLoad, samplingMode);
  6490. };
  6491. if (!(fromData instanceof Array))
  6492. BABYLON.Tools.LoadFile(url, function (data) {
  6493. callback(data);
  6494. }, onerror, scene.database, true);
  6495. else
  6496. callback(buffer);
  6497. }
  6498. else {
  6499. var onload = function (img) {
  6500. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6501. var isPot = (img.width === potWidth && img.height === potHeight);
  6502. if (!isPot) {
  6503. _this._prepareWorkingCanvas();
  6504. _this._workingCanvas.width = potWidth;
  6505. _this._workingCanvas.height = potHeight;
  6506. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6507. _this._workingContext.imageSmoothingEnabled = false;
  6508. _this._workingContext.mozImageSmoothingEnabled = false;
  6509. _this._workingContext.oImageSmoothingEnabled = false;
  6510. _this._workingContext.webkitImageSmoothingEnabled = false;
  6511. _this._workingContext.msImageSmoothingEnabled = false;
  6512. }
  6513. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6514. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6515. _this._workingContext.imageSmoothingEnabled = true;
  6516. _this._workingContext.mozImageSmoothingEnabled = true;
  6517. _this._workingContext.oImageSmoothingEnabled = true;
  6518. _this._workingContext.webkitImageSmoothingEnabled = true;
  6519. _this._workingContext.msImageSmoothingEnabled = true;
  6520. }
  6521. }
  6522. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6523. }, onLoad, samplingMode);
  6524. };
  6525. if (!(fromData instanceof Array))
  6526. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6527. else
  6528. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6529. }
  6530. return texture;
  6531. };
  6532. Engine.prototype._getInternalFormat = function (format) {
  6533. var internalFormat = this._gl.RGBA;
  6534. switch (format) {
  6535. case Engine.TEXTUREFORMAT_ALPHA:
  6536. internalFormat = this._gl.ALPHA;
  6537. break;
  6538. case Engine.TEXTUREFORMAT_LUMINANCE:
  6539. internalFormat = this._gl.LUMINANCE;
  6540. break;
  6541. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6542. internalFormat = this._gl.LUMINANCE_ALPHA;
  6543. break;
  6544. case Engine.TEXTUREFORMAT_RGB:
  6545. internalFormat = this._gl.RGB;
  6546. break;
  6547. case Engine.TEXTUREFORMAT_RGBA:
  6548. internalFormat = this._gl.RGBA;
  6549. break;
  6550. }
  6551. return internalFormat;
  6552. };
  6553. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6554. if (compression === void 0) { compression = null; }
  6555. var internalFormat = this._getInternalFormat(format);
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6557. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6558. if (compression) {
  6559. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6560. }
  6561. else {
  6562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6563. }
  6564. if (texture.generateMipMaps) {
  6565. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6566. }
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6568. this.resetTextureCache();
  6569. texture.isReady = true;
  6570. };
  6571. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6572. if (compression === void 0) { compression = null; }
  6573. var texture = this._gl.createTexture();
  6574. texture._baseWidth = width;
  6575. texture._baseHeight = height;
  6576. texture._width = width;
  6577. texture._height = height;
  6578. texture.references = 1;
  6579. this.updateRawTexture(texture, data, format, invertY, compression);
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6581. // Filters
  6582. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6584. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6585. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6586. texture.samplingMode = samplingMode;
  6587. this._loadedTexturesCache.push(texture);
  6588. return texture;
  6589. };
  6590. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6591. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6592. var texture = this._gl.createTexture();
  6593. texture._baseWidth = width;
  6594. texture._baseHeight = height;
  6595. if (forceExponantOfTwo) {
  6596. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6597. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6598. }
  6599. this.resetTextureCache();
  6600. texture._width = width;
  6601. texture._height = height;
  6602. texture.isReady = false;
  6603. texture.generateMipMaps = generateMipMaps;
  6604. texture.references = 1;
  6605. texture.samplingMode = samplingMode;
  6606. this.updateTextureSamplingMode(samplingMode, texture);
  6607. this._loadedTexturesCache.push(texture);
  6608. return texture;
  6609. };
  6610. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6611. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6612. if (texture.isCube) {
  6613. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6614. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6615. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6616. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6617. }
  6618. else {
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6622. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6623. }
  6624. };
  6625. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6627. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6629. if (texture.generateMipMaps) {
  6630. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6631. }
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6633. this.resetTextureCache();
  6634. texture.isReady = true;
  6635. };
  6636. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6637. if (texture._isDisabled) {
  6638. return;
  6639. }
  6640. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6641. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6642. try {
  6643. // Testing video texture support
  6644. if (this._videoTextureSupported === undefined) {
  6645. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6646. if (this._gl.getError() !== 0) {
  6647. this._videoTextureSupported = false;
  6648. }
  6649. else {
  6650. this._videoTextureSupported = true;
  6651. }
  6652. }
  6653. // Copy video through the current working canvas if video texture is not supported
  6654. if (!this._videoTextureSupported) {
  6655. if (!texture._workingCanvas) {
  6656. texture._workingCanvas = document.createElement("canvas");
  6657. texture._workingContext = texture._workingCanvas.getContext("2d");
  6658. texture._workingCanvas.width = texture._width;
  6659. texture._workingCanvas.height = texture._height;
  6660. }
  6661. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6663. }
  6664. else {
  6665. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6666. }
  6667. if (texture.generateMipMaps) {
  6668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6669. }
  6670. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6671. this.resetTextureCache();
  6672. texture.isReady = true;
  6673. }
  6674. catch (ex) {
  6675. // Something unexpected
  6676. // Let's disable the texture
  6677. texture._isDisabled = true;
  6678. }
  6679. };
  6680. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6681. // old version had a "generateMipMaps" arg instead of options.
  6682. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6683. // in the same way, generateDepthBuffer is defaulted to true
  6684. var generateMipMaps = false;
  6685. var generateDepthBuffer = true;
  6686. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6687. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6688. if (options !== undefined) {
  6689. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6690. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6691. type = options.type === undefined ? type : options.type;
  6692. if (options.samplingMode !== undefined) {
  6693. samplingMode = options.samplingMode;
  6694. }
  6695. if (type === Engine.TEXTURETYPE_FLOAT) {
  6696. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6698. }
  6699. }
  6700. var gl = this._gl;
  6701. var texture = gl.createTexture();
  6702. gl.bindTexture(gl.TEXTURE_2D, texture);
  6703. var width = size.width || size;
  6704. var height = size.height || size;
  6705. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6706. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6707. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6708. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6709. }
  6710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6715. var depthBuffer;
  6716. // Create the depth buffer
  6717. if (generateDepthBuffer) {
  6718. depthBuffer = gl.createRenderbuffer();
  6719. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6720. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6721. }
  6722. // Create the framebuffer
  6723. var framebuffer = gl.createFramebuffer();
  6724. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6725. if (generateDepthBuffer) {
  6726. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6727. }
  6728. if (generateMipMaps) {
  6729. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6730. }
  6731. // Unbind
  6732. gl.bindTexture(gl.TEXTURE_2D, null);
  6733. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6734. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6735. texture._framebuffer = framebuffer;
  6736. if (generateDepthBuffer) {
  6737. texture._depthBuffer = depthBuffer;
  6738. }
  6739. texture._width = width;
  6740. texture._height = height;
  6741. texture.isReady = true;
  6742. texture.generateMipMaps = generateMipMaps;
  6743. texture.references = 1;
  6744. texture.samplingMode = samplingMode;
  6745. this.resetTextureCache();
  6746. this._loadedTexturesCache.push(texture);
  6747. return texture;
  6748. };
  6749. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6750. var gl = this._gl;
  6751. var texture = gl.createTexture();
  6752. var generateMipMaps = true;
  6753. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6754. if (options !== undefined) {
  6755. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6756. if (options.samplingMode !== undefined) {
  6757. samplingMode = options.samplingMode;
  6758. }
  6759. }
  6760. texture.isCube = true;
  6761. texture.references = 1;
  6762. texture.generateMipMaps = generateMipMaps;
  6763. texture.references = 1;
  6764. texture.samplingMode = samplingMode;
  6765. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6766. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6767. for (var face = 0; face < 6; face++) {
  6768. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6769. }
  6770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6774. // Create the depth buffer
  6775. var depthBuffer = gl.createRenderbuffer();
  6776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6777. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6778. // Create the framebuffer
  6779. var framebuffer = gl.createFramebuffer();
  6780. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6781. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6782. // Mipmaps
  6783. if (texture.generateMipMaps) {
  6784. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6786. }
  6787. // Unbind
  6788. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6790. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6791. texture._framebuffer = framebuffer;
  6792. texture._depthBuffer = depthBuffer;
  6793. this.resetTextureCache();
  6794. texture._width = size;
  6795. texture._height = size;
  6796. texture.isReady = true;
  6797. return texture;
  6798. };
  6799. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6800. var _this = this;
  6801. var gl = this._gl;
  6802. var texture = gl.createTexture();
  6803. texture.isCube = true;
  6804. texture.url = rootUrl;
  6805. texture.references = 1;
  6806. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6807. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6808. if (isDDS) {
  6809. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6810. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6811. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6812. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6814. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6815. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6816. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6817. }
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6822. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6823. _this.resetTextureCache();
  6824. texture._width = info.width;
  6825. texture._height = info.height;
  6826. texture.isReady = true;
  6827. }, null, null, true);
  6828. }
  6829. else {
  6830. cascadeLoad(rootUrl, scene, function (imgs) {
  6831. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6832. var height = width;
  6833. _this._prepareWorkingCanvas();
  6834. _this._workingCanvas.width = width;
  6835. _this._workingCanvas.height = height;
  6836. var faces = [
  6837. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6838. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6839. ];
  6840. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6841. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6842. for (var index = 0; index < faces.length; index++) {
  6843. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6844. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6845. }
  6846. if (!noMipmap) {
  6847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6848. }
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6853. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6854. _this.resetTextureCache();
  6855. texture._width = width;
  6856. texture._height = height;
  6857. texture.isReady = true;
  6858. }, files);
  6859. }
  6860. return texture;
  6861. };
  6862. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6863. var _this = this;
  6864. var gl = this._gl;
  6865. var texture = gl.createTexture();
  6866. scene._addPendingData(texture);
  6867. texture.isCube = true;
  6868. texture.references = 1;
  6869. texture.url = url;
  6870. var internalFormat = this._getInternalFormat(format);
  6871. var textureType = gl.UNSIGNED_BYTE;
  6872. if (type === Engine.TEXTURETYPE_FLOAT) {
  6873. textureType = gl.FLOAT;
  6874. }
  6875. var width = size;
  6876. var height = width;
  6877. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6878. texture._width = width;
  6879. texture._height = height;
  6880. var onerror = function () {
  6881. scene._removePendingData(texture);
  6882. };
  6883. var internalCallback = function (data) {
  6884. var rgbeDataArrays = callback(data);
  6885. var facesIndex = [
  6886. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6887. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6888. ];
  6889. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6891. for (var index = 0; index < facesIndex.length; index++) {
  6892. var faceData = rgbeDataArrays[index];
  6893. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6894. }
  6895. if (!noMipmap && isPot) {
  6896. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6897. }
  6898. else {
  6899. noMipmap = true;
  6900. }
  6901. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6904. }
  6905. else {
  6906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6908. }
  6909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6911. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6912. texture.isReady = true;
  6913. _this.resetTextureCache();
  6914. scene._removePendingData(texture);
  6915. };
  6916. BABYLON.Tools.LoadFile(url, function (data) {
  6917. internalCallback(data);
  6918. }, onerror, scene.database, true);
  6919. return texture;
  6920. };
  6921. ;
  6922. Engine.prototype._releaseTexture = function (texture) {
  6923. var gl = this._gl;
  6924. if (texture._framebuffer) {
  6925. gl.deleteFramebuffer(texture._framebuffer);
  6926. }
  6927. if (texture._depthBuffer) {
  6928. gl.deleteRenderbuffer(texture._depthBuffer);
  6929. }
  6930. gl.deleteTexture(texture);
  6931. // Unbind channels
  6932. this.unbindAllTextures();
  6933. var index = this._loadedTexturesCache.indexOf(texture);
  6934. if (index !== -1) {
  6935. this._loadedTexturesCache.splice(index, 1);
  6936. }
  6937. };
  6938. Engine.prototype.bindSamplers = function (effect) {
  6939. this._gl.useProgram(effect.getProgram());
  6940. var samplers = effect.getSamplers();
  6941. for (var index = 0; index < samplers.length; index++) {
  6942. var uniform = effect.getUniform(samplers[index]);
  6943. this._gl.uniform1i(uniform, index);
  6944. }
  6945. this._currentEffect = null;
  6946. };
  6947. Engine.prototype._bindTexture = function (channel, texture) {
  6948. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6949. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6950. this._activeTexturesCache[channel] = null;
  6951. };
  6952. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6953. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6954. };
  6955. Engine.prototype.unbindAllTextures = function () {
  6956. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6957. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6958. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6959. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6960. this._activeTexturesCache[channel] = null;
  6961. }
  6962. };
  6963. Engine.prototype.setTexture = function (channel, texture) {
  6964. if (channel < 0) {
  6965. return;
  6966. }
  6967. // Not ready?
  6968. if (!texture || !texture.isReady()) {
  6969. if (this._activeTexturesCache[channel] != null) {
  6970. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6971. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6972. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6973. this._activeTexturesCache[channel] = null;
  6974. }
  6975. return;
  6976. }
  6977. // Video
  6978. var alreadyActivated = false;
  6979. if (texture instanceof BABYLON.VideoTexture) {
  6980. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6981. alreadyActivated = true;
  6982. texture.update();
  6983. }
  6984. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6985. texture.delayLoad();
  6986. return;
  6987. }
  6988. if (this._activeTexturesCache[channel] === texture) {
  6989. return;
  6990. }
  6991. this._activeTexturesCache[channel] = texture;
  6992. var internalTexture = texture.getInternalTexture();
  6993. if (!alreadyActivated) {
  6994. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6995. }
  6996. if (internalTexture.isCube) {
  6997. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6998. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6999. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7000. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7001. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7002. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7003. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7004. }
  7005. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7006. }
  7007. else {
  7008. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7009. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7010. internalTexture._cachedWrapU = texture.wrapU;
  7011. switch (texture.wrapU) {
  7012. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7013. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7014. break;
  7015. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7016. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7017. break;
  7018. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7019. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7020. break;
  7021. }
  7022. }
  7023. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7024. internalTexture._cachedWrapV = texture.wrapV;
  7025. switch (texture.wrapV) {
  7026. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7027. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7028. break;
  7029. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7030. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7031. break;
  7032. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7033. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7034. break;
  7035. }
  7036. }
  7037. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7038. }
  7039. };
  7040. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7041. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7042. var value = texture.anisotropicFilteringLevel;
  7043. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7044. value = 1;
  7045. }
  7046. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7047. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7048. texture._cachedAnisotropicFilteringLevel = value;
  7049. }
  7050. };
  7051. Engine.prototype.readPixels = function (x, y, width, height) {
  7052. var data = new Uint8Array(height * width * 4);
  7053. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7054. return data;
  7055. };
  7056. Engine.prototype.releaseInternalTexture = function (texture) {
  7057. if (!texture) {
  7058. return;
  7059. }
  7060. texture.references--;
  7061. // Final reference ?
  7062. if (texture.references === 0) {
  7063. var texturesCache = this.getLoadedTexturesCache();
  7064. var index = texturesCache.indexOf(texture);
  7065. if (index > -1) {
  7066. texturesCache.splice(index, 1);
  7067. }
  7068. this._releaseTexture(texture);
  7069. }
  7070. };
  7071. // Dispose
  7072. Engine.prototype.dispose = function () {
  7073. this.hideLoadingUI();
  7074. this.stopRenderLoop();
  7075. // Release scenes
  7076. while (this.scenes.length) {
  7077. this.scenes[0].dispose();
  7078. }
  7079. // Release audio engine
  7080. Engine.audioEngine.dispose();
  7081. // Release effects
  7082. for (var name in this._compiledEffects) {
  7083. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7084. }
  7085. // Unbind
  7086. for (var i in this._vertexAttribArrays) {
  7087. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  7088. continue;
  7089. }
  7090. this._gl.disableVertexAttribArray(i);
  7091. }
  7092. this._gl = null;
  7093. // Events
  7094. window.removeEventListener("blur", this._onBlur);
  7095. window.removeEventListener("focus", this._onFocus);
  7096. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7097. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7098. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7099. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7100. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7101. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7102. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7103. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7104. };
  7105. // Loading screen
  7106. Engine.prototype.displayLoadingUI = function () {
  7107. this._loadingScreen.displayLoadingUI();
  7108. };
  7109. Engine.prototype.hideLoadingUI = function () {
  7110. this._loadingScreen.hideLoadingUI();
  7111. };
  7112. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7113. get: function () {
  7114. return this._loadingScreen;
  7115. },
  7116. set: function (loadingScreen) {
  7117. this._loadingScreen = loadingScreen;
  7118. },
  7119. enumerable: true,
  7120. configurable: true
  7121. });
  7122. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7123. set: function (text) {
  7124. this._loadingScreen.loadingUIText = text;
  7125. },
  7126. enumerable: true,
  7127. configurable: true
  7128. });
  7129. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7130. set: function (color) {
  7131. this._loadingScreen.loadingUIBackgroundColor = color;
  7132. },
  7133. enumerable: true,
  7134. configurable: true
  7135. });
  7136. // FPS
  7137. Engine.prototype.getFps = function () {
  7138. return this.fps;
  7139. };
  7140. Engine.prototype.getDeltaTime = function () {
  7141. return this.deltaTime;
  7142. };
  7143. Engine.prototype._measureFps = function () {
  7144. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7145. var length = this.previousFramesDuration.length;
  7146. if (length >= 2) {
  7147. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7148. }
  7149. if (length >= this.fpsRange) {
  7150. if (length > this.fpsRange) {
  7151. this.previousFramesDuration.splice(0, 1);
  7152. length = this.previousFramesDuration.length;
  7153. }
  7154. var sum = 0;
  7155. for (var id = 0; id < length - 1; id++) {
  7156. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7157. }
  7158. this.fps = 1000.0 / (sum / (length - 1));
  7159. }
  7160. };
  7161. // Statics
  7162. Engine.isSupported = function () {
  7163. try {
  7164. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7165. if (navigator.isCocoonJS) {
  7166. return true;
  7167. }
  7168. var tempcanvas = document.createElement("canvas");
  7169. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7170. return gl != null && !!window.WebGLRenderingContext;
  7171. }
  7172. catch (e) {
  7173. return false;
  7174. }
  7175. };
  7176. // Const statics
  7177. Engine._ALPHA_DISABLE = 0;
  7178. Engine._ALPHA_ADD = 1;
  7179. Engine._ALPHA_COMBINE = 2;
  7180. Engine._ALPHA_SUBTRACT = 3;
  7181. Engine._ALPHA_MULTIPLY = 4;
  7182. Engine._ALPHA_MAXIMIZED = 5;
  7183. Engine._ALPHA_ONEONE = 6;
  7184. Engine._DELAYLOADSTATE_NONE = 0;
  7185. Engine._DELAYLOADSTATE_LOADED = 1;
  7186. Engine._DELAYLOADSTATE_LOADING = 2;
  7187. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7188. Engine._TEXTUREFORMAT_ALPHA = 0;
  7189. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7190. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7191. Engine._TEXTUREFORMAT_RGB = 4;
  7192. Engine._TEXTUREFORMAT_RGBA = 5;
  7193. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7194. Engine._TEXTURETYPE_FLOAT = 1;
  7195. // Updatable statics so stick with vars here
  7196. Engine.Epsilon = 0.001;
  7197. Engine.CollisionsEpsilon = 0.001;
  7198. Engine.CodeRepository = "src/";
  7199. Engine.ShadersRepository = "src/Shaders/";
  7200. return Engine;
  7201. })();
  7202. BABYLON.Engine = Engine;
  7203. })(BABYLON || (BABYLON = {}));
  7204. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7205. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7206. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7207. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7208. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7209. };
  7210. var BABYLON;
  7211. (function (BABYLON) {
  7212. /**
  7213. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7214. */
  7215. var Node = (function () {
  7216. /**
  7217. * @constructor
  7218. * @param {string} name - the name and id to be given to this node
  7219. * @param {BABYLON.Scene} the scene this node will be added to
  7220. */
  7221. function Node(name, scene) {
  7222. this.state = "";
  7223. this.animations = new Array();
  7224. this._ranges = {};
  7225. this._childrenFlag = -1;
  7226. this._isEnabled = true;
  7227. this._isReady = true;
  7228. this._currentRenderId = -1;
  7229. this._parentRenderId = -1;
  7230. this.name = name;
  7231. this.id = name;
  7232. this._scene = scene;
  7233. this._initCache();
  7234. }
  7235. Node.prototype.getScene = function () {
  7236. return this._scene;
  7237. };
  7238. Node.prototype.getEngine = function () {
  7239. return this._scene.getEngine();
  7240. };
  7241. // override it in derived class
  7242. Node.prototype.getWorldMatrix = function () {
  7243. return BABYLON.Matrix.Identity();
  7244. };
  7245. // override it in derived class if you add new variables to the cache
  7246. // and call the parent class method
  7247. Node.prototype._initCache = function () {
  7248. this._cache = {};
  7249. this._cache.parent = undefined;
  7250. };
  7251. Node.prototype.updateCache = function (force) {
  7252. if (!force && this.isSynchronized())
  7253. return;
  7254. this._cache.parent = this.parent;
  7255. this._updateCache();
  7256. };
  7257. // override it in derived class if you add new variables to the cache
  7258. // and call the parent class method if !ignoreParentClass
  7259. Node.prototype._updateCache = function (ignoreParentClass) {
  7260. };
  7261. // override it in derived class if you add new variables to the cache
  7262. Node.prototype._isSynchronized = function () {
  7263. return true;
  7264. };
  7265. Node.prototype._markSyncedWithParent = function () {
  7266. this._parentRenderId = this.parent._currentRenderId;
  7267. };
  7268. Node.prototype.isSynchronizedWithParent = function () {
  7269. if (!this.parent) {
  7270. return true;
  7271. }
  7272. if (this._parentRenderId !== this.parent._currentRenderId) {
  7273. return false;
  7274. }
  7275. return this.parent.isSynchronized();
  7276. };
  7277. Node.prototype.isSynchronized = function (updateCache) {
  7278. var check = this.hasNewParent();
  7279. check = check || !this.isSynchronizedWithParent();
  7280. check = check || !this._isSynchronized();
  7281. if (updateCache)
  7282. this.updateCache(true);
  7283. return !check;
  7284. };
  7285. Node.prototype.hasNewParent = function (update) {
  7286. if (this._cache.parent === this.parent)
  7287. return false;
  7288. if (update)
  7289. this._cache.parent = this.parent;
  7290. return true;
  7291. };
  7292. /**
  7293. * Is this node ready to be used/rendered
  7294. * @return {boolean} is it ready
  7295. */
  7296. Node.prototype.isReady = function () {
  7297. return this._isReady;
  7298. };
  7299. /**
  7300. * Is this node enabled.
  7301. * If the node has a parent and is enabled, the parent will be inspected as well.
  7302. * @return {boolean} whether this node (and its parent) is enabled.
  7303. * @see setEnabled
  7304. */
  7305. Node.prototype.isEnabled = function () {
  7306. if (!this._isEnabled) {
  7307. return false;
  7308. }
  7309. if (this.parent) {
  7310. return this.parent.isEnabled();
  7311. }
  7312. return true;
  7313. };
  7314. /**
  7315. * Set the enabled state of this node.
  7316. * @param {boolean} value - the new enabled state
  7317. * @see isEnabled
  7318. */
  7319. Node.prototype.setEnabled = function (value) {
  7320. this._isEnabled = value;
  7321. };
  7322. /**
  7323. * Is this node a descendant of the given node.
  7324. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7325. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7326. * @see parent
  7327. */
  7328. Node.prototype.isDescendantOf = function (ancestor) {
  7329. if (this.parent) {
  7330. if (this.parent === ancestor) {
  7331. return true;
  7332. }
  7333. return this.parent.isDescendantOf(ancestor);
  7334. }
  7335. return false;
  7336. };
  7337. Node.prototype._getDescendants = function (list, results) {
  7338. for (var index = 0; index < list.length; index++) {
  7339. var item = list[index];
  7340. if (item.isDescendantOf(this)) {
  7341. results.push(item);
  7342. }
  7343. }
  7344. };
  7345. /**
  7346. * Will return all nodes that have this node as parent.
  7347. * @return {BABYLON.Node[]} all children nodes of all types.
  7348. */
  7349. Node.prototype.getDescendants = function () {
  7350. var results = [];
  7351. this._getDescendants(this._scene.meshes, results);
  7352. this._getDescendants(this._scene.lights, results);
  7353. this._getDescendants(this._scene.cameras, results);
  7354. return results;
  7355. };
  7356. Node.prototype._setReady = function (state) {
  7357. if (state === this._isReady) {
  7358. return;
  7359. }
  7360. if (!state) {
  7361. this._isReady = false;
  7362. return;
  7363. }
  7364. this._isReady = true;
  7365. if (this.onReady) {
  7366. this.onReady(this);
  7367. }
  7368. };
  7369. Node.prototype.getAnimationByName = function (name) {
  7370. for (var i = 0; i < this.animations.length; i++) {
  7371. var animation = this.animations[i];
  7372. if (animation.name === name) {
  7373. return animation;
  7374. }
  7375. }
  7376. return null;
  7377. };
  7378. Node.prototype.createAnimationRange = function (name, from, to) {
  7379. // check name not already in use
  7380. if (!this._ranges[name]) {
  7381. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7382. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7383. if (this.animations[i]) {
  7384. this.animations[i].createRange(name, from, to);
  7385. }
  7386. }
  7387. }
  7388. };
  7389. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7390. if (deleteFrames === void 0) { deleteFrames = true; }
  7391. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7392. if (this.animations[i]) {
  7393. this.animations[i].deleteRange(name, deleteFrames);
  7394. }
  7395. }
  7396. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7397. };
  7398. Node.prototype.getAnimationRange = function (name) {
  7399. return this._ranges[name];
  7400. };
  7401. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7402. var range = this.getAnimationRange(name);
  7403. if (!range) {
  7404. return null;
  7405. }
  7406. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7407. };
  7408. Node.prototype.serializeAnimationRanges = function () {
  7409. var serializationRanges = [];
  7410. for (var name in this._ranges) {
  7411. var range = {};
  7412. range.name = name;
  7413. range.from = this._ranges[name].from;
  7414. range.to = this._ranges[name].to;
  7415. serializationRanges.push(range);
  7416. }
  7417. return serializationRanges;
  7418. };
  7419. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7420. if (parsedNode.ranges) {
  7421. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7422. var data = parsedNode.ranges[index];
  7423. node.createAnimationRange(data.name, data.from, data.to);
  7424. }
  7425. }
  7426. };
  7427. __decorate([
  7428. BABYLON.serialize()
  7429. ], Node.prototype, "name", void 0);
  7430. __decorate([
  7431. BABYLON.serialize()
  7432. ], Node.prototype, "id", void 0);
  7433. __decorate([
  7434. BABYLON.serialize()
  7435. ], Node.prototype, "uniqueId", void 0);
  7436. __decorate([
  7437. BABYLON.serialize()
  7438. ], Node.prototype, "state", void 0);
  7439. return Node;
  7440. })();
  7441. BABYLON.Node = Node;
  7442. })(BABYLON || (BABYLON = {}));
  7443. var BABYLON;
  7444. (function (BABYLON) {
  7445. var FilesInput = (function () {
  7446. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7447. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7448. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7449. this._engine = p_engine;
  7450. this._canvas = p_canvas;
  7451. this._currentScene = p_scene;
  7452. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7453. this._progressCallback = p_progressCallback;
  7454. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7455. this._textureLoadingCallback = p_textureLoadingCallback;
  7456. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7457. }
  7458. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7459. var _this = this;
  7460. if (p_elementToMonitor) {
  7461. this._elementToMonitor = p_elementToMonitor;
  7462. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7463. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7464. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7465. }
  7466. };
  7467. FilesInput.prototype.renderFunction = function () {
  7468. if (this._additionnalRenderLoopLogicCallback) {
  7469. this._additionnalRenderLoopLogicCallback();
  7470. }
  7471. if (this._currentScene) {
  7472. if (this._textureLoadingCallback) {
  7473. var remaining = this._currentScene.getWaitingItemsCount();
  7474. if (remaining > 0) {
  7475. this._textureLoadingCallback(remaining);
  7476. }
  7477. }
  7478. this._currentScene.render();
  7479. }
  7480. };
  7481. FilesInput.prototype.drag = function (e) {
  7482. e.stopPropagation();
  7483. e.preventDefault();
  7484. };
  7485. FilesInput.prototype.drop = function (eventDrop) {
  7486. eventDrop.stopPropagation();
  7487. eventDrop.preventDefault();
  7488. this.loadFiles(eventDrop);
  7489. };
  7490. FilesInput.prototype.loadFiles = function (event) {
  7491. if (this._startingProcessingFilesCallback)
  7492. this._startingProcessingFilesCallback();
  7493. // Handling data transfer via drag'n'drop
  7494. if (event && event.dataTransfer && event.dataTransfer.files) {
  7495. this._filesToLoad = event.dataTransfer.files;
  7496. }
  7497. // Handling files from input files
  7498. if (event && event.target && event.target.files) {
  7499. this._filesToLoad = event.target.files;
  7500. }
  7501. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7502. for (var i = 0; i < this._filesToLoad.length; i++) {
  7503. switch (this._filesToLoad[i].type) {
  7504. case "image/jpeg":
  7505. case "image/png":
  7506. case "image/bmp":
  7507. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7508. break;
  7509. case "image/targa":
  7510. case "image/vnd.ms-dds":
  7511. case "audio/wav":
  7512. case "audio/x-wav":
  7513. case "audio/mp3":
  7514. case "audio/mpeg":
  7515. case "audio/mpeg3":
  7516. case "audio/x-mpeg-3":
  7517. case "audio/ogg":
  7518. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7519. break;
  7520. default:
  7521. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7522. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7523. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7524. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7525. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7526. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7527. this._sceneFileToLoad = this._filesToLoad[i];
  7528. }
  7529. break;
  7530. }
  7531. }
  7532. this.reload();
  7533. }
  7534. };
  7535. FilesInput.prototype.reload = function () {
  7536. var _this = this;
  7537. var that = this;
  7538. // If a ".babylon" file has been provided
  7539. if (this._sceneFileToLoad) {
  7540. if (this._currentScene) {
  7541. if (BABYLON.Tools.errorsCount > 0) {
  7542. BABYLON.Tools.ClearLogCache();
  7543. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7544. }
  7545. this._engine.stopRenderLoop();
  7546. this._currentScene.dispose();
  7547. }
  7548. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7549. that._currentScene = newScene;
  7550. // Wait for textures and shaders to be ready
  7551. that._currentScene.executeWhenReady(function () {
  7552. // Attach camera to canvas inputs
  7553. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7554. that._currentScene.createDefaultCameraOrLight();
  7555. }
  7556. that._currentScene.activeCamera.attachControl(that._canvas);
  7557. if (that._sceneLoadedCallback) {
  7558. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7559. }
  7560. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7561. });
  7562. }, function (progress) {
  7563. if (_this._progressCallback) {
  7564. _this._progressCallback(progress);
  7565. }
  7566. });
  7567. }
  7568. else {
  7569. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7570. }
  7571. };
  7572. FilesInput.FilesTextures = new Array();
  7573. FilesInput.FilesToLoad = new Array();
  7574. return FilesInput;
  7575. })();
  7576. BABYLON.FilesInput = FilesInput;
  7577. })(BABYLON || (BABYLON = {}));
  7578. var BABYLON;
  7579. (function (BABYLON) {
  7580. var IntersectionInfo = (function () {
  7581. function IntersectionInfo(bu, bv, distance) {
  7582. this.bu = bu;
  7583. this.bv = bv;
  7584. this.distance = distance;
  7585. this.faceId = 0;
  7586. this.subMeshId = 0;
  7587. }
  7588. return IntersectionInfo;
  7589. })();
  7590. BABYLON.IntersectionInfo = IntersectionInfo;
  7591. var PickingInfo = (function () {
  7592. function PickingInfo() {
  7593. this.hit = false;
  7594. this.distance = 0;
  7595. this.pickedPoint = null;
  7596. this.pickedMesh = null;
  7597. this.bu = 0;
  7598. this.bv = 0;
  7599. this.faceId = -1;
  7600. this.subMeshId = 0;
  7601. this.pickedSprite = null;
  7602. }
  7603. // Methods
  7604. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7605. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7606. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7607. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7608. return null;
  7609. }
  7610. var indices = this.pickedMesh.getIndices();
  7611. var result;
  7612. if (useVerticesNormals) {
  7613. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7614. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7615. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7616. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7617. normal0 = normal0.scale(this.bu);
  7618. normal1 = normal1.scale(this.bv);
  7619. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7620. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7621. }
  7622. else {
  7623. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7624. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7625. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7626. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7627. var p1p2 = vertex1.subtract(vertex2);
  7628. var p3p2 = vertex3.subtract(vertex2);
  7629. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7630. }
  7631. if (useWorldCoordinates) {
  7632. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7633. }
  7634. return BABYLON.Vector3.Normalize(result);
  7635. };
  7636. PickingInfo.prototype.getTextureCoordinates = function () {
  7637. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7638. return null;
  7639. }
  7640. var indices = this.pickedMesh.getIndices();
  7641. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7642. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7643. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7644. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7645. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7646. uv1 = uv1.scale(this.bu);
  7647. uv2 = uv2.scale(this.bv);
  7648. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7649. };
  7650. return PickingInfo;
  7651. })();
  7652. BABYLON.PickingInfo = PickingInfo;
  7653. })(BABYLON || (BABYLON = {}));
  7654. var BABYLON;
  7655. (function (BABYLON) {
  7656. var BoundingSphere = (function () {
  7657. function BoundingSphere(minimum, maximum) {
  7658. this.minimum = minimum;
  7659. this.maximum = maximum;
  7660. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7661. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7662. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7663. this.radius = distance * 0.5;
  7664. this.centerWorld = BABYLON.Vector3.Zero();
  7665. this._update(BABYLON.Matrix.Identity());
  7666. }
  7667. // Methods
  7668. BoundingSphere.prototype._update = function (world) {
  7669. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7670. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7671. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7672. };
  7673. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7674. for (var i = 0; i < 6; i++) {
  7675. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7676. return false;
  7677. }
  7678. return true;
  7679. };
  7680. BoundingSphere.prototype.intersectsPoint = function (point) {
  7681. var x = this.centerWorld.x - point.x;
  7682. var y = this.centerWorld.y - point.y;
  7683. var z = this.centerWorld.z - point.z;
  7684. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7685. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7686. return false;
  7687. return true;
  7688. };
  7689. // Statics
  7690. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7691. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7692. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7693. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7694. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7695. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7696. return false;
  7697. return true;
  7698. };
  7699. return BoundingSphere;
  7700. })();
  7701. BABYLON.BoundingSphere = BoundingSphere;
  7702. })(BABYLON || (BABYLON = {}));
  7703. var BABYLON;
  7704. (function (BABYLON) {
  7705. var BoundingBox = (function () {
  7706. function BoundingBox(minimum, maximum) {
  7707. this.minimum = minimum;
  7708. this.maximum = maximum;
  7709. this.vectors = new Array();
  7710. this.vectorsWorld = new Array();
  7711. // Bounding vectors
  7712. this.vectors.push(this.minimum.clone());
  7713. this.vectors.push(this.maximum.clone());
  7714. this.vectors.push(this.minimum.clone());
  7715. this.vectors[2].x = this.maximum.x;
  7716. this.vectors.push(this.minimum.clone());
  7717. this.vectors[3].y = this.maximum.y;
  7718. this.vectors.push(this.minimum.clone());
  7719. this.vectors[4].z = this.maximum.z;
  7720. this.vectors.push(this.maximum.clone());
  7721. this.vectors[5].z = this.minimum.z;
  7722. this.vectors.push(this.maximum.clone());
  7723. this.vectors[6].x = this.minimum.x;
  7724. this.vectors.push(this.maximum.clone());
  7725. this.vectors[7].y = this.minimum.y;
  7726. // OBB
  7727. this.center = this.maximum.add(this.minimum).scale(0.5);
  7728. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7729. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7730. // World
  7731. for (var index = 0; index < this.vectors.length; index++) {
  7732. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7733. }
  7734. this.minimumWorld = BABYLON.Vector3.Zero();
  7735. this.maximumWorld = BABYLON.Vector3.Zero();
  7736. this._update(BABYLON.Matrix.Identity());
  7737. }
  7738. // Methods
  7739. BoundingBox.prototype.getWorldMatrix = function () {
  7740. return this._worldMatrix;
  7741. };
  7742. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7743. this._worldMatrix.copyFrom(matrix);
  7744. return this;
  7745. };
  7746. BoundingBox.prototype._update = function (world) {
  7747. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7748. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7749. for (var index = 0; index < this.vectors.length; index++) {
  7750. var v = this.vectorsWorld[index];
  7751. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7752. if (v.x < this.minimumWorld.x)
  7753. this.minimumWorld.x = v.x;
  7754. if (v.y < this.minimumWorld.y)
  7755. this.minimumWorld.y = v.y;
  7756. if (v.z < this.minimumWorld.z)
  7757. this.minimumWorld.z = v.z;
  7758. if (v.x > this.maximumWorld.x)
  7759. this.maximumWorld.x = v.x;
  7760. if (v.y > this.maximumWorld.y)
  7761. this.maximumWorld.y = v.y;
  7762. if (v.z > this.maximumWorld.z)
  7763. this.maximumWorld.z = v.z;
  7764. }
  7765. // OBB
  7766. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7767. this.center.scaleInPlace(0.5);
  7768. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7769. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7770. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7771. this._worldMatrix = world;
  7772. };
  7773. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7774. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7775. };
  7776. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7777. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7778. };
  7779. BoundingBox.prototype.intersectsPoint = function (point) {
  7780. var delta = -BABYLON.Engine.Epsilon;
  7781. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7782. return false;
  7783. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7784. return false;
  7785. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7786. return false;
  7787. return true;
  7788. };
  7789. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7790. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7791. };
  7792. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7793. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7794. return false;
  7795. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7796. return false;
  7797. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7798. return false;
  7799. return true;
  7800. };
  7801. // Statics
  7802. BoundingBox.Intersects = function (box0, box1) {
  7803. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7804. return false;
  7805. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7806. return false;
  7807. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7808. return false;
  7809. return true;
  7810. };
  7811. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7812. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7813. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7814. return (num <= (sphereRadius * sphereRadius));
  7815. };
  7816. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7817. for (var p = 0; p < 6; p++) {
  7818. for (var i = 0; i < 8; i++) {
  7819. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7820. return false;
  7821. }
  7822. }
  7823. }
  7824. return true;
  7825. };
  7826. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7827. for (var p = 0; p < 6; p++) {
  7828. var inCount = 8;
  7829. for (var i = 0; i < 8; i++) {
  7830. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7831. --inCount;
  7832. }
  7833. else {
  7834. break;
  7835. }
  7836. }
  7837. if (inCount === 0)
  7838. return false;
  7839. }
  7840. return true;
  7841. };
  7842. return BoundingBox;
  7843. })();
  7844. BABYLON.BoundingBox = BoundingBox;
  7845. })(BABYLON || (BABYLON = {}));
  7846. var BABYLON;
  7847. (function (BABYLON) {
  7848. var computeBoxExtents = function (axis, box) {
  7849. var p = BABYLON.Vector3.Dot(box.center, axis);
  7850. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7851. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7852. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7853. var r = r0 + r1 + r2;
  7854. return {
  7855. min: p - r,
  7856. max: p + r
  7857. };
  7858. };
  7859. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7860. var axisOverlap = function (axis, box0, box1) {
  7861. var result0 = computeBoxExtents(axis, box0);
  7862. var result1 = computeBoxExtents(axis, box1);
  7863. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7864. };
  7865. var BoundingInfo = (function () {
  7866. function BoundingInfo(minimum, maximum) {
  7867. this.minimum = minimum;
  7868. this.maximum = maximum;
  7869. this._isLocked = false;
  7870. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7871. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7872. }
  7873. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7874. get: function () {
  7875. return this._isLocked;
  7876. },
  7877. set: function (value) {
  7878. this._isLocked = value;
  7879. },
  7880. enumerable: true,
  7881. configurable: true
  7882. });
  7883. // Methods
  7884. BoundingInfo.prototype.update = function (world) {
  7885. if (this._isLocked) {
  7886. return;
  7887. }
  7888. this.boundingBox._update(world);
  7889. this.boundingSphere._update(world);
  7890. };
  7891. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7892. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7893. return false;
  7894. return this.boundingBox.isInFrustum(frustumPlanes);
  7895. };
  7896. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7897. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7898. };
  7899. BoundingInfo.prototype._checkCollision = function (collider) {
  7900. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7901. };
  7902. BoundingInfo.prototype.intersectsPoint = function (point) {
  7903. if (!this.boundingSphere.centerWorld) {
  7904. return false;
  7905. }
  7906. if (!this.boundingSphere.intersectsPoint(point)) {
  7907. return false;
  7908. }
  7909. if (!this.boundingBox.intersectsPoint(point)) {
  7910. return false;
  7911. }
  7912. return true;
  7913. };
  7914. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7915. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7916. return false;
  7917. }
  7918. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7919. return false;
  7920. }
  7921. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7922. return false;
  7923. }
  7924. if (!precise) {
  7925. return true;
  7926. }
  7927. var box0 = this.boundingBox;
  7928. var box1 = boundingInfo.boundingBox;
  7929. if (!axisOverlap(box0.directions[0], box0, box1))
  7930. return false;
  7931. if (!axisOverlap(box0.directions[1], box0, box1))
  7932. return false;
  7933. if (!axisOverlap(box0.directions[2], box0, box1))
  7934. return false;
  7935. if (!axisOverlap(box1.directions[0], box0, box1))
  7936. return false;
  7937. if (!axisOverlap(box1.directions[1], box0, box1))
  7938. return false;
  7939. if (!axisOverlap(box1.directions[2], box0, box1))
  7940. return false;
  7941. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7942. return false;
  7943. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7944. return false;
  7945. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7946. return false;
  7947. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7948. return false;
  7949. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7950. return false;
  7951. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7952. return false;
  7953. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7954. return false;
  7955. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7956. return false;
  7957. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7958. return false;
  7959. return true;
  7960. };
  7961. return BoundingInfo;
  7962. })();
  7963. BABYLON.BoundingInfo = BoundingInfo;
  7964. })(BABYLON || (BABYLON = {}));
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. var AbstractMesh = (function (_super) {
  7968. __extends(AbstractMesh, _super);
  7969. // Constructor
  7970. function AbstractMesh(name, scene) {
  7971. var _this = this;
  7972. _super.call(this, name, scene);
  7973. // Properties
  7974. this.definedFacingForward = true; // orientation for POV movement & rotation
  7975. this.position = new BABYLON.Vector3(0, 0, 0);
  7976. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7977. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7978. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7979. this.visibility = 1.0;
  7980. this.alphaIndex = Number.MAX_VALUE;
  7981. this.infiniteDistance = false;
  7982. this.isVisible = true;
  7983. this.isPickable = true;
  7984. this.showBoundingBox = false;
  7985. this.showSubMeshesBoundingBox = false;
  7986. this.onDispose = null;
  7987. this.isBlocker = false;
  7988. this.renderingGroupId = 0;
  7989. this.receiveShadows = false;
  7990. this.renderOutline = false;
  7991. this.outlineColor = BABYLON.Color3.Red();
  7992. this.outlineWidth = 0.02;
  7993. this.renderOverlay = false;
  7994. this.overlayColor = BABYLON.Color3.Red();
  7995. this.overlayAlpha = 0.5;
  7996. this.hasVertexAlpha = false;
  7997. this.useVertexColors = true;
  7998. this.applyFog = true;
  7999. this.computeBonesUsingShaders = true;
  8000. this.scalingDeterminant = 1;
  8001. this.numBoneInfluencers = 4;
  8002. this.useOctreeForRenderingSelection = true;
  8003. this.useOctreeForPicking = true;
  8004. this.useOctreeForCollisions = true;
  8005. this.layerMask = 0x0FFFFFFF;
  8006. this.alwaysSelectAsActiveMesh = false;
  8007. // Physics
  8008. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8009. // Collisions
  8010. this._checkCollisions = false;
  8011. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8012. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8013. this._collider = new BABYLON.Collider();
  8014. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8015. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8016. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8017. // Edges
  8018. this.edgesWidth = 1;
  8019. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8020. // Cache
  8021. this._localWorld = BABYLON.Matrix.Zero();
  8022. this._worldMatrix = BABYLON.Matrix.Zero();
  8023. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8024. this._absolutePosition = BABYLON.Vector3.Zero();
  8025. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8026. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8027. this._isDirty = false;
  8028. this._pivotMatrix = BABYLON.Matrix.Identity();
  8029. this._isDisposed = false;
  8030. this._renderId = 0;
  8031. this._intersectionsInProgress = new Array();
  8032. this._onAfterWorldMatrixUpdate = new Array();
  8033. this._isWorldMatrixFrozen = false;
  8034. this._unIndexed = false;
  8035. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8036. if (collidedMesh === void 0) { collidedMesh = null; }
  8037. //TODO move this to the collision coordinator!
  8038. if (_this.getScene().workerCollisions)
  8039. newPosition.multiplyInPlace(_this._collider.radius);
  8040. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8041. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8042. _this.position.addInPlace(_this._diffPositionForCollisions);
  8043. }
  8044. if (_this.onCollide && collidedMesh) {
  8045. _this.onCollide(collidedMesh);
  8046. }
  8047. if (_this.onCollisionPositionChange) {
  8048. _this.onCollisionPositionChange(_this.position);
  8049. }
  8050. };
  8051. scene.addMesh(this);
  8052. }
  8053. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8054. get: function () {
  8055. return AbstractMesh._BILLBOARDMODE_NONE;
  8056. },
  8057. enumerable: true,
  8058. configurable: true
  8059. });
  8060. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8061. get: function () {
  8062. return AbstractMesh._BILLBOARDMODE_X;
  8063. },
  8064. enumerable: true,
  8065. configurable: true
  8066. });
  8067. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8068. get: function () {
  8069. return AbstractMesh._BILLBOARDMODE_Y;
  8070. },
  8071. enumerable: true,
  8072. configurable: true
  8073. });
  8074. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8075. get: function () {
  8076. return AbstractMesh._BILLBOARDMODE_Z;
  8077. },
  8078. enumerable: true,
  8079. configurable: true
  8080. });
  8081. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8082. get: function () {
  8083. return AbstractMesh._BILLBOARDMODE_ALL;
  8084. },
  8085. enumerable: true,
  8086. configurable: true
  8087. });
  8088. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8089. get: function () {
  8090. return this._skeleton;
  8091. },
  8092. set: function (value) {
  8093. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8094. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8095. }
  8096. if (value && value.needInitialSkinMatrix) {
  8097. value._registerMeshWithPoseMatrix(this);
  8098. }
  8099. this._skeleton = value;
  8100. if (!this._skeleton) {
  8101. this._bonesTransformMatrices = null;
  8102. }
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. // Methods
  8108. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8109. this._poseMatrix.copyFrom(matrix);
  8110. };
  8111. AbstractMesh.prototype.getPoseMatrix = function () {
  8112. return this._poseMatrix;
  8113. };
  8114. AbstractMesh.prototype.disableEdgesRendering = function () {
  8115. if (this._edgesRenderer !== undefined) {
  8116. this._edgesRenderer.dispose();
  8117. this._edgesRenderer = undefined;
  8118. }
  8119. };
  8120. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8121. if (epsilon === void 0) { epsilon = 0.95; }
  8122. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8123. this.disableEdgesRendering();
  8124. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8125. };
  8126. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8127. get: function () {
  8128. return false;
  8129. },
  8130. enumerable: true,
  8131. configurable: true
  8132. });
  8133. AbstractMesh.prototype.getLOD = function (camera) {
  8134. return this;
  8135. };
  8136. AbstractMesh.prototype.getTotalVertices = function () {
  8137. return 0;
  8138. };
  8139. AbstractMesh.prototype.getIndices = function () {
  8140. return null;
  8141. };
  8142. AbstractMesh.prototype.getVerticesData = function (kind) {
  8143. return null;
  8144. };
  8145. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8146. return false;
  8147. };
  8148. AbstractMesh.prototype.getBoundingInfo = function () {
  8149. if (this._masterMesh) {
  8150. return this._masterMesh.getBoundingInfo();
  8151. }
  8152. if (!this._boundingInfo) {
  8153. this._updateBoundingInfo();
  8154. }
  8155. return this._boundingInfo;
  8156. };
  8157. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8158. get: function () {
  8159. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. AbstractMesh.prototype._preActivate = function () {
  8165. };
  8166. AbstractMesh.prototype._activate = function (renderId) {
  8167. this._renderId = renderId;
  8168. };
  8169. AbstractMesh.prototype.getWorldMatrix = function () {
  8170. if (this._masterMesh) {
  8171. return this._masterMesh.getWorldMatrix();
  8172. }
  8173. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8174. this.computeWorldMatrix();
  8175. }
  8176. return this._worldMatrix;
  8177. };
  8178. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8179. get: function () {
  8180. return this._worldMatrix;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8186. get: function () {
  8187. return this._absolutePosition;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8193. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8194. this.computeWorldMatrix(true);
  8195. this._isWorldMatrixFrozen = true;
  8196. };
  8197. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8198. this._isWorldMatrixFrozen = false;
  8199. this.computeWorldMatrix(true);
  8200. };
  8201. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8202. get: function () {
  8203. return this._isWorldMatrixFrozen;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8209. axis.normalize();
  8210. if (!this.rotationQuaternion) {
  8211. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8212. this.rotation = BABYLON.Vector3.Zero();
  8213. }
  8214. var rotationQuaternion;
  8215. if (!space || space === BABYLON.Space.LOCAL) {
  8216. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8217. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8218. }
  8219. else {
  8220. if (this.parent) {
  8221. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8222. invertParentWorldMatrix.invert();
  8223. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8224. }
  8225. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8226. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8227. }
  8228. };
  8229. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8230. var displacementVector = axis.scale(distance);
  8231. if (!space || space === BABYLON.Space.LOCAL) {
  8232. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8233. this.setPositionWithLocalVector(tempV3);
  8234. }
  8235. else {
  8236. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8237. }
  8238. };
  8239. AbstractMesh.prototype.getAbsolutePosition = function () {
  8240. this.computeWorldMatrix();
  8241. return this._absolutePosition;
  8242. };
  8243. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8244. if (!absolutePosition) {
  8245. return;
  8246. }
  8247. var absolutePositionX;
  8248. var absolutePositionY;
  8249. var absolutePositionZ;
  8250. if (absolutePosition.x === undefined) {
  8251. if (arguments.length < 3) {
  8252. return;
  8253. }
  8254. absolutePositionX = arguments[0];
  8255. absolutePositionY = arguments[1];
  8256. absolutePositionZ = arguments[2];
  8257. }
  8258. else {
  8259. absolutePositionX = absolutePosition.x;
  8260. absolutePositionY = absolutePosition.y;
  8261. absolutePositionZ = absolutePosition.z;
  8262. }
  8263. if (this.parent) {
  8264. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8265. invertParentWorldMatrix.invert();
  8266. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8267. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8268. }
  8269. else {
  8270. this.position.x = absolutePositionX;
  8271. this.position.y = absolutePositionY;
  8272. this.position.z = absolutePositionZ;
  8273. }
  8274. };
  8275. // ================================== Point of View Movement =================================
  8276. /**
  8277. * Perform relative position change from the point of view of behind the front of the mesh.
  8278. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8279. * Supports definition of mesh facing forward or backward.
  8280. * @param {number} amountRight
  8281. * @param {number} amountUp
  8282. * @param {number} amountForward
  8283. */
  8284. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8285. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8286. };
  8287. /**
  8288. * Calculate relative position change from the point of view of behind the front of the mesh.
  8289. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8290. * Supports definition of mesh facing forward or backward.
  8291. * @param {number} amountRight
  8292. * @param {number} amountUp
  8293. * @param {number} amountForward
  8294. */
  8295. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8296. var rotMatrix = new BABYLON.Matrix();
  8297. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8298. rotQuaternion.toRotationMatrix(rotMatrix);
  8299. var translationDelta = BABYLON.Vector3.Zero();
  8300. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8302. return translationDelta;
  8303. };
  8304. // ================================== Point of View Rotation =================================
  8305. /**
  8306. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8307. * Supports definition of mesh facing forward or backward.
  8308. * @param {number} flipBack
  8309. * @param {number} twirlClockwise
  8310. * @param {number} tiltRight
  8311. */
  8312. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8313. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8314. };
  8315. /**
  8316. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8317. * Supports definition of mesh facing forward or backward.
  8318. * @param {number} flipBack
  8319. * @param {number} twirlClockwise
  8320. * @param {number} tiltRight
  8321. */
  8322. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8323. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8324. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8325. };
  8326. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8327. this._pivotMatrix = matrix;
  8328. this._cache.pivotMatrixUpdated = true;
  8329. };
  8330. AbstractMesh.prototype.getPivotMatrix = function () {
  8331. return this._pivotMatrix;
  8332. };
  8333. AbstractMesh.prototype._isSynchronized = function () {
  8334. if (this._isDirty) {
  8335. return false;
  8336. }
  8337. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8338. return false;
  8339. if (this._cache.pivotMatrixUpdated) {
  8340. return false;
  8341. }
  8342. if (this.infiniteDistance) {
  8343. return false;
  8344. }
  8345. if (!this._cache.position.equals(this.position))
  8346. return false;
  8347. if (this.rotationQuaternion) {
  8348. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8349. return false;
  8350. }
  8351. else {
  8352. if (!this._cache.rotation.equals(this.rotation))
  8353. return false;
  8354. }
  8355. if (!this._cache.scaling.equals(this.scaling))
  8356. return false;
  8357. return true;
  8358. };
  8359. AbstractMesh.prototype._initCache = function () {
  8360. _super.prototype._initCache.call(this);
  8361. this._cache.localMatrixUpdated = false;
  8362. this._cache.position = BABYLON.Vector3.Zero();
  8363. this._cache.scaling = BABYLON.Vector3.Zero();
  8364. this._cache.rotation = BABYLON.Vector3.Zero();
  8365. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8366. this._cache.billboardMode = -1;
  8367. };
  8368. AbstractMesh.prototype.markAsDirty = function (property) {
  8369. if (property === "rotation") {
  8370. this.rotationQuaternion = null;
  8371. }
  8372. this._currentRenderId = Number.MAX_VALUE;
  8373. this._isDirty = true;
  8374. };
  8375. AbstractMesh.prototype._updateBoundingInfo = function () {
  8376. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8377. this._boundingInfo.update(this.worldMatrixFromCache);
  8378. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8379. };
  8380. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8381. if (!this.subMeshes) {
  8382. return;
  8383. }
  8384. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8385. var subMesh = this.subMeshes[subIndex];
  8386. if (!subMesh.IsGlobal) {
  8387. subMesh.updateBoundingInfo(matrix);
  8388. }
  8389. }
  8390. };
  8391. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8392. if (this._isWorldMatrixFrozen) {
  8393. return this._worldMatrix;
  8394. }
  8395. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8396. this._currentRenderId = this.getScene().getRenderId();
  8397. return this._worldMatrix;
  8398. }
  8399. this._cache.position.copyFrom(this.position);
  8400. this._cache.scaling.copyFrom(this.scaling);
  8401. this._cache.pivotMatrixUpdated = false;
  8402. this._cache.billboardMode = this.billboardMode;
  8403. this._currentRenderId = this.getScene().getRenderId();
  8404. this._isDirty = false;
  8405. // Scaling
  8406. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8407. // Rotation
  8408. if (this.rotationQuaternion) {
  8409. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8410. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8411. }
  8412. else {
  8413. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8414. this._cache.rotation.copyFrom(this.rotation);
  8415. }
  8416. // Translation
  8417. if (this.infiniteDistance && !this.parent) {
  8418. var camera = this.getScene().activeCamera;
  8419. if (camera) {
  8420. var cameraWorldMatrix = camera.getWorldMatrix();
  8421. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8422. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8423. }
  8424. }
  8425. else {
  8426. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8427. }
  8428. // Composing transformations
  8429. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8430. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8431. // Billboarding
  8432. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8433. var localPosition = this.position.clone();
  8434. var zero = this.getScene().activeCamera.globalPosition.clone();
  8435. if (this.parent && this.parent.position) {
  8436. localPosition.addInPlace(this.parent.position);
  8437. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8438. }
  8439. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8440. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8441. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8442. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8443. zero.y = localPosition.y + 0.001;
  8444. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8445. zero.z = localPosition.z + 0.001;
  8446. }
  8447. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8448. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8449. BABYLON.Tmp.Matrix[3].invert();
  8450. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8451. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8452. }
  8453. // Local world
  8454. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8455. // Parent
  8456. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8457. this._markSyncedWithParent();
  8458. if (this._meshToBoneReferal) {
  8459. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8460. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8461. }
  8462. else {
  8463. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8464. }
  8465. }
  8466. else {
  8467. this._worldMatrix.copyFrom(this._localWorld);
  8468. }
  8469. // Bounding info
  8470. this._updateBoundingInfo();
  8471. // Absolute position
  8472. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8473. // Callbacks
  8474. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8475. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8476. }
  8477. if (!this._poseMatrix) {
  8478. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8479. }
  8480. return this._worldMatrix;
  8481. };
  8482. /**
  8483. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8484. * @param func: callback function to add
  8485. */
  8486. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8487. this._onAfterWorldMatrixUpdate.push(func);
  8488. };
  8489. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8490. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8491. if (index > -1) {
  8492. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8493. }
  8494. };
  8495. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8496. this.computeWorldMatrix();
  8497. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8498. };
  8499. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8500. this.computeWorldMatrix();
  8501. var invLocalWorldMatrix = this._localWorld.clone();
  8502. invLocalWorldMatrix.invert();
  8503. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8504. };
  8505. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8506. this.computeWorldMatrix(true);
  8507. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8508. };
  8509. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8510. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8511. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8512. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8513. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8514. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8515. /// <returns>Mesh oriented towards targetMesh</returns>
  8516. yawCor = yawCor || 0; // default to zero if undefined
  8517. pitchCor = pitchCor || 0;
  8518. rollCor = rollCor || 0;
  8519. var dv = targetPoint.subtract(this.position);
  8520. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8521. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8522. var pitch = Math.atan2(dv.y, len);
  8523. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8524. };
  8525. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8526. this._meshToBoneReferal = affectedMesh;
  8527. this.parent = bone;
  8528. if (bone.getWorldMatrix().determinant() < 0) {
  8529. this.scalingDeterminant *= -1;
  8530. }
  8531. };
  8532. AbstractMesh.prototype.detachFromBone = function () {
  8533. if (this.parent.getWorldMatrix().determinant() < 0) {
  8534. this.scalingDeterminant *= -1;
  8535. }
  8536. this._meshToBoneReferal = null;
  8537. this.parent = null;
  8538. };
  8539. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8540. return this._boundingInfo.isInFrustum(frustumPlanes);
  8541. };
  8542. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8543. if (!camera) {
  8544. camera = this.getScene().activeCamera;
  8545. }
  8546. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8547. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8548. return false;
  8549. }
  8550. return true;
  8551. };
  8552. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8553. if (!this._boundingInfo || !mesh._boundingInfo) {
  8554. return false;
  8555. }
  8556. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8557. };
  8558. AbstractMesh.prototype.intersectsPoint = function (point) {
  8559. if (!this._boundingInfo) {
  8560. return false;
  8561. }
  8562. return this._boundingInfo.intersectsPoint(point);
  8563. };
  8564. // Physics
  8565. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8566. var physicsEngine = this.getScene().getPhysicsEngine();
  8567. if (!physicsEngine) {
  8568. return null;
  8569. }
  8570. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8571. if (impostor.impostor) {
  8572. // Old API
  8573. options = impostor;
  8574. impostor = impostor.impostor;
  8575. }
  8576. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8577. physicsEngine._unregisterMesh(this);
  8578. return null;
  8579. }
  8580. if (!options) {
  8581. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8582. }
  8583. else {
  8584. if (!options.mass && options.mass !== 0)
  8585. options.mass = 0;
  8586. if (!options.friction && options.friction !== 0)
  8587. options.friction = 0.2;
  8588. if (!options.restitution && options.restitution !== 0)
  8589. options.restitution = 0.2;
  8590. }
  8591. this._physicImpostor = impostor;
  8592. this._physicsMass = options.mass;
  8593. this._physicsFriction = options.friction;
  8594. this._physicRestitution = options.restitution;
  8595. return physicsEngine._registerMesh(this, impostor, options);
  8596. };
  8597. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8598. if (!this._physicImpostor) {
  8599. return BABYLON.PhysicsEngine.NoImpostor;
  8600. }
  8601. return this._physicImpostor;
  8602. };
  8603. AbstractMesh.prototype.getPhysicsMass = function () {
  8604. if (!this._physicsMass) {
  8605. return 0;
  8606. }
  8607. return this._physicsMass;
  8608. };
  8609. AbstractMesh.prototype.getPhysicsFriction = function () {
  8610. if (!this._physicsFriction) {
  8611. return 0;
  8612. }
  8613. return this._physicsFriction;
  8614. };
  8615. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8616. if (!this._physicRestitution) {
  8617. return 0;
  8618. }
  8619. return this._physicRestitution;
  8620. };
  8621. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8622. if (!camera) {
  8623. camera = this.getScene().activeCamera;
  8624. }
  8625. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8626. };
  8627. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8628. if (!camera) {
  8629. camera = this.getScene().activeCamera;
  8630. }
  8631. return this.absolutePosition.subtract(camera.position).length();
  8632. };
  8633. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8634. if (!this._physicImpostor) {
  8635. return;
  8636. }
  8637. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8638. };
  8639. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8640. if (!this._physicImpostor) {
  8641. return;
  8642. }
  8643. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8644. };
  8645. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8646. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8647. this.updatePhysicsBody();
  8648. };
  8649. AbstractMesh.prototype.updatePhysicsBody = function () {
  8650. if (!this._physicImpostor) {
  8651. return;
  8652. }
  8653. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8654. };
  8655. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8656. // Collisions
  8657. get: function () {
  8658. return this._checkCollisions;
  8659. },
  8660. set: function (collisionEnabled) {
  8661. this._checkCollisions = collisionEnabled;
  8662. if (this.getScene().workerCollisions) {
  8663. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8664. }
  8665. },
  8666. enumerable: true,
  8667. configurable: true
  8668. });
  8669. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8670. var globalPosition = this.getAbsolutePosition();
  8671. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8672. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8673. this._collider.radius = this.ellipsoid;
  8674. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8675. };
  8676. // Submeshes octree
  8677. /**
  8678. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8679. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8680. */
  8681. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8682. if (maxCapacity === void 0) { maxCapacity = 64; }
  8683. if (maxDepth === void 0) { maxDepth = 2; }
  8684. if (!this._submeshesOctree) {
  8685. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8686. }
  8687. this.computeWorldMatrix(true);
  8688. // Update octree
  8689. var bbox = this.getBoundingInfo().boundingBox;
  8690. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8691. return this._submeshesOctree;
  8692. };
  8693. // Collisions
  8694. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8695. this._generatePointsArray();
  8696. // Transformation
  8697. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8698. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8699. subMesh._lastColliderWorldVertices = [];
  8700. subMesh._trianglePlanes = [];
  8701. var start = subMesh.verticesStart;
  8702. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8703. for (var i = start; i < end; i++) {
  8704. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8705. }
  8706. }
  8707. // Collide
  8708. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8709. if (collider.collisionFound) {
  8710. collider.collidedMesh = this;
  8711. }
  8712. };
  8713. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8714. var subMeshes;
  8715. var len;
  8716. // Octrees
  8717. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8718. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8719. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8720. len = intersections.length;
  8721. subMeshes = intersections.data;
  8722. }
  8723. else {
  8724. subMeshes = this.subMeshes;
  8725. len = subMeshes.length;
  8726. }
  8727. for (var index = 0; index < len; index++) {
  8728. var subMesh = subMeshes[index];
  8729. // Bounding test
  8730. if (len > 1 && !subMesh._checkCollision(collider))
  8731. continue;
  8732. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8733. }
  8734. };
  8735. AbstractMesh.prototype._checkCollision = function (collider) {
  8736. // Bounding box test
  8737. if (!this._boundingInfo._checkCollision(collider))
  8738. return;
  8739. // Transformation matrix
  8740. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8741. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8742. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8743. };
  8744. // Picking
  8745. AbstractMesh.prototype._generatePointsArray = function () {
  8746. return false;
  8747. };
  8748. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8749. var pickingInfo = new BABYLON.PickingInfo();
  8750. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8751. return pickingInfo;
  8752. }
  8753. if (!this._generatePointsArray()) {
  8754. return pickingInfo;
  8755. }
  8756. var intersectInfo = null;
  8757. // Octrees
  8758. var subMeshes;
  8759. var len;
  8760. if (this._submeshesOctree && this.useOctreeForPicking) {
  8761. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8762. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8763. len = intersections.length;
  8764. subMeshes = intersections.data;
  8765. }
  8766. else {
  8767. subMeshes = this.subMeshes;
  8768. len = subMeshes.length;
  8769. }
  8770. for (var index = 0; index < len; index++) {
  8771. var subMesh = subMeshes[index];
  8772. // Bounding test
  8773. if (len > 1 && !subMesh.canIntersects(ray))
  8774. continue;
  8775. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8776. if (currentIntersectInfo) {
  8777. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8778. intersectInfo = currentIntersectInfo;
  8779. intersectInfo.subMeshId = index;
  8780. if (fastCheck) {
  8781. break;
  8782. }
  8783. }
  8784. }
  8785. }
  8786. if (intersectInfo) {
  8787. // Get picked point
  8788. var world = this.getWorldMatrix();
  8789. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8790. var direction = ray.direction.clone();
  8791. direction = direction.scale(intersectInfo.distance);
  8792. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8793. var pickedPoint = worldOrigin.add(worldDirection);
  8794. // Return result
  8795. pickingInfo.hit = true;
  8796. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8797. pickingInfo.pickedPoint = pickedPoint;
  8798. pickingInfo.pickedMesh = this;
  8799. pickingInfo.bu = intersectInfo.bu;
  8800. pickingInfo.bv = intersectInfo.bv;
  8801. pickingInfo.faceId = intersectInfo.faceId;
  8802. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8803. return pickingInfo;
  8804. }
  8805. return pickingInfo;
  8806. };
  8807. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8808. return null;
  8809. };
  8810. AbstractMesh.prototype.releaseSubMeshes = function () {
  8811. if (this.subMeshes) {
  8812. while (this.subMeshes.length) {
  8813. this.subMeshes[0].dispose();
  8814. }
  8815. }
  8816. else {
  8817. this.subMeshes = new Array();
  8818. }
  8819. };
  8820. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8821. var index;
  8822. // Action manager
  8823. if (this.actionManager) {
  8824. this.actionManager.dispose();
  8825. this.actionManager = null;
  8826. }
  8827. // Skeleton
  8828. this.skeleton = null;
  8829. // Animations
  8830. this.getScene().stopAnimation(this);
  8831. // Physics
  8832. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8833. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8834. }
  8835. // Intersections in progress
  8836. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8837. var other = this._intersectionsInProgress[index];
  8838. var pos = other._intersectionsInProgress.indexOf(this);
  8839. other._intersectionsInProgress.splice(pos, 1);
  8840. }
  8841. this._intersectionsInProgress = [];
  8842. // Edges
  8843. if (this._edgesRenderer) {
  8844. this._edgesRenderer.dispose();
  8845. this._edgesRenderer = null;
  8846. }
  8847. // SubMeshes
  8848. this.releaseSubMeshes();
  8849. // Remove from scene
  8850. this.getScene().removeMesh(this);
  8851. if (!doNotRecurse) {
  8852. // Particles
  8853. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8854. if (this.getScene().particleSystems[index].emitter === this) {
  8855. this.getScene().particleSystems[index].dispose();
  8856. index--;
  8857. }
  8858. }
  8859. // Children
  8860. var objects = this.getScene().meshes.slice(0);
  8861. for (index = 0; index < objects.length; index++) {
  8862. if (objects[index].parent === this) {
  8863. objects[index].dispose();
  8864. }
  8865. }
  8866. }
  8867. else {
  8868. for (index = 0; index < this.getScene().meshes.length; index++) {
  8869. var obj = this.getScene().meshes[index];
  8870. if (obj.parent === this) {
  8871. obj.parent = null;
  8872. obj.computeWorldMatrix(true);
  8873. }
  8874. }
  8875. }
  8876. this._onAfterWorldMatrixUpdate = [];
  8877. this._isDisposed = true;
  8878. // Callback
  8879. if (this.onDispose) {
  8880. this.onDispose();
  8881. }
  8882. };
  8883. // Statics
  8884. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8885. AbstractMesh._BILLBOARDMODE_X = 1;
  8886. AbstractMesh._BILLBOARDMODE_Y = 2;
  8887. AbstractMesh._BILLBOARDMODE_Z = 4;
  8888. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8889. return AbstractMesh;
  8890. })(BABYLON.Node);
  8891. BABYLON.AbstractMesh = AbstractMesh;
  8892. })(BABYLON || (BABYLON = {}));
  8893. var BABYLON;
  8894. (function (BABYLON) {
  8895. var Light = (function (_super) {
  8896. __extends(Light, _super);
  8897. function Light(name, scene) {
  8898. _super.call(this, name, scene);
  8899. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8900. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8901. this.intensity = 1.0;
  8902. this.range = Number.MAX_VALUE;
  8903. this.includeOnlyWithLayerMask = 0;
  8904. this.includedOnlyMeshes = new Array();
  8905. this.excludedMeshes = new Array();
  8906. this.excludeWithLayerMask = 0;
  8907. // PBR Properties.
  8908. this.radius = 0.00001;
  8909. this._excludedMeshesIds = new Array();
  8910. this._includedOnlyMeshesIds = new Array();
  8911. scene.addLight(this);
  8912. }
  8913. Light.prototype.getShadowGenerator = function () {
  8914. return this._shadowGenerator;
  8915. };
  8916. Light.prototype.getAbsolutePosition = function () {
  8917. return BABYLON.Vector3.Zero();
  8918. };
  8919. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8920. };
  8921. Light.prototype._getWorldMatrix = function () {
  8922. return BABYLON.Matrix.Identity();
  8923. };
  8924. Light.prototype.canAffectMesh = function (mesh) {
  8925. if (!mesh) {
  8926. return true;
  8927. }
  8928. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8929. return false;
  8930. }
  8931. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8932. return false;
  8933. }
  8934. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8935. return false;
  8936. }
  8937. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8938. return false;
  8939. }
  8940. return true;
  8941. };
  8942. Light.prototype.getWorldMatrix = function () {
  8943. this._currentRenderId = this.getScene().getRenderId();
  8944. var worldMatrix = this._getWorldMatrix();
  8945. if (this.parent && this.parent.getWorldMatrix) {
  8946. if (!this._parentedWorldMatrix) {
  8947. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8948. }
  8949. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8950. this._markSyncedWithParent();
  8951. return this._parentedWorldMatrix;
  8952. }
  8953. return worldMatrix;
  8954. };
  8955. Light.prototype.dispose = function () {
  8956. if (this._shadowGenerator) {
  8957. this._shadowGenerator.dispose();
  8958. this._shadowGenerator = null;
  8959. }
  8960. // Animations
  8961. this.getScene().stopAnimation(this);
  8962. // Remove from scene
  8963. this.getScene().removeLight(this);
  8964. };
  8965. Light.prototype.serialize = function () {
  8966. var serializationObject = {};
  8967. serializationObject.name = this.name;
  8968. serializationObject.id = this.id;
  8969. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8970. if (this.intensity) {
  8971. serializationObject.intensity = this.intensity;
  8972. }
  8973. // Parent
  8974. if (this.parent) {
  8975. serializationObject.parentId = this.parent.id;
  8976. }
  8977. serializationObject.range = this.range;
  8978. serializationObject.radius = this.radius;
  8979. serializationObject.diffuse = this.diffuse.asArray();
  8980. serializationObject.specular = this.specular.asArray();
  8981. return serializationObject;
  8982. };
  8983. Light.Parse = function (parsedLight, scene) {
  8984. var light;
  8985. switch (parsedLight.type) {
  8986. case 0:
  8987. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8988. break;
  8989. case 1:
  8990. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8991. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8992. break;
  8993. case 2:
  8994. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8995. break;
  8996. case 3:
  8997. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8998. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8999. break;
  9000. }
  9001. light.id = parsedLight.id;
  9002. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  9003. if (parsedLight.intensity !== undefined) {
  9004. light.intensity = parsedLight.intensity;
  9005. }
  9006. if (parsedLight.range) {
  9007. light.range = parsedLight.range;
  9008. }
  9009. if (parsedLight.radius) {
  9010. light.radius = parsedLight.radius;
  9011. }
  9012. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  9013. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  9014. if (parsedLight.excludedMeshesIds) {
  9015. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9016. }
  9017. // Parent
  9018. if (parsedLight.parentId) {
  9019. light._waitingParentId = parsedLight.parentId;
  9020. }
  9021. if (parsedLight.includedOnlyMeshesIds) {
  9022. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9023. }
  9024. // Animations
  9025. if (parsedLight.animations) {
  9026. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9027. var parsedAnimation = parsedLight.animations[animationIndex];
  9028. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9029. }
  9030. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9031. }
  9032. if (parsedLight.autoAnimate) {
  9033. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9034. }
  9035. return light;
  9036. };
  9037. return Light;
  9038. })(BABYLON.Node);
  9039. BABYLON.Light = Light;
  9040. })(BABYLON || (BABYLON = {}));
  9041. var BABYLON;
  9042. (function (BABYLON) {
  9043. var PointLight = (function (_super) {
  9044. __extends(PointLight, _super);
  9045. function PointLight(name, position, scene) {
  9046. _super.call(this, name, scene);
  9047. this.position = position;
  9048. }
  9049. PointLight.prototype.getAbsolutePosition = function () {
  9050. return this.transformedPosition ? this.transformedPosition : this.position;
  9051. };
  9052. PointLight.prototype.computeTransformedPosition = function () {
  9053. if (this.parent && this.parent.getWorldMatrix) {
  9054. if (!this.transformedPosition) {
  9055. this.transformedPosition = BABYLON.Vector3.Zero();
  9056. }
  9057. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9058. return true;
  9059. }
  9060. return false;
  9061. };
  9062. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9063. if (this.parent && this.parent.getWorldMatrix) {
  9064. this.computeTransformedPosition();
  9065. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9066. return;
  9067. }
  9068. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9069. };
  9070. PointLight.prototype.needCube = function () {
  9071. return true;
  9072. };
  9073. PointLight.prototype.supportsVSM = function () {
  9074. return false;
  9075. };
  9076. PointLight.prototype.needRefreshPerFrame = function () {
  9077. return false;
  9078. };
  9079. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9080. switch (faceIndex) {
  9081. case 0:
  9082. return new BABYLON.Vector3(1, 0, 0);
  9083. case 1:
  9084. return new BABYLON.Vector3(-1, 0, 0);
  9085. case 2:
  9086. return new BABYLON.Vector3(0, -1, 0);
  9087. case 3:
  9088. return new BABYLON.Vector3(0, 1, 0);
  9089. case 4:
  9090. return new BABYLON.Vector3(0, 0, 1);
  9091. case 5:
  9092. return new BABYLON.Vector3(0, 0, -1);
  9093. }
  9094. return BABYLON.Vector3.Zero();
  9095. };
  9096. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9097. var activeCamera = this.getScene().activeCamera;
  9098. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9099. };
  9100. PointLight.prototype._getWorldMatrix = function () {
  9101. if (!this._worldMatrix) {
  9102. this._worldMatrix = BABYLON.Matrix.Identity();
  9103. }
  9104. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9105. return this._worldMatrix;
  9106. };
  9107. PointLight.prototype.serialize = function () {
  9108. var serializationObject = _super.prototype.serialize.call(this);
  9109. serializationObject.type = 0;
  9110. serializationObject.position = this.position.asArray();
  9111. return serializationObject;
  9112. };
  9113. return PointLight;
  9114. })(BABYLON.Light);
  9115. BABYLON.PointLight = PointLight;
  9116. })(BABYLON || (BABYLON = {}));
  9117. var BABYLON;
  9118. (function (BABYLON) {
  9119. var SpotLight = (function (_super) {
  9120. __extends(SpotLight, _super);
  9121. function SpotLight(name, position, direction, angle, exponent, scene) {
  9122. _super.call(this, name, scene);
  9123. this.position = position;
  9124. this.direction = direction;
  9125. this.angle = angle;
  9126. this.exponent = exponent;
  9127. }
  9128. SpotLight.prototype.getAbsolutePosition = function () {
  9129. return this.transformedPosition ? this.transformedPosition : this.position;
  9130. };
  9131. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9132. var activeCamera = this.getScene().activeCamera;
  9133. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9134. };
  9135. SpotLight.prototype.needCube = function () {
  9136. return false;
  9137. };
  9138. SpotLight.prototype.supportsVSM = function () {
  9139. return true;
  9140. };
  9141. SpotLight.prototype.needRefreshPerFrame = function () {
  9142. return false;
  9143. };
  9144. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9145. return this.direction;
  9146. };
  9147. SpotLight.prototype.setDirectionToTarget = function (target) {
  9148. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9149. return this.direction;
  9150. };
  9151. SpotLight.prototype.computeTransformedPosition = function () {
  9152. if (this.parent && this.parent.getWorldMatrix) {
  9153. if (!this.transformedPosition) {
  9154. this.transformedPosition = BABYLON.Vector3.Zero();
  9155. }
  9156. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9157. return true;
  9158. }
  9159. return false;
  9160. };
  9161. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9162. var normalizeDirection;
  9163. if (this.parent && this.parent.getWorldMatrix) {
  9164. if (!this._transformedDirection) {
  9165. this._transformedDirection = BABYLON.Vector3.Zero();
  9166. }
  9167. this.computeTransformedPosition();
  9168. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9169. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9170. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9171. }
  9172. else {
  9173. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9174. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9175. }
  9176. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9177. };
  9178. SpotLight.prototype._getWorldMatrix = function () {
  9179. if (!this._worldMatrix) {
  9180. this._worldMatrix = BABYLON.Matrix.Identity();
  9181. }
  9182. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9183. return this._worldMatrix;
  9184. };
  9185. SpotLight.prototype.serialize = function () {
  9186. var serializationObject = _super.prototype.serialize.call(this);
  9187. serializationObject.type = 2;
  9188. serializationObject.position = this.position.asArray();
  9189. serializationObject.direction = this.position.asArray();
  9190. serializationObject.angle = this.angle;
  9191. serializationObject.exponent = this.exponent;
  9192. return serializationObject;
  9193. };
  9194. return SpotLight;
  9195. })(BABYLON.Light);
  9196. BABYLON.SpotLight = SpotLight;
  9197. })(BABYLON || (BABYLON = {}));
  9198. var BABYLON;
  9199. (function (BABYLON) {
  9200. var HemisphericLight = (function (_super) {
  9201. __extends(HemisphericLight, _super);
  9202. function HemisphericLight(name, direction, scene) {
  9203. _super.call(this, name, scene);
  9204. this.direction = direction;
  9205. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9206. }
  9207. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9208. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9209. return this.direction;
  9210. };
  9211. HemisphericLight.prototype.getShadowGenerator = function () {
  9212. return null;
  9213. };
  9214. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9215. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9216. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9217. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9218. };
  9219. HemisphericLight.prototype._getWorldMatrix = function () {
  9220. if (!this._worldMatrix) {
  9221. this._worldMatrix = BABYLON.Matrix.Identity();
  9222. }
  9223. return this._worldMatrix;
  9224. };
  9225. HemisphericLight.prototype.serialize = function () {
  9226. var serializationObject = _super.prototype.serialize.call(this);
  9227. serializationObject.type = 3;
  9228. serializationObject.direction = this.direction.asArray();
  9229. serializationObject.groundColor = this.groundColor.asArray();
  9230. return serializationObject;
  9231. };
  9232. return HemisphericLight;
  9233. })(BABYLON.Light);
  9234. BABYLON.HemisphericLight = HemisphericLight;
  9235. })(BABYLON || (BABYLON = {}));
  9236. var BABYLON;
  9237. (function (BABYLON) {
  9238. var DirectionalLight = (function (_super) {
  9239. __extends(DirectionalLight, _super);
  9240. function DirectionalLight(name, direction, scene) {
  9241. _super.call(this, name, scene);
  9242. this.direction = direction;
  9243. this.shadowOrthoScale = 0.5;
  9244. this.autoUpdateExtends = true;
  9245. // Cache
  9246. this._orthoLeft = Number.MAX_VALUE;
  9247. this._orthoRight = Number.MIN_VALUE;
  9248. this._orthoTop = Number.MIN_VALUE;
  9249. this._orthoBottom = Number.MAX_VALUE;
  9250. this.position = direction.scale(-1);
  9251. }
  9252. DirectionalLight.prototype.getAbsolutePosition = function () {
  9253. return this.transformedPosition ? this.transformedPosition : this.position;
  9254. };
  9255. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9256. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9257. return this.direction;
  9258. };
  9259. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9260. var activeCamera = this.getScene().activeCamera;
  9261. // Check extends
  9262. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9263. var tempVector3 = BABYLON.Vector3.Zero();
  9264. this._orthoLeft = Number.MAX_VALUE;
  9265. this._orthoRight = Number.MIN_VALUE;
  9266. this._orthoTop = Number.MIN_VALUE;
  9267. this._orthoBottom = Number.MAX_VALUE;
  9268. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9269. var mesh = renderList[meshIndex];
  9270. if (!mesh) {
  9271. continue;
  9272. }
  9273. var boundingInfo = mesh.getBoundingInfo();
  9274. if (!boundingInfo) {
  9275. continue;
  9276. }
  9277. var boundingBox = boundingInfo.boundingBox;
  9278. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9279. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9280. if (tempVector3.x < this._orthoLeft)
  9281. this._orthoLeft = tempVector3.x;
  9282. if (tempVector3.y < this._orthoBottom)
  9283. this._orthoBottom = tempVector3.y;
  9284. if (tempVector3.x > this._orthoRight)
  9285. this._orthoRight = tempVector3.x;
  9286. if (tempVector3.y > this._orthoTop)
  9287. this._orthoTop = tempVector3.y;
  9288. }
  9289. }
  9290. }
  9291. var xOffset = this._orthoRight - this._orthoLeft;
  9292. var yOffset = this._orthoTop - this._orthoBottom;
  9293. 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);
  9294. };
  9295. DirectionalLight.prototype.supportsVSM = function () {
  9296. return true;
  9297. };
  9298. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9299. return true;
  9300. };
  9301. DirectionalLight.prototype.needCube = function () {
  9302. return false;
  9303. };
  9304. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9305. return this.direction;
  9306. };
  9307. DirectionalLight.prototype.computeTransformedPosition = function () {
  9308. if (this.parent && this.parent.getWorldMatrix) {
  9309. if (!this.transformedPosition) {
  9310. this.transformedPosition = BABYLON.Vector3.Zero();
  9311. }
  9312. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9313. return true;
  9314. }
  9315. return false;
  9316. };
  9317. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9318. if (this.parent && this.parent.getWorldMatrix) {
  9319. if (!this._transformedDirection) {
  9320. this._transformedDirection = BABYLON.Vector3.Zero();
  9321. }
  9322. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9323. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9324. return;
  9325. }
  9326. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9327. };
  9328. DirectionalLight.prototype._getWorldMatrix = function () {
  9329. if (!this._worldMatrix) {
  9330. this._worldMatrix = BABYLON.Matrix.Identity();
  9331. }
  9332. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9333. return this._worldMatrix;
  9334. };
  9335. DirectionalLight.prototype.serialize = function () {
  9336. var serializationObject = _super.prototype.serialize.call(this);
  9337. serializationObject.type = 1;
  9338. serializationObject.position = this.position.asArray();
  9339. serializationObject.direction = this.direction.asArray();
  9340. return serializationObject;
  9341. };
  9342. return DirectionalLight;
  9343. })(BABYLON.Light);
  9344. BABYLON.DirectionalLight = DirectionalLight;
  9345. })(BABYLON || (BABYLON = {}));
  9346. var BABYLON;
  9347. (function (BABYLON) {
  9348. var ShadowGenerator = (function () {
  9349. function ShadowGenerator(mapSize, light) {
  9350. var _this = this;
  9351. // Members
  9352. this._filter = ShadowGenerator.FILTER_NONE;
  9353. this.blurScale = 2;
  9354. this._blurBoxOffset = 0;
  9355. this._bias = 0.00005;
  9356. this._lightDirection = BABYLON.Vector3.Zero();
  9357. this.forceBackFacesOnly = false;
  9358. this._darkness = 0;
  9359. this._transparencyShadow = false;
  9360. this._viewMatrix = BABYLON.Matrix.Zero();
  9361. this._projectionMatrix = BABYLON.Matrix.Zero();
  9362. this._transformMatrix = BABYLON.Matrix.Zero();
  9363. this._worldViewProjection = BABYLON.Matrix.Zero();
  9364. this._currentFaceIndex = 0;
  9365. this._currentFaceIndexCache = 0;
  9366. this._light = light;
  9367. this._scene = light.getScene();
  9368. this._mapSize = mapSize;
  9369. light._shadowGenerator = this;
  9370. // Render target
  9371. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9372. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9373. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9374. this._shadowMap.anisotropicFilteringLevel = 1;
  9375. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9376. this._shadowMap.renderParticles = false;
  9377. this._shadowMap.onBeforeRender = function (faceIndex) {
  9378. _this._currentFaceIndex = faceIndex;
  9379. };
  9380. this._shadowMap.onAfterUnbind = function () {
  9381. if (!_this.useBlurVarianceShadowMap) {
  9382. return;
  9383. }
  9384. if (!_this._shadowMap2) {
  9385. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9386. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9387. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9388. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9389. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9390. _this._downSamplePostprocess.onApply = function (effect) {
  9391. effect.setTexture("textureSampler", _this._shadowMap);
  9392. };
  9393. _this.blurBoxOffset = 1;
  9394. }
  9395. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9396. };
  9397. // Custom render function
  9398. var renderSubMesh = function (subMesh) {
  9399. var mesh = subMesh.getRenderingMesh();
  9400. var scene = _this._scene;
  9401. var engine = scene.getEngine();
  9402. // Culling
  9403. engine.setState(subMesh.getMaterial().backFaceCulling);
  9404. // Managing instances
  9405. var batch = mesh._getInstancesRenderList(subMesh._id);
  9406. if (batch.mustReturn) {
  9407. return;
  9408. }
  9409. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9410. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9411. engine.enableEffect(_this._effect);
  9412. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9413. var material = subMesh.getMaterial();
  9414. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9415. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9416. if (_this.getLight().needCube()) {
  9417. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9418. }
  9419. // Alpha test
  9420. if (material && material.needAlphaTesting()) {
  9421. var alphaTexture = material.getAlphaTestTexture();
  9422. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9423. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9424. }
  9425. // Bones
  9426. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9427. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9428. }
  9429. if (_this.forceBackFacesOnly) {
  9430. engine.setState(true, 0, false, true);
  9431. }
  9432. // Draw
  9433. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9434. if (_this.forceBackFacesOnly) {
  9435. engine.setState(true, 0, false, false);
  9436. }
  9437. }
  9438. else {
  9439. // Need to reset refresh rate of the shadowMap
  9440. _this._shadowMap.resetRefreshCounter();
  9441. }
  9442. };
  9443. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9444. var index;
  9445. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9446. renderSubMesh(opaqueSubMeshes.data[index]);
  9447. }
  9448. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9449. renderSubMesh(alphaTestSubMeshes.data[index]);
  9450. }
  9451. if (_this._transparencyShadow) {
  9452. for (index = 0; index < transparentSubMeshes.length; index++) {
  9453. renderSubMesh(transparentSubMeshes.data[index]);
  9454. }
  9455. }
  9456. };
  9457. this._shadowMap.onClear = function (engine) {
  9458. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9459. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9460. }
  9461. else {
  9462. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9463. }
  9464. };
  9465. }
  9466. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9467. // Static
  9468. get: function () {
  9469. return ShadowGenerator._FILTER_NONE;
  9470. },
  9471. enumerable: true,
  9472. configurable: true
  9473. });
  9474. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9475. get: function () {
  9476. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9477. },
  9478. enumerable: true,
  9479. configurable: true
  9480. });
  9481. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9482. get: function () {
  9483. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9484. },
  9485. enumerable: true,
  9486. configurable: true
  9487. });
  9488. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9489. get: function () {
  9490. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9491. },
  9492. enumerable: true,
  9493. configurable: true
  9494. });
  9495. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9496. get: function () {
  9497. return this._bias;
  9498. },
  9499. set: function (bias) {
  9500. this._bias = bias;
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9506. get: function () {
  9507. return this._blurBoxOffset;
  9508. },
  9509. set: function (value) {
  9510. var _this = this;
  9511. if (this._blurBoxOffset === value) {
  9512. return;
  9513. }
  9514. this._blurBoxOffset = value;
  9515. if (this._boxBlurPostprocess) {
  9516. this._boxBlurPostprocess.dispose();
  9517. }
  9518. 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);
  9519. this._boxBlurPostprocess.onApply = function (effect) {
  9520. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9521. };
  9522. },
  9523. enumerable: true,
  9524. configurable: true
  9525. });
  9526. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9527. get: function () {
  9528. return this._filter;
  9529. },
  9530. set: function (value) {
  9531. if (this._filter === value) {
  9532. return;
  9533. }
  9534. this._filter = value;
  9535. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9536. this._shadowMap.anisotropicFilteringLevel = 16;
  9537. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9538. }
  9539. else {
  9540. this._shadowMap.anisotropicFilteringLevel = 1;
  9541. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9542. }
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9548. get: function () {
  9549. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9550. },
  9551. set: function (value) {
  9552. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9558. get: function () {
  9559. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9560. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9561. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9562. },
  9563. set: function (value) {
  9564. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9570. get: function () {
  9571. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9572. },
  9573. set: function (value) {
  9574. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9580. var defines = [];
  9581. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9582. defines.push("#define VSM");
  9583. }
  9584. if (this.getLight().needCube()) {
  9585. defines.push("#define CUBEMAP");
  9586. }
  9587. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9588. var mesh = subMesh.getMesh();
  9589. var material = subMesh.getMaterial();
  9590. // Alpha test
  9591. if (material && material.needAlphaTesting()) {
  9592. defines.push("#define ALPHATEST");
  9593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9594. attribs.push(BABYLON.VertexBuffer.UVKind);
  9595. defines.push("#define UV1");
  9596. }
  9597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9599. defines.push("#define UV2");
  9600. }
  9601. }
  9602. // Bones
  9603. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9604. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9605. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9606. if (mesh.numBoneInfluencers > 4) {
  9607. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9608. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9609. }
  9610. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9611. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9612. }
  9613. else {
  9614. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9615. }
  9616. // Instances
  9617. if (useInstances) {
  9618. defines.push("#define INSTANCES");
  9619. attribs.push("world0");
  9620. attribs.push("world1");
  9621. attribs.push("world2");
  9622. attribs.push("world3");
  9623. }
  9624. // Get correct effect
  9625. var join = defines.join("\n");
  9626. if (this._cachedDefines !== join) {
  9627. this._cachedDefines = join;
  9628. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9629. }
  9630. return this._effect.isReady();
  9631. };
  9632. ShadowGenerator.prototype.getShadowMap = function () {
  9633. return this._shadowMap;
  9634. };
  9635. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9636. if (this._shadowMap2) {
  9637. return this._shadowMap2;
  9638. }
  9639. return this._shadowMap;
  9640. };
  9641. ShadowGenerator.prototype.getLight = function () {
  9642. return this._light;
  9643. };
  9644. // Methods
  9645. ShadowGenerator.prototype.getTransformMatrix = function () {
  9646. var scene = this._scene;
  9647. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9648. return this._transformMatrix;
  9649. }
  9650. this._currentRenderID = scene.getRenderId();
  9651. this._currentFaceIndexCache = this._currentFaceIndex;
  9652. var lightPosition = this._light.position;
  9653. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9654. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9655. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9656. }
  9657. if (this._light.computeTransformedPosition()) {
  9658. lightPosition = this._light.transformedPosition;
  9659. }
  9660. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9661. this._cachedPosition = lightPosition.clone();
  9662. this._cachedDirection = this._lightDirection.clone();
  9663. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9664. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9665. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9666. }
  9667. return this._transformMatrix;
  9668. };
  9669. ShadowGenerator.prototype.getDarkness = function () {
  9670. return this._darkness;
  9671. };
  9672. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9673. if (darkness >= 1.0)
  9674. this._darkness = 1.0;
  9675. else if (darkness <= 0.0)
  9676. this._darkness = 0.0;
  9677. else
  9678. this._darkness = darkness;
  9679. };
  9680. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9681. this._transparencyShadow = hasShadow;
  9682. };
  9683. ShadowGenerator.prototype._packHalf = function (depth) {
  9684. var scale = depth * 255.0;
  9685. var fract = scale - Math.floor(scale);
  9686. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9687. };
  9688. ShadowGenerator.prototype.dispose = function () {
  9689. this._shadowMap.dispose();
  9690. if (this._shadowMap2) {
  9691. this._shadowMap2.dispose();
  9692. }
  9693. if (this._downSamplePostprocess) {
  9694. this._downSamplePostprocess.dispose();
  9695. }
  9696. if (this._boxBlurPostprocess) {
  9697. this._boxBlurPostprocess.dispose();
  9698. }
  9699. };
  9700. ShadowGenerator.prototype.serialize = function () {
  9701. var serializationObject = {};
  9702. serializationObject.lightId = this._light.id;
  9703. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9704. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9705. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9706. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9707. serializationObject.renderList = [];
  9708. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9709. var mesh = this.getShadowMap().renderList[meshIndex];
  9710. serializationObject.renderList.push(mesh.id);
  9711. }
  9712. return serializationObject;
  9713. };
  9714. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9715. //casting to point light, as light is missing the position attr and typescript complains.
  9716. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9717. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9718. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9719. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9720. shadowGenerator.getShadowMap().renderList.push(mesh);
  9721. }
  9722. if (parsedShadowGenerator.usePoissonSampling) {
  9723. shadowGenerator.usePoissonSampling = true;
  9724. }
  9725. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9726. shadowGenerator.useVarianceShadowMap = true;
  9727. }
  9728. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9729. shadowGenerator.useBlurVarianceShadowMap = true;
  9730. if (parsedShadowGenerator.blurScale) {
  9731. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9732. }
  9733. if (parsedShadowGenerator.blurBoxOffset) {
  9734. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9735. }
  9736. }
  9737. if (parsedShadowGenerator.bias !== undefined) {
  9738. shadowGenerator.bias = parsedShadowGenerator.bias;
  9739. }
  9740. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9741. return shadowGenerator;
  9742. };
  9743. ShadowGenerator._FILTER_NONE = 0;
  9744. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9745. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9746. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9747. return ShadowGenerator;
  9748. })();
  9749. BABYLON.ShadowGenerator = ShadowGenerator;
  9750. })(BABYLON || (BABYLON = {}));
  9751. var BABYLON;
  9752. (function (BABYLON) {
  9753. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9754. if (boxMin.x > sphereCenter.x + sphereRadius)
  9755. return false;
  9756. if (sphereCenter.x - sphereRadius > boxMax.x)
  9757. return false;
  9758. if (boxMin.y > sphereCenter.y + sphereRadius)
  9759. return false;
  9760. if (sphereCenter.y - sphereRadius > boxMax.y)
  9761. return false;
  9762. if (boxMin.z > sphereCenter.z + sphereRadius)
  9763. return false;
  9764. if (sphereCenter.z - sphereRadius > boxMax.z)
  9765. return false;
  9766. return true;
  9767. };
  9768. var getLowestRoot = function (a, b, c, maxR) {
  9769. var determinant = b * b - 4.0 * a * c;
  9770. var result = { root: 0, found: false };
  9771. if (determinant < 0)
  9772. return result;
  9773. var sqrtD = Math.sqrt(determinant);
  9774. var r1 = (-b - sqrtD) / (2.0 * a);
  9775. var r2 = (-b + sqrtD) / (2.0 * a);
  9776. if (r1 > r2) {
  9777. var temp = r2;
  9778. r2 = r1;
  9779. r1 = temp;
  9780. }
  9781. if (r1 > 0 && r1 < maxR) {
  9782. result.root = r1;
  9783. result.found = true;
  9784. return result;
  9785. }
  9786. if (r2 > 0 && r2 < maxR) {
  9787. result.root = r2;
  9788. result.found = true;
  9789. return result;
  9790. }
  9791. return result;
  9792. };
  9793. var Collider = (function () {
  9794. function Collider() {
  9795. this.radius = new BABYLON.Vector3(1, 1, 1);
  9796. this.retry = 0;
  9797. this.basePointWorld = BABYLON.Vector3.Zero();
  9798. this.velocityWorld = BABYLON.Vector3.Zero();
  9799. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9800. this._collisionPoint = BABYLON.Vector3.Zero();
  9801. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9802. this._tempVector = BABYLON.Vector3.Zero();
  9803. this._tempVector2 = BABYLON.Vector3.Zero();
  9804. this._tempVector3 = BABYLON.Vector3.Zero();
  9805. this._tempVector4 = BABYLON.Vector3.Zero();
  9806. this._edge = BABYLON.Vector3.Zero();
  9807. this._baseToVertex = BABYLON.Vector3.Zero();
  9808. this._destinationPoint = BABYLON.Vector3.Zero();
  9809. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9810. this._displacementVector = BABYLON.Vector3.Zero();
  9811. }
  9812. // Methods
  9813. Collider.prototype._initialize = function (source, dir, e) {
  9814. this.velocity = dir;
  9815. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9816. this.basePoint = source;
  9817. source.multiplyToRef(this.radius, this.basePointWorld);
  9818. dir.multiplyToRef(this.radius, this.velocityWorld);
  9819. this.velocityWorldLength = this.velocityWorld.length();
  9820. this.epsilon = e;
  9821. this.collisionFound = false;
  9822. };
  9823. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9824. pa.subtractToRef(point, this._tempVector);
  9825. pb.subtractToRef(point, this._tempVector2);
  9826. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9827. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9828. if (d < 0)
  9829. return false;
  9830. pc.subtractToRef(point, this._tempVector3);
  9831. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9832. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9833. if (d < 0)
  9834. return false;
  9835. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9836. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9837. return d >= 0;
  9838. };
  9839. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9840. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9841. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9842. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9843. return false;
  9844. }
  9845. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9846. return false;
  9847. return true;
  9848. };
  9849. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9850. var t0;
  9851. var embeddedInPlane = false;
  9852. //defensive programming, actually not needed.
  9853. if (!trianglePlaneArray) {
  9854. trianglePlaneArray = [];
  9855. }
  9856. if (!trianglePlaneArray[faceIndex]) {
  9857. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9858. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9859. }
  9860. var trianglePlane = trianglePlaneArray[faceIndex];
  9861. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9862. return;
  9863. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9864. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9865. if (normalDotVelocity == 0) {
  9866. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9867. return;
  9868. embeddedInPlane = true;
  9869. t0 = 0;
  9870. }
  9871. else {
  9872. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9873. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9874. if (t0 > t1) {
  9875. var temp = t1;
  9876. t1 = t0;
  9877. t0 = temp;
  9878. }
  9879. if (t0 > 1.0 || t1 < 0.0)
  9880. return;
  9881. if (t0 < 0)
  9882. t0 = 0;
  9883. if (t0 > 1.0)
  9884. t0 = 1.0;
  9885. }
  9886. this._collisionPoint.copyFromFloats(0, 0, 0);
  9887. var found = false;
  9888. var t = 1.0;
  9889. if (!embeddedInPlane) {
  9890. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9891. this.velocity.scaleToRef(t0, this._tempVector);
  9892. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9893. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9894. found = true;
  9895. t = t0;
  9896. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9897. }
  9898. }
  9899. if (!found) {
  9900. var velocitySquaredLength = this.velocity.lengthSquared();
  9901. var a = velocitySquaredLength;
  9902. this.basePoint.subtractToRef(p1, this._tempVector);
  9903. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9904. var c = this._tempVector.lengthSquared() - 1.0;
  9905. var lowestRoot = getLowestRoot(a, b, c, t);
  9906. if (lowestRoot.found) {
  9907. t = lowestRoot.root;
  9908. found = true;
  9909. this._collisionPoint.copyFrom(p1);
  9910. }
  9911. this.basePoint.subtractToRef(p2, this._tempVector);
  9912. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9913. c = this._tempVector.lengthSquared() - 1.0;
  9914. lowestRoot = getLowestRoot(a, b, c, t);
  9915. if (lowestRoot.found) {
  9916. t = lowestRoot.root;
  9917. found = true;
  9918. this._collisionPoint.copyFrom(p2);
  9919. }
  9920. this.basePoint.subtractToRef(p3, this._tempVector);
  9921. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9922. c = this._tempVector.lengthSquared() - 1.0;
  9923. lowestRoot = getLowestRoot(a, b, c, t);
  9924. if (lowestRoot.found) {
  9925. t = lowestRoot.root;
  9926. found = true;
  9927. this._collisionPoint.copyFrom(p3);
  9928. }
  9929. p2.subtractToRef(p1, this._edge);
  9930. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9931. var edgeSquaredLength = this._edge.lengthSquared();
  9932. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9933. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9934. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9935. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9936. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9937. lowestRoot = getLowestRoot(a, b, c, t);
  9938. if (lowestRoot.found) {
  9939. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9940. if (f >= 0.0 && f <= 1.0) {
  9941. t = lowestRoot.root;
  9942. found = true;
  9943. this._edge.scaleInPlace(f);
  9944. p1.addToRef(this._edge, this._collisionPoint);
  9945. }
  9946. }
  9947. p3.subtractToRef(p2, this._edge);
  9948. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9949. edgeSquaredLength = this._edge.lengthSquared();
  9950. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9951. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9952. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9953. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9954. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9955. lowestRoot = getLowestRoot(a, b, c, t);
  9956. if (lowestRoot.found) {
  9957. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9958. if (f >= 0.0 && f <= 1.0) {
  9959. t = lowestRoot.root;
  9960. found = true;
  9961. this._edge.scaleInPlace(f);
  9962. p2.addToRef(this._edge, this._collisionPoint);
  9963. }
  9964. }
  9965. p1.subtractToRef(p3, this._edge);
  9966. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9967. edgeSquaredLength = this._edge.lengthSquared();
  9968. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9969. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9970. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9971. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9972. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9973. lowestRoot = getLowestRoot(a, b, c, t);
  9974. if (lowestRoot.found) {
  9975. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9976. if (f >= 0.0 && f <= 1.0) {
  9977. t = lowestRoot.root;
  9978. found = true;
  9979. this._edge.scaleInPlace(f);
  9980. p3.addToRef(this._edge, this._collisionPoint);
  9981. }
  9982. }
  9983. }
  9984. if (found) {
  9985. var distToCollision = t * this.velocity.length();
  9986. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9987. if (!this.intersectionPoint) {
  9988. this.intersectionPoint = this._collisionPoint.clone();
  9989. }
  9990. else {
  9991. this.intersectionPoint.copyFrom(this._collisionPoint);
  9992. }
  9993. this.nearestDistance = distToCollision;
  9994. this.collisionFound = true;
  9995. }
  9996. }
  9997. };
  9998. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9999. for (var i = indexStart; i < indexEnd; i += 3) {
  10000. var p1 = pts[indices[i] - decal];
  10001. var p2 = pts[indices[i + 1] - decal];
  10002. var p3 = pts[indices[i + 2] - decal];
  10003. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10004. }
  10005. };
  10006. Collider.prototype._getResponse = function (pos, vel) {
  10007. pos.addToRef(vel, this._destinationPoint);
  10008. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10009. this.basePoint.addToRef(vel, pos);
  10010. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10011. this._slidePlaneNormal.normalize();
  10012. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10013. pos.addInPlace(this._displacementVector);
  10014. this.intersectionPoint.addInPlace(this._displacementVector);
  10015. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10016. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10017. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10018. };
  10019. return Collider;
  10020. })();
  10021. BABYLON.Collider = Collider;
  10022. })(BABYLON || (BABYLON = {}));
  10023. var BABYLON;
  10024. (function (BABYLON) {
  10025. //WebWorker code will be inserted to this variable.
  10026. BABYLON.CollisionWorker = "";
  10027. (function (WorkerTaskType) {
  10028. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10029. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10030. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10031. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10032. var WorkerTaskType = BABYLON.WorkerTaskType;
  10033. (function (WorkerReplyType) {
  10034. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10035. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10036. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10037. var WorkerReplyType = BABYLON.WorkerReplyType;
  10038. var CollisionCoordinatorWorker = (function () {
  10039. function CollisionCoordinatorWorker() {
  10040. var _this = this;
  10041. this._scaledPosition = BABYLON.Vector3.Zero();
  10042. this._scaledVelocity = BABYLON.Vector3.Zero();
  10043. this.onMeshUpdated = function (mesh) {
  10044. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10045. };
  10046. this.onGeometryUpdated = function (geometry) {
  10047. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10048. };
  10049. this._afterRender = function () {
  10050. if (!_this._init)
  10051. return;
  10052. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10053. return;
  10054. }
  10055. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10056. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10057. if (_this._runningUpdated > 4) {
  10058. return;
  10059. }
  10060. ++_this._runningUpdated;
  10061. var payload = {
  10062. updatedMeshes: _this._addUpdateMeshesList,
  10063. updatedGeometries: _this._addUpdateGeometriesList,
  10064. removedGeometries: _this._toRemoveGeometryArray,
  10065. removedMeshes: _this._toRemoveMeshesArray
  10066. };
  10067. var message = {
  10068. payload: payload,
  10069. taskType: WorkerTaskType.UPDATE
  10070. };
  10071. var serializable = [];
  10072. for (var id in payload.updatedGeometries) {
  10073. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10074. //prepare transferables
  10075. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10076. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10077. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10078. }
  10079. }
  10080. _this._worker.postMessage(message, serializable);
  10081. _this._addUpdateMeshesList = {};
  10082. _this._addUpdateGeometriesList = {};
  10083. _this._toRemoveGeometryArray = [];
  10084. _this._toRemoveMeshesArray = [];
  10085. };
  10086. this._onMessageFromWorker = function (e) {
  10087. var returnData = e.data;
  10088. if (returnData.error != WorkerReplyType.SUCCESS) {
  10089. //TODO what errors can be returned from the worker?
  10090. BABYLON.Tools.Warn("error returned from worker!");
  10091. return;
  10092. }
  10093. switch (returnData.taskType) {
  10094. case WorkerTaskType.INIT:
  10095. _this._init = true;
  10096. //Update the worked with ALL of the scene's current state
  10097. _this._scene.meshes.forEach(function (mesh) {
  10098. _this.onMeshAdded(mesh);
  10099. });
  10100. _this._scene.getGeometries().forEach(function (geometry) {
  10101. _this.onGeometryAdded(geometry);
  10102. });
  10103. break;
  10104. case WorkerTaskType.UPDATE:
  10105. _this._runningUpdated--;
  10106. break;
  10107. case WorkerTaskType.COLLIDE:
  10108. _this._runningCollisionTask = false;
  10109. var returnPayload = returnData.payload;
  10110. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10111. return;
  10112. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10113. //cleanup
  10114. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10115. break;
  10116. }
  10117. };
  10118. this._collisionsCallbackArray = [];
  10119. this._init = false;
  10120. this._runningUpdated = 0;
  10121. this._runningCollisionTask = false;
  10122. this._addUpdateMeshesList = {};
  10123. this._addUpdateGeometriesList = {};
  10124. this._toRemoveGeometryArray = [];
  10125. this._toRemoveMeshesArray = [];
  10126. }
  10127. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10128. if (!this._init)
  10129. return;
  10130. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10131. return;
  10132. position.divideToRef(collider.radius, this._scaledPosition);
  10133. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10134. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10135. var payload = {
  10136. collider: {
  10137. position: this._scaledPosition.asArray(),
  10138. velocity: this._scaledVelocity.asArray(),
  10139. radius: collider.radius.asArray()
  10140. },
  10141. collisionId: collisionIndex,
  10142. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10143. maximumRetry: maximumRetry
  10144. };
  10145. var message = {
  10146. payload: payload,
  10147. taskType: WorkerTaskType.COLLIDE
  10148. };
  10149. this._worker.postMessage(message);
  10150. };
  10151. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10152. this._scene = scene;
  10153. this._scene.registerAfterRender(this._afterRender);
  10154. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10155. this._worker = new Worker(workerUrl);
  10156. this._worker.onmessage = this._onMessageFromWorker;
  10157. var message = {
  10158. payload: {},
  10159. taskType: WorkerTaskType.INIT
  10160. };
  10161. this._worker.postMessage(message);
  10162. };
  10163. CollisionCoordinatorWorker.prototype.destroy = function () {
  10164. this._scene.unregisterAfterRender(this._afterRender);
  10165. this._worker.terminate();
  10166. };
  10167. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10168. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10169. this.onMeshUpdated(mesh);
  10170. };
  10171. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10172. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10173. };
  10174. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10175. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10176. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10177. this.onGeometryUpdated(geometry);
  10178. };
  10179. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10180. this._toRemoveGeometryArray.push(geometry.id);
  10181. };
  10182. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10183. var submeshes = [];
  10184. if (mesh.subMeshes) {
  10185. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10186. return {
  10187. position: idx,
  10188. verticesStart: sm.verticesStart,
  10189. verticesCount: sm.verticesCount,
  10190. indexStart: sm.indexStart,
  10191. indexCount: sm.indexCount,
  10192. hasMaterial: !!sm.getMaterial(),
  10193. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10194. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10195. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10196. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10197. };
  10198. });
  10199. }
  10200. var geometryId = null;
  10201. if (mesh instanceof BABYLON.Mesh) {
  10202. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10203. }
  10204. else if (mesh instanceof BABYLON.InstancedMesh) {
  10205. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10206. }
  10207. return {
  10208. uniqueId: mesh.uniqueId,
  10209. id: mesh.id,
  10210. name: mesh.name,
  10211. geometryId: geometryId,
  10212. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10213. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10214. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10215. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10216. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10217. subMeshes: submeshes,
  10218. checkCollisions: mesh.checkCollisions
  10219. };
  10220. };
  10221. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10222. return {
  10223. id: geometry.id,
  10224. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10225. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10226. indices: new Int32Array(geometry.getIndices() || []),
  10227. };
  10228. };
  10229. return CollisionCoordinatorWorker;
  10230. })();
  10231. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10232. var CollisionCoordinatorLegacy = (function () {
  10233. function CollisionCoordinatorLegacy() {
  10234. this._scaledPosition = BABYLON.Vector3.Zero();
  10235. this._scaledVelocity = BABYLON.Vector3.Zero();
  10236. this._finalPosition = BABYLON.Vector3.Zero();
  10237. }
  10238. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10239. position.divideToRef(collider.radius, this._scaledPosition);
  10240. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10241. collider.collidedMesh = null;
  10242. collider.retry = 0;
  10243. collider.initialVelocity = this._scaledVelocity;
  10244. collider.initialPosition = this._scaledPosition;
  10245. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10246. this._finalPosition.multiplyInPlace(collider.radius);
  10247. //run the callback
  10248. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10249. };
  10250. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10251. this._scene = scene;
  10252. };
  10253. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10254. //Legacy need no destruction method.
  10255. };
  10256. //No update in legacy mode
  10257. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10258. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10259. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10260. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10261. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10262. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10263. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10264. if (excludedMesh === void 0) { excludedMesh = null; }
  10265. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10266. if (collider.retry >= maximumRetry) {
  10267. finalPosition.copyFrom(position);
  10268. return;
  10269. }
  10270. collider._initialize(position, velocity, closeDistance);
  10271. // Check all meshes
  10272. for (var index = 0; index < this._scene.meshes.length; index++) {
  10273. var mesh = this._scene.meshes[index];
  10274. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10275. mesh._checkCollision(collider);
  10276. }
  10277. }
  10278. if (!collider.collisionFound) {
  10279. position.addToRef(velocity, finalPosition);
  10280. return;
  10281. }
  10282. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10283. collider._getResponse(position, velocity);
  10284. }
  10285. if (velocity.length() <= closeDistance) {
  10286. finalPosition.copyFrom(position);
  10287. return;
  10288. }
  10289. collider.retry++;
  10290. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10291. };
  10292. return CollisionCoordinatorLegacy;
  10293. })();
  10294. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10295. })(BABYLON || (BABYLON = {}));
  10296. var BABYLON;
  10297. (function (BABYLON) {
  10298. var Camera = (function (_super) {
  10299. __extends(Camera, _super);
  10300. function Camera(name, position, scene) {
  10301. _super.call(this, name, scene);
  10302. this.upVector = BABYLON.Vector3.Up();
  10303. this.orthoLeft = null;
  10304. this.orthoRight = null;
  10305. this.orthoBottom = null;
  10306. this.orthoTop = null;
  10307. this.fov = 0.8;
  10308. this.minZ = 1.0;
  10309. this.maxZ = 10000.0;
  10310. this.inertia = 0.9;
  10311. this.mode = Camera.PERSPECTIVE_CAMERA;
  10312. this.isIntermediate = false;
  10313. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10314. this.layerMask = 0x0FFFFFFF;
  10315. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10316. // Camera rig members
  10317. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10318. this._rigCameras = new Array();
  10319. // Cache
  10320. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10321. this._projectionMatrix = new BABYLON.Matrix();
  10322. this._postProcesses = new Array();
  10323. this._postProcessesTakenIndices = [];
  10324. this._activeMeshes = new BABYLON.SmartArray(256);
  10325. this._globalPosition = BABYLON.Vector3.Zero();
  10326. scene.addCamera(this);
  10327. if (!scene.activeCamera) {
  10328. scene.activeCamera = this;
  10329. }
  10330. this.position = position;
  10331. }
  10332. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10333. get: function () {
  10334. return Camera._PERSPECTIVE_CAMERA;
  10335. },
  10336. enumerable: true,
  10337. configurable: true
  10338. });
  10339. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10340. get: function () {
  10341. return Camera._ORTHOGRAPHIC_CAMERA;
  10342. },
  10343. enumerable: true,
  10344. configurable: true
  10345. });
  10346. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10347. get: function () {
  10348. return Camera._FOVMODE_VERTICAL_FIXED;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10354. get: function () {
  10355. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10356. },
  10357. enumerable: true,
  10358. configurable: true
  10359. });
  10360. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10361. get: function () {
  10362. return Camera._RIG_MODE_NONE;
  10363. },
  10364. enumerable: true,
  10365. configurable: true
  10366. });
  10367. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10368. get: function () {
  10369. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10370. },
  10371. enumerable: true,
  10372. configurable: true
  10373. });
  10374. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10375. get: function () {
  10376. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10377. },
  10378. enumerable: true,
  10379. configurable: true
  10380. });
  10381. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10382. get: function () {
  10383. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10384. },
  10385. enumerable: true,
  10386. configurable: true
  10387. });
  10388. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10389. get: function () {
  10390. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10396. get: function () {
  10397. return Camera._RIG_MODE_VR;
  10398. },
  10399. enumerable: true,
  10400. configurable: true
  10401. });
  10402. Object.defineProperty(Camera.prototype, "globalPosition", {
  10403. get: function () {
  10404. return this._globalPosition;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Camera.prototype.getActiveMeshes = function () {
  10410. return this._activeMeshes;
  10411. };
  10412. Camera.prototype.isActiveMesh = function (mesh) {
  10413. return (this._activeMeshes.indexOf(mesh) !== -1);
  10414. };
  10415. //Cache
  10416. Camera.prototype._initCache = function () {
  10417. _super.prototype._initCache.call(this);
  10418. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10419. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10420. this._cache.mode = undefined;
  10421. this._cache.minZ = undefined;
  10422. this._cache.maxZ = undefined;
  10423. this._cache.fov = undefined;
  10424. this._cache.aspectRatio = undefined;
  10425. this._cache.orthoLeft = undefined;
  10426. this._cache.orthoRight = undefined;
  10427. this._cache.orthoBottom = undefined;
  10428. this._cache.orthoTop = undefined;
  10429. this._cache.renderWidth = undefined;
  10430. this._cache.renderHeight = undefined;
  10431. };
  10432. Camera.prototype._updateCache = function (ignoreParentClass) {
  10433. if (!ignoreParentClass) {
  10434. _super.prototype._updateCache.call(this);
  10435. }
  10436. var engine = this.getEngine();
  10437. this._cache.position.copyFrom(this.position);
  10438. this._cache.upVector.copyFrom(this.upVector);
  10439. this._cache.mode = this.mode;
  10440. this._cache.minZ = this.minZ;
  10441. this._cache.maxZ = this.maxZ;
  10442. this._cache.fov = this.fov;
  10443. this._cache.aspectRatio = engine.getAspectRatio(this);
  10444. this._cache.orthoLeft = this.orthoLeft;
  10445. this._cache.orthoRight = this.orthoRight;
  10446. this._cache.orthoBottom = this.orthoBottom;
  10447. this._cache.orthoTop = this.orthoTop;
  10448. this._cache.renderWidth = engine.getRenderWidth();
  10449. this._cache.renderHeight = engine.getRenderHeight();
  10450. };
  10451. Camera.prototype._updateFromScene = function () {
  10452. this.updateCache();
  10453. this._update();
  10454. };
  10455. // Synchronized
  10456. Camera.prototype._isSynchronized = function () {
  10457. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10458. };
  10459. Camera.prototype._isSynchronizedViewMatrix = function () {
  10460. if (!_super.prototype._isSynchronized.call(this))
  10461. return false;
  10462. return this._cache.position.equals(this.position)
  10463. && this._cache.upVector.equals(this.upVector)
  10464. && this.isSynchronizedWithParent();
  10465. };
  10466. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10467. var check = this._cache.mode === this.mode
  10468. && this._cache.minZ === this.minZ
  10469. && this._cache.maxZ === this.maxZ;
  10470. if (!check) {
  10471. return false;
  10472. }
  10473. var engine = this.getEngine();
  10474. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10475. check = this._cache.fov === this.fov
  10476. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10477. }
  10478. else {
  10479. check = this._cache.orthoLeft === this.orthoLeft
  10480. && this._cache.orthoRight === this.orthoRight
  10481. && this._cache.orthoBottom === this.orthoBottom
  10482. && this._cache.orthoTop === this.orthoTop
  10483. && this._cache.renderWidth === engine.getRenderWidth()
  10484. && this._cache.renderHeight === engine.getRenderHeight();
  10485. }
  10486. return check;
  10487. };
  10488. // Controls
  10489. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10490. };
  10491. Camera.prototype.detachControl = function (element) {
  10492. };
  10493. Camera.prototype._update = function () {
  10494. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10495. this._updateRigCameras();
  10496. }
  10497. this._checkInputs();
  10498. };
  10499. Camera.prototype._checkInputs = function () {
  10500. };
  10501. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10502. if (insertAt === void 0) { insertAt = null; }
  10503. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10504. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10505. return 0;
  10506. }
  10507. if (insertAt == null || insertAt < 0) {
  10508. this._postProcesses.push(postProcess);
  10509. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10510. return this._postProcesses.length - 1;
  10511. }
  10512. var add = 0;
  10513. var i;
  10514. var start;
  10515. if (this._postProcesses[insertAt]) {
  10516. start = this._postProcesses.length - 1;
  10517. for (i = start; i >= insertAt + 1; --i) {
  10518. this._postProcesses[i + 1] = this._postProcesses[i];
  10519. }
  10520. add = 1;
  10521. }
  10522. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10523. if (this._postProcessesTakenIndices[i] < insertAt) {
  10524. continue;
  10525. }
  10526. start = this._postProcessesTakenIndices.length - 1;
  10527. for (var j = start; j >= i; --j) {
  10528. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10529. }
  10530. this._postProcessesTakenIndices[i] = insertAt;
  10531. break;
  10532. }
  10533. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10534. this._postProcessesTakenIndices.push(insertAt);
  10535. }
  10536. var result = insertAt + add;
  10537. this._postProcesses[result] = postProcess;
  10538. return result;
  10539. };
  10540. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10541. if (atIndices === void 0) { atIndices = null; }
  10542. var result = [];
  10543. var i;
  10544. var index;
  10545. if (!atIndices) {
  10546. var length = this._postProcesses.length;
  10547. for (i = 0; i < length; i++) {
  10548. if (this._postProcesses[i] !== postProcess) {
  10549. continue;
  10550. }
  10551. delete this._postProcesses[i];
  10552. index = this._postProcessesTakenIndices.indexOf(i);
  10553. this._postProcessesTakenIndices.splice(index, 1);
  10554. }
  10555. }
  10556. else {
  10557. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10558. for (i = 0; i < atIndices.length; i++) {
  10559. var foundPostProcess = this._postProcesses[atIndices[i]];
  10560. if (foundPostProcess !== postProcess) {
  10561. result.push(i);
  10562. continue;
  10563. }
  10564. delete this._postProcesses[atIndices[i]];
  10565. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10566. this._postProcessesTakenIndices.splice(index, 1);
  10567. }
  10568. }
  10569. return result;
  10570. };
  10571. Camera.prototype.getWorldMatrix = function () {
  10572. if (!this._worldMatrix) {
  10573. this._worldMatrix = BABYLON.Matrix.Identity();
  10574. }
  10575. var viewMatrix = this.getViewMatrix();
  10576. viewMatrix.invertToRef(this._worldMatrix);
  10577. return this._worldMatrix;
  10578. };
  10579. Camera.prototype._getViewMatrix = function () {
  10580. return BABYLON.Matrix.Identity();
  10581. };
  10582. Camera.prototype.getViewMatrix = function (force) {
  10583. this._computedViewMatrix = this._computeViewMatrix(force);
  10584. if (!force && this._isSynchronizedViewMatrix()) {
  10585. return this._computedViewMatrix;
  10586. }
  10587. if (!this.parent || !this.parent.getWorldMatrix) {
  10588. this._globalPosition.copyFrom(this.position);
  10589. }
  10590. else {
  10591. if (!this._worldMatrix) {
  10592. this._worldMatrix = BABYLON.Matrix.Identity();
  10593. }
  10594. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10595. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10596. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10597. this._computedViewMatrix.invert();
  10598. this._markSyncedWithParent();
  10599. }
  10600. this._currentRenderId = this.getScene().getRenderId();
  10601. return this._computedViewMatrix;
  10602. };
  10603. Camera.prototype._computeViewMatrix = function (force) {
  10604. if (!force && this._isSynchronizedViewMatrix()) {
  10605. return this._computedViewMatrix;
  10606. }
  10607. this._computedViewMatrix = this._getViewMatrix();
  10608. this._currentRenderId = this.getScene().getRenderId();
  10609. return this._computedViewMatrix;
  10610. };
  10611. Camera.prototype.getProjectionMatrix = function (force) {
  10612. if (!force && this._isSynchronizedProjectionMatrix()) {
  10613. return this._projectionMatrix;
  10614. }
  10615. var engine = this.getEngine();
  10616. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10617. if (this.minZ <= 0) {
  10618. this.minZ = 0.1;
  10619. }
  10620. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10621. return this._projectionMatrix;
  10622. }
  10623. var halfWidth = engine.getRenderWidth() / 2.0;
  10624. var halfHeight = engine.getRenderHeight() / 2.0;
  10625. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10626. return this._projectionMatrix;
  10627. };
  10628. Camera.prototype.dispose = function () {
  10629. // Animations
  10630. this.getScene().stopAnimation(this);
  10631. // Remove from scene
  10632. this.getScene().removeCamera(this);
  10633. while (this._rigCameras.length > 0) {
  10634. this._rigCameras.pop().dispose();
  10635. }
  10636. // Postprocesses
  10637. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10638. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10639. }
  10640. };
  10641. // ---- Camera rigs section ----
  10642. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10643. while (this._rigCameras.length > 0) {
  10644. this._rigCameras.pop().dispose();
  10645. }
  10646. this.cameraRigMode = mode;
  10647. this._cameraRigParams = {};
  10648. switch (this.cameraRigMode) {
  10649. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10650. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10651. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10652. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10653. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10654. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10655. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10656. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10657. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10658. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10659. break;
  10660. }
  10661. var postProcesses = new Array();
  10662. switch (this.cameraRigMode) {
  10663. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10664. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10665. this._rigCameras[0].isIntermediate = true;
  10666. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10667. postProcesses[1].onApply = function (effect) {
  10668. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10669. };
  10670. break;
  10671. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10672. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10673. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10674. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10675. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10676. var secondCamIndex = 1 - firstCamIndex;
  10677. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10678. this._rigCameras[firstCamIndex].isIntermediate = true;
  10679. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10680. break;
  10681. case Camera.RIG_MODE_VR:
  10682. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10683. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10684. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10685. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10686. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10687. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10688. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10689. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10690. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10691. if (metrics.compensateDistortion) {
  10692. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10693. }
  10694. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10695. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10696. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10697. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10698. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10699. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10700. if (metrics.compensateDistortion) {
  10701. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10702. }
  10703. break;
  10704. }
  10705. this._update();
  10706. };
  10707. Camera.prototype._getVRProjectionMatrix = function () {
  10708. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10709. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10710. return this._projectionMatrix;
  10711. };
  10712. Camera.prototype.setCameraRigParameter = function (name, value) {
  10713. this._cameraRigParams[name] = value;
  10714. //provisionnally:
  10715. if (name === "interaxialDistance") {
  10716. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10717. }
  10718. };
  10719. /**
  10720. * May needs to be overridden by children so sub has required properties to be copied
  10721. */
  10722. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10723. return null;
  10724. };
  10725. /**
  10726. * May needs to be overridden by children
  10727. */
  10728. Camera.prototype._updateRigCameras = function () {
  10729. for (var i = 0; i < this._rigCameras.length; i++) {
  10730. this._rigCameras[i].minZ = this.minZ;
  10731. this._rigCameras[i].maxZ = this.maxZ;
  10732. this._rigCameras[i].fov = this.fov;
  10733. }
  10734. // only update viewport when ANAGLYPH
  10735. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10736. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10737. }
  10738. };
  10739. Camera.prototype.serialize = function () {
  10740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10741. // Type
  10742. serializationObject.type = this.getTypeName();
  10743. // Parent
  10744. if (this.parent) {
  10745. serializationObject.parentId = this.parent.id;
  10746. }
  10747. // Animations
  10748. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10749. serializationObject.ranges = this.serializeAnimationRanges();
  10750. return serializationObject;
  10751. };
  10752. Camera.prototype.getTypeName = function () {
  10753. return "Camera";
  10754. };
  10755. Camera.prototype.clone = function (name) {
  10756. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10757. };
  10758. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10759. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10760. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10761. switch (type) {
  10762. case "ArcRotateCamera":
  10763. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10764. case "DeviceOrientationCamera":
  10765. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10766. case "FollowCamera":
  10767. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10768. case "ArcFollowCamera":
  10769. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10770. case "GamepadCamera":
  10771. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10772. case "TouchCamera":
  10773. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10774. case "VirtualJoysticksCamera":
  10775. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10776. case "WebVRFreeCamera":
  10777. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10778. case "VRDeviceOrientationFreeCamera":
  10779. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10780. case "AnaglyphArcRotateCamera":
  10781. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10782. case "AnaglyphFreeCamera":
  10783. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10784. case "AnaglyphGamepadCamera":
  10785. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10786. case "AnaglyphUniversalCamera":
  10787. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10788. case "StereoscopicArcRotateCamera":
  10789. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10790. case "StereoscopicFreeCamera":
  10791. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10792. case "StereoscopicGamepadCamera":
  10793. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10794. case "StereoscopicUniversalCamera":
  10795. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10796. case "FreeCamera":
  10797. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10798. default:
  10799. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10800. }
  10801. };
  10802. Camera.Parse = function (parsedCamera, scene) {
  10803. var type = parsedCamera.type;
  10804. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10805. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10806. // Parent
  10807. if (parsedCamera.parentId) {
  10808. camera._waitingParentId = parsedCamera.parentId;
  10809. }
  10810. // Target
  10811. if (parsedCamera.target) {
  10812. if (camera.setTarget) {
  10813. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10814. }
  10815. }
  10816. // Apply 3d rig, when found
  10817. if (parsedCamera.cameraRigMode) {
  10818. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10819. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10820. }
  10821. // Animations
  10822. if (parsedCamera.animations) {
  10823. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10824. var parsedAnimation = parsedCamera.animations[animationIndex];
  10825. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10826. }
  10827. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10828. }
  10829. if (parsedCamera.autoAnimate) {
  10830. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10831. }
  10832. return camera;
  10833. };
  10834. // Statics
  10835. Camera._PERSPECTIVE_CAMERA = 0;
  10836. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10837. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10838. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10839. Camera._RIG_MODE_NONE = 0;
  10840. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10841. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10842. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10843. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10844. Camera._RIG_MODE_VR = 20;
  10845. __decorate([
  10846. BABYLON.serializeAsVector3()
  10847. ], Camera.prototype, "position", void 0);
  10848. __decorate([
  10849. BABYLON.serialize()
  10850. ], Camera.prototype, "upVector", void 0);
  10851. __decorate([
  10852. BABYLON.serialize()
  10853. ], Camera.prototype, "orthoLeft", void 0);
  10854. __decorate([
  10855. BABYLON.serialize()
  10856. ], Camera.prototype, "orthoRight", void 0);
  10857. __decorate([
  10858. BABYLON.serialize()
  10859. ], Camera.prototype, "orthoBottom", void 0);
  10860. __decorate([
  10861. BABYLON.serialize()
  10862. ], Camera.prototype, "orthoTop", void 0);
  10863. __decorate([
  10864. BABYLON.serialize()
  10865. ], Camera.prototype, "fov", void 0);
  10866. __decorate([
  10867. BABYLON.serialize()
  10868. ], Camera.prototype, "minZ", void 0);
  10869. __decorate([
  10870. BABYLON.serialize()
  10871. ], Camera.prototype, "maxZ", void 0);
  10872. __decorate([
  10873. BABYLON.serialize()
  10874. ], Camera.prototype, "inertia", void 0);
  10875. __decorate([
  10876. BABYLON.serialize()
  10877. ], Camera.prototype, "mode", void 0);
  10878. __decorate([
  10879. BABYLON.serialize()
  10880. ], Camera.prototype, "layerMask", void 0);
  10881. __decorate([
  10882. BABYLON.serialize()
  10883. ], Camera.prototype, "fovMode", void 0);
  10884. __decorate([
  10885. BABYLON.serialize()
  10886. ], Camera.prototype, "cameraRigMode", void 0);
  10887. __decorate([
  10888. BABYLON.serialize()
  10889. ], Camera.prototype, "interaxialDistance", void 0);
  10890. __decorate([
  10891. BABYLON.serialize()
  10892. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10893. return Camera;
  10894. })(BABYLON.Node);
  10895. BABYLON.Camera = Camera;
  10896. })(BABYLON || (BABYLON = {}));
  10897. var BABYLON;
  10898. (function (BABYLON) {
  10899. var TargetCamera = (function (_super) {
  10900. __extends(TargetCamera, _super);
  10901. function TargetCamera(name, position, scene) {
  10902. _super.call(this, name, position, scene);
  10903. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10904. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10905. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10906. this.speed = 2.0;
  10907. this.noRotationConstraint = false;
  10908. this.lockedTarget = null;
  10909. this._currentTarget = BABYLON.Vector3.Zero();
  10910. this._viewMatrix = BABYLON.Matrix.Zero();
  10911. this._camMatrix = BABYLON.Matrix.Zero();
  10912. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10913. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10914. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10915. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10916. this._lookAtTemp = BABYLON.Matrix.Zero();
  10917. this._tempMatrix = BABYLON.Matrix.Zero();
  10918. }
  10919. TargetCamera.prototype.getFrontPosition = function (distance) {
  10920. var direction = this.getTarget().subtract(this.position);
  10921. direction.normalize();
  10922. direction.scaleInPlace(distance);
  10923. return this.globalPosition.add(direction);
  10924. };
  10925. TargetCamera.prototype._getLockedTargetPosition = function () {
  10926. if (!this.lockedTarget) {
  10927. return null;
  10928. }
  10929. return this.lockedTarget.position || this.lockedTarget;
  10930. };
  10931. // Cache
  10932. TargetCamera.prototype._initCache = function () {
  10933. _super.prototype._initCache.call(this);
  10934. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10935. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10936. };
  10937. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10938. if (!ignoreParentClass) {
  10939. _super.prototype._updateCache.call(this);
  10940. }
  10941. var lockedTargetPosition = this._getLockedTargetPosition();
  10942. if (!lockedTargetPosition) {
  10943. this._cache.lockedTarget = null;
  10944. }
  10945. else {
  10946. if (!this._cache.lockedTarget) {
  10947. this._cache.lockedTarget = lockedTargetPosition.clone();
  10948. }
  10949. else {
  10950. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10951. }
  10952. }
  10953. this._cache.rotation.copyFrom(this.rotation);
  10954. };
  10955. // Synchronized
  10956. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10957. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10958. return false;
  10959. }
  10960. var lockedTargetPosition = this._getLockedTargetPosition();
  10961. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10962. && this._cache.rotation.equals(this.rotation);
  10963. };
  10964. // Methods
  10965. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10966. var engine = this.getEngine();
  10967. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10968. };
  10969. // Target
  10970. TargetCamera.prototype.setTarget = function (target) {
  10971. this.upVector.normalize();
  10972. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10973. this._camMatrix.invert();
  10974. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10975. var vDir = target.subtract(this.position);
  10976. if (vDir.x >= 0.0) {
  10977. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10978. }
  10979. else {
  10980. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10981. }
  10982. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10983. if (isNaN(this.rotation.x)) {
  10984. this.rotation.x = 0;
  10985. }
  10986. if (isNaN(this.rotation.y)) {
  10987. this.rotation.y = 0;
  10988. }
  10989. if (isNaN(this.rotation.z)) {
  10990. this.rotation.z = 0;
  10991. }
  10992. };
  10993. TargetCamera.prototype.getTarget = function () {
  10994. return this._currentTarget;
  10995. };
  10996. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10997. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10998. };
  10999. TargetCamera.prototype._updatePosition = function () {
  11000. this.position.addInPlace(this.cameraDirection);
  11001. };
  11002. TargetCamera.prototype._checkInputs = function () {
  11003. var needToMove = this._decideIfNeedsToMove();
  11004. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11005. // Move
  11006. if (needToMove) {
  11007. this._updatePosition();
  11008. }
  11009. // Rotate
  11010. if (needToRotate) {
  11011. this.rotation.x += this.cameraRotation.x;
  11012. this.rotation.y += this.cameraRotation.y;
  11013. if (!this.noRotationConstraint) {
  11014. var limit = (Math.PI / 2) * 0.95;
  11015. if (this.rotation.x > limit)
  11016. this.rotation.x = limit;
  11017. if (this.rotation.x < -limit)
  11018. this.rotation.x = -limit;
  11019. }
  11020. }
  11021. // Inertia
  11022. if (needToMove) {
  11023. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11024. this.cameraDirection.x = 0;
  11025. }
  11026. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11027. this.cameraDirection.y = 0;
  11028. }
  11029. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11030. this.cameraDirection.z = 0;
  11031. }
  11032. this.cameraDirection.scaleInPlace(this.inertia);
  11033. }
  11034. if (needToRotate) {
  11035. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11036. this.cameraRotation.x = 0;
  11037. }
  11038. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11039. this.cameraRotation.y = 0;
  11040. }
  11041. this.cameraRotation.scaleInPlace(this.inertia);
  11042. }
  11043. _super.prototype._checkInputs.call(this);
  11044. };
  11045. TargetCamera.prototype._getViewMatrix = function () {
  11046. if (!this.lockedTarget) {
  11047. // Compute
  11048. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11049. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11050. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11051. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11052. this._lookAtTemp.invert();
  11053. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11054. }
  11055. else {
  11056. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11057. }
  11058. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11059. // Computing target and final matrix
  11060. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11061. }
  11062. else {
  11063. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11064. }
  11065. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11066. return this._viewMatrix;
  11067. };
  11068. TargetCamera.prototype._getVRViewMatrix = function () {
  11069. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11070. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11071. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11072. // Computing target and final matrix
  11073. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11074. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11075. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11076. return this._viewMatrix;
  11077. };
  11078. /**
  11079. * @override
  11080. * Override Camera.createRigCamera
  11081. */
  11082. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11083. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11084. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11085. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11086. rigCamera._cameraRigParams = {};
  11087. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11088. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11089. }
  11090. return rigCamera;
  11091. }
  11092. return null;
  11093. };
  11094. /**
  11095. * @override
  11096. * Override Camera._updateRigCameras
  11097. */
  11098. TargetCamera.prototype._updateRigCameras = function () {
  11099. switch (this.cameraRigMode) {
  11100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11104. case BABYLON.Camera.RIG_MODE_VR:
  11105. var camLeft = this._rigCameras[0];
  11106. var camRight = this._rigCameras[1];
  11107. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11108. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11109. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11110. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11111. camLeft.position.copyFrom(this.position);
  11112. camRight.position.copyFrom(this.position);
  11113. }
  11114. else {
  11115. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11116. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11117. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11118. camLeft.setTarget(this.getTarget());
  11119. camRight.setTarget(this.getTarget());
  11120. }
  11121. break;
  11122. }
  11123. _super.prototype._updateRigCameras.call(this);
  11124. };
  11125. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11126. if (!this._rigCamTransformMatrix) {
  11127. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11128. }
  11129. var target = this.getTarget();
  11130. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11131. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11132. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11133. };
  11134. TargetCamera.prototype.getTypeName = function () {
  11135. return "TargetCamera";
  11136. };
  11137. __decorate([
  11138. BABYLON.serializeAsVector3()
  11139. ], TargetCamera.prototype, "rotation", void 0);
  11140. __decorate([
  11141. BABYLON.serialize()
  11142. ], TargetCamera.prototype, "speed", void 0);
  11143. __decorate([
  11144. BABYLON.serializeAsMeshReference("lockedTargetId")
  11145. ], TargetCamera.prototype, "lockedTarget", void 0);
  11146. return TargetCamera;
  11147. })(BABYLON.Camera);
  11148. BABYLON.TargetCamera = TargetCamera;
  11149. })(BABYLON || (BABYLON = {}));
  11150. var BABYLON;
  11151. (function (BABYLON) {
  11152. var FreeCamera = (function (_super) {
  11153. __extends(FreeCamera, _super);
  11154. function FreeCamera(name, position, scene) {
  11155. var _this = this;
  11156. _super.call(this, name, position, scene);
  11157. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11158. this.keysUp = [38];
  11159. this.keysDown = [40];
  11160. this.keysLeft = [37];
  11161. this.keysRight = [39];
  11162. this.checkCollisions = false;
  11163. this.applyGravity = false;
  11164. this.angularSensibility = 2000.0;
  11165. this._keys = [];
  11166. this._collider = new BABYLON.Collider();
  11167. this._needMoveForGravity = false;
  11168. this._oldPosition = BABYLON.Vector3.Zero();
  11169. this._diffPosition = BABYLON.Vector3.Zero();
  11170. this._newPosition = BABYLON.Vector3.Zero();
  11171. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11172. if (collidedMesh === void 0) { collidedMesh = null; }
  11173. //TODO move this to the collision coordinator!
  11174. if (_this.getScene().workerCollisions)
  11175. newPosition.multiplyInPlace(_this._collider.radius);
  11176. var updatePosition = function (newPos) {
  11177. _this._newPosition.copyFrom(newPos);
  11178. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11179. var oldPosition = _this.position.clone();
  11180. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11181. _this.position.addInPlace(_this._diffPosition);
  11182. if (_this.onCollide && collidedMesh) {
  11183. _this.onCollide(collidedMesh);
  11184. }
  11185. }
  11186. };
  11187. updatePosition(newPosition);
  11188. };
  11189. }
  11190. FreeCamera.prototype._onLostFocus = function (e) {
  11191. this._keys = [];
  11192. };
  11193. // Controls
  11194. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11195. var _this = this;
  11196. var previousPosition;
  11197. var engine = this.getEngine();
  11198. if (this._attachedElement) {
  11199. return;
  11200. }
  11201. this._attachedElement = element;
  11202. if (this._onMouseDown === undefined) {
  11203. this._onMouseDown = function (evt) {
  11204. previousPosition = {
  11205. x: evt.clientX,
  11206. y: evt.clientY
  11207. };
  11208. if (!noPreventDefault) {
  11209. evt.preventDefault();
  11210. }
  11211. };
  11212. this._onMouseUp = function (evt) {
  11213. previousPosition = null;
  11214. if (!noPreventDefault) {
  11215. evt.preventDefault();
  11216. }
  11217. };
  11218. this._onMouseOut = function (evt) {
  11219. previousPosition = null;
  11220. _this._keys = [];
  11221. if (!noPreventDefault) {
  11222. evt.preventDefault();
  11223. }
  11224. };
  11225. this._onMouseMove = function (evt) {
  11226. if (!previousPosition && !engine.isPointerLock) {
  11227. return;
  11228. }
  11229. var offsetX;
  11230. var offsetY;
  11231. if (!engine.isPointerLock) {
  11232. offsetX = evt.clientX - previousPosition.x;
  11233. offsetY = evt.clientY - previousPosition.y;
  11234. }
  11235. else {
  11236. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11237. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11238. }
  11239. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11240. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11241. previousPosition = {
  11242. x: evt.clientX,
  11243. y: evt.clientY
  11244. };
  11245. if (!noPreventDefault) {
  11246. evt.preventDefault();
  11247. }
  11248. };
  11249. this._onKeyDown = function (evt) {
  11250. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11251. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11252. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11253. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11254. var index = _this._keys.indexOf(evt.keyCode);
  11255. if (index === -1) {
  11256. _this._keys.push(evt.keyCode);
  11257. }
  11258. if (!noPreventDefault) {
  11259. evt.preventDefault();
  11260. }
  11261. }
  11262. };
  11263. this._onKeyUp = function (evt) {
  11264. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11265. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11266. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11267. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11268. var index = _this._keys.indexOf(evt.keyCode);
  11269. if (index >= 0) {
  11270. _this._keys.splice(index, 1);
  11271. }
  11272. if (!noPreventDefault) {
  11273. evt.preventDefault();
  11274. }
  11275. }
  11276. };
  11277. this._reset = function () {
  11278. _this._keys = [];
  11279. previousPosition = null;
  11280. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11281. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11282. };
  11283. }
  11284. element.addEventListener("mousedown", this._onMouseDown, false);
  11285. element.addEventListener("mouseup", this._onMouseUp, false);
  11286. element.addEventListener("mouseout", this._onMouseOut, false);
  11287. element.addEventListener("mousemove", this._onMouseMove, false);
  11288. BABYLON.Tools.RegisterTopRootEvents([
  11289. { name: "keydown", handler: this._onKeyDown },
  11290. { name: "keyup", handler: this._onKeyUp },
  11291. { name: "blur", handler: this._onLostFocus }
  11292. ]);
  11293. };
  11294. FreeCamera.prototype.detachControl = function (element) {
  11295. if (this._attachedElement !== element) {
  11296. return;
  11297. }
  11298. element.removeEventListener("mousedown", this._onMouseDown);
  11299. element.removeEventListener("mouseup", this._onMouseUp);
  11300. element.removeEventListener("mouseout", this._onMouseOut);
  11301. element.removeEventListener("mousemove", this._onMouseMove);
  11302. BABYLON.Tools.UnregisterTopRootEvents([
  11303. { name: "keydown", handler: this._onKeyDown },
  11304. { name: "keyup", handler: this._onKeyUp },
  11305. { name: "blur", handler: this._onLostFocus }
  11306. ]);
  11307. this._attachedElement = null;
  11308. if (this._reset) {
  11309. this._reset();
  11310. }
  11311. };
  11312. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11313. var globalPosition;
  11314. if (this.parent) {
  11315. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11316. }
  11317. else {
  11318. globalPosition = this.position;
  11319. }
  11320. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11321. this._collider.radius = this.ellipsoid;
  11322. //no need for clone, as long as gravity is not on.
  11323. var actualVelocity = velocity;
  11324. //add gravity to the velocity to prevent the dual-collision checking
  11325. if (this.applyGravity) {
  11326. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11327. actualVelocity = velocity.add(this.getScene().gravity);
  11328. }
  11329. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11330. };
  11331. FreeCamera.prototype._checkInputs = function () {
  11332. if (!this._localDirection) {
  11333. this._localDirection = BABYLON.Vector3.Zero();
  11334. this._transformedDirection = BABYLON.Vector3.Zero();
  11335. }
  11336. // Keyboard
  11337. for (var index = 0; index < this._keys.length; index++) {
  11338. var keyCode = this._keys[index];
  11339. var speed = this._computeLocalCameraSpeed();
  11340. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11341. this._localDirection.copyFromFloats(-speed, 0, 0);
  11342. }
  11343. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11344. this._localDirection.copyFromFloats(0, 0, speed);
  11345. }
  11346. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11347. this._localDirection.copyFromFloats(speed, 0, 0);
  11348. }
  11349. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11350. this._localDirection.copyFromFloats(0, 0, -speed);
  11351. }
  11352. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11353. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11354. this.cameraDirection.addInPlace(this._transformedDirection);
  11355. }
  11356. _super.prototype._checkInputs.call(this);
  11357. };
  11358. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11359. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11360. };
  11361. FreeCamera.prototype._updatePosition = function () {
  11362. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11363. this._collideWithWorld(this.cameraDirection);
  11364. }
  11365. else {
  11366. this.position.addInPlace(this.cameraDirection);
  11367. }
  11368. };
  11369. FreeCamera.prototype.getTypeName = function () {
  11370. return "FreeCamera";
  11371. };
  11372. __decorate([
  11373. BABYLON.serializeAsVector3()
  11374. ], FreeCamera.prototype, "ellipsoid", void 0);
  11375. __decorate([
  11376. BABYLON.serialize()
  11377. ], FreeCamera.prototype, "keysUp", void 0);
  11378. __decorate([
  11379. BABYLON.serialize()
  11380. ], FreeCamera.prototype, "keysDown", void 0);
  11381. __decorate([
  11382. BABYLON.serialize()
  11383. ], FreeCamera.prototype, "keysLeft", void 0);
  11384. __decorate([
  11385. BABYLON.serialize()
  11386. ], FreeCamera.prototype, "keysRight", void 0);
  11387. __decorate([
  11388. BABYLON.serialize()
  11389. ], FreeCamera.prototype, "checkCollisions", void 0);
  11390. __decorate([
  11391. BABYLON.serialize()
  11392. ], FreeCamera.prototype, "applyGravity", void 0);
  11393. __decorate([
  11394. BABYLON.serialize()
  11395. ], FreeCamera.prototype, "angularSensibility", void 0);
  11396. return FreeCamera;
  11397. })(BABYLON.TargetCamera);
  11398. BABYLON.FreeCamera = FreeCamera;
  11399. })(BABYLON || (BABYLON = {}));
  11400. var BABYLON;
  11401. (function (BABYLON) {
  11402. var FollowCamera = (function (_super) {
  11403. __extends(FollowCamera, _super);
  11404. function FollowCamera(name, position, scene, target) {
  11405. _super.call(this, name, position, scene);
  11406. this.radius = 12;
  11407. this.rotationOffset = 0;
  11408. this.heightOffset = 4;
  11409. this.cameraAcceleration = 0.05;
  11410. this.maxCameraSpeed = 20;
  11411. this.target = target;
  11412. }
  11413. FollowCamera.prototype.getRadians = function (degrees) {
  11414. return degrees * Math.PI / 180;
  11415. };
  11416. FollowCamera.prototype.follow = function (cameraTarget) {
  11417. if (!cameraTarget)
  11418. return;
  11419. var yRotation;
  11420. if (cameraTarget.rotationQuaternion) {
  11421. var rotMatrix = new BABYLON.Matrix();
  11422. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11423. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11424. }
  11425. else {
  11426. yRotation = cameraTarget.rotation.y;
  11427. }
  11428. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11429. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11430. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11431. var dx = targetX - this.position.x;
  11432. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11433. var dz = (targetZ) - this.position.z;
  11434. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11435. var vy = dy * this.cameraAcceleration;
  11436. var vz = dz * this.cameraAcceleration * 2;
  11437. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11438. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11439. }
  11440. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11441. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11442. }
  11443. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11444. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11445. }
  11446. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11447. this.setTarget(cameraTarget.position);
  11448. };
  11449. FollowCamera.prototype._checkInputs = function () {
  11450. _super.prototype._checkInputs.call(this);
  11451. this.follow(this.target);
  11452. };
  11453. FollowCamera.prototype.getTypeName = function () {
  11454. return "FollowCamera";
  11455. };
  11456. __decorate([
  11457. BABYLON.serialize()
  11458. ], FollowCamera.prototype, "radius", void 0);
  11459. __decorate([
  11460. BABYLON.serialize()
  11461. ], FollowCamera.prototype, "rotationOffset", void 0);
  11462. __decorate([
  11463. BABYLON.serialize()
  11464. ], FollowCamera.prototype, "heightOffset", void 0);
  11465. __decorate([
  11466. BABYLON.serialize()
  11467. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11468. __decorate([
  11469. BABYLON.serialize()
  11470. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11471. __decorate([
  11472. BABYLON.serializeAsMeshReference("lockedTargetId")
  11473. ], FollowCamera.prototype, "target", void 0);
  11474. return FollowCamera;
  11475. })(BABYLON.TargetCamera);
  11476. BABYLON.FollowCamera = FollowCamera;
  11477. var ArcFollowCamera = (function (_super) {
  11478. __extends(ArcFollowCamera, _super);
  11479. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11480. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11481. this.alpha = alpha;
  11482. this.beta = beta;
  11483. this.radius = radius;
  11484. this.target = target;
  11485. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11486. this.follow();
  11487. }
  11488. ArcFollowCamera.prototype.follow = function () {
  11489. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11490. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11491. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11492. this.position = this.target.position.add(this._cartesianCoordinates);
  11493. this.setTarget(this.target.position);
  11494. };
  11495. ArcFollowCamera.prototype._checkInputs = function () {
  11496. _super.prototype._checkInputs.call(this);
  11497. this.follow();
  11498. };
  11499. ArcFollowCamera.prototype.getTypeName = function () {
  11500. return "ArcFollowCamera";
  11501. };
  11502. return ArcFollowCamera;
  11503. })(BABYLON.TargetCamera);
  11504. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11505. })(BABYLON || (BABYLON = {}));
  11506. var BABYLON;
  11507. (function (BABYLON) {
  11508. // We're mainly based on the logic defined into the FreeCamera code
  11509. var TouchCamera = (function (_super) {
  11510. __extends(TouchCamera, _super);
  11511. function TouchCamera(name, position, scene) {
  11512. _super.call(this, name, position, scene);
  11513. this._offsetX = null;
  11514. this._offsetY = null;
  11515. this._pointerCount = 0;
  11516. this._pointerPressed = [];
  11517. this.touchAngularSensibility = 200000.0;
  11518. this.touchMoveSensibility = 250.0;
  11519. }
  11520. TouchCamera.prototype._onLostFocus = function (e) {
  11521. this._offsetX = null;
  11522. this._offsetY = null;
  11523. _super.prototype._onLostFocus.call(this, e);
  11524. };
  11525. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11526. var _this = this;
  11527. var previousPosition;
  11528. if (this._attachedCanvas) {
  11529. return;
  11530. }
  11531. if (this._onPointerDown === undefined) {
  11532. this._onPointerDown = function (evt) {
  11533. if (evt.pointerType === "mouse") {
  11534. return;
  11535. }
  11536. if (!noPreventDefault) {
  11537. evt.preventDefault();
  11538. }
  11539. _this._pointerPressed.push(evt.pointerId);
  11540. if (_this._pointerPressed.length !== 1) {
  11541. return;
  11542. }
  11543. previousPosition = {
  11544. x: evt.clientX,
  11545. y: evt.clientY
  11546. };
  11547. };
  11548. this._onPointerUp = function (evt) {
  11549. if (evt.pointerType === "mouse") {
  11550. return;
  11551. }
  11552. if (!noPreventDefault) {
  11553. evt.preventDefault();
  11554. }
  11555. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11556. if (index === -1) {
  11557. return;
  11558. }
  11559. _this._pointerPressed.splice(index, 1);
  11560. if (index != 0) {
  11561. return;
  11562. }
  11563. previousPosition = null;
  11564. _this._offsetX = null;
  11565. _this._offsetY = null;
  11566. };
  11567. this._onPointerMove = function (evt) {
  11568. if (evt.pointerType === "mouse") {
  11569. return;
  11570. }
  11571. if (!noPreventDefault) {
  11572. evt.preventDefault();
  11573. }
  11574. if (!previousPosition) {
  11575. return;
  11576. }
  11577. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11578. if (index != 0) {
  11579. return;
  11580. }
  11581. _this._offsetX = evt.clientX - previousPosition.x;
  11582. _this._offsetY = -(evt.clientY - previousPosition.y);
  11583. };
  11584. }
  11585. canvas.addEventListener("pointerdown", this._onPointerDown);
  11586. canvas.addEventListener("pointerup", this._onPointerUp);
  11587. canvas.addEventListener("pointerout", this._onPointerUp);
  11588. canvas.addEventListener("pointermove", this._onPointerMove);
  11589. _super.prototype.attachControl.call(this, canvas);
  11590. };
  11591. TouchCamera.prototype.detachControl = function (canvas) {
  11592. if (this._attachedCanvas !== canvas) {
  11593. return;
  11594. }
  11595. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11596. canvas.removeEventListener("pointerup", this._onPointerUp);
  11597. canvas.removeEventListener("pointerout", this._onPointerUp);
  11598. canvas.removeEventListener("pointermove", this._onPointerMove);
  11599. _super.prototype.detachControl.call(this, canvas);
  11600. };
  11601. TouchCamera.prototype._checkInputs = function () {
  11602. if (this._offsetX) {
  11603. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11604. if (this._pointerPressed.length > 1) {
  11605. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11606. }
  11607. else {
  11608. var speed = this._computeLocalCameraSpeed();
  11609. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11610. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11611. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11612. }
  11613. }
  11614. _super.prototype._checkInputs.call(this);
  11615. };
  11616. TouchCamera.prototype.getTypeName = function () {
  11617. return "TouchCamera";
  11618. };
  11619. __decorate([
  11620. BABYLON.serialize()
  11621. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11622. __decorate([
  11623. BABYLON.serialize()
  11624. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11625. return TouchCamera;
  11626. })(BABYLON.FreeCamera);
  11627. BABYLON.TouchCamera = TouchCamera;
  11628. })(BABYLON || (BABYLON = {}));
  11629. var BABYLON;
  11630. (function (BABYLON) {
  11631. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11632. var ArcRotateCamera = (function (_super) {
  11633. __extends(ArcRotateCamera, _super);
  11634. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11635. var _this = this;
  11636. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11637. this.inertialAlphaOffset = 0;
  11638. this.inertialBetaOffset = 0;
  11639. this.inertialRadiusOffset = 0;
  11640. this.lowerAlphaLimit = null;
  11641. this.upperAlphaLimit = null;
  11642. this.lowerBetaLimit = 0.01;
  11643. this.upperBetaLimit = Math.PI;
  11644. this.lowerRadiusLimit = null;
  11645. this.upperRadiusLimit = null;
  11646. this.angularSensibilityX = 1000.0;
  11647. this.angularSensibilityY = 1000.0;
  11648. this.wheelPrecision = 3.0;
  11649. this.pinchPrecision = 2.0;
  11650. this.panningSensibility = 50.0;
  11651. this.inertialPanningX = 0;
  11652. this.inertialPanningY = 0;
  11653. this.keysUp = [38];
  11654. this.keysDown = [40];
  11655. this.keysLeft = [37];
  11656. this.keysRight = [39];
  11657. this.zoomOnFactor = 1;
  11658. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11659. this.pinchInwards = true;
  11660. this.allowUpsideDown = true;
  11661. this._keys = [];
  11662. this._viewMatrix = new BABYLON.Matrix();
  11663. // Panning
  11664. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11665. this._isRightClick = false;
  11666. this._isCtrlPushed = false;
  11667. this.checkCollisions = false;
  11668. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11669. this._collider = new BABYLON.Collider();
  11670. this._previousPosition = BABYLON.Vector3.Zero();
  11671. this._collisionVelocity = BABYLON.Vector3.Zero();
  11672. this._newPosition = BABYLON.Vector3.Zero();
  11673. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11674. if (collidedMesh === void 0) { collidedMesh = null; }
  11675. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11676. newPosition.multiplyInPlace(_this._collider.radius);
  11677. }
  11678. if (!collidedMesh) {
  11679. _this._previousPosition.copyFrom(_this.position);
  11680. }
  11681. else {
  11682. _this.setPosition(newPosition);
  11683. if (_this.onCollide) {
  11684. _this.onCollide(collidedMesh);
  11685. }
  11686. }
  11687. // Recompute because of constraints
  11688. var cosa = Math.cos(_this.alpha);
  11689. var sina = Math.sin(_this.alpha);
  11690. var cosb = Math.cos(_this.beta);
  11691. var sinb = Math.sin(_this.beta);
  11692. if (sinb === 0) {
  11693. sinb = 0.0001;
  11694. }
  11695. var target = _this.target;
  11696. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11697. _this.position.copyFrom(_this._newPosition);
  11698. var up = _this.upVector;
  11699. if (_this.allowUpsideDown && _this.beta < 0) {
  11700. up = up.clone();
  11701. up = up.negate();
  11702. }
  11703. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11704. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11705. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11706. _this._collisionTriggered = false;
  11707. };
  11708. if (!this.target) {
  11709. this.target = BABYLON.Vector3.Zero();
  11710. }
  11711. else {
  11712. this.target = target;
  11713. }
  11714. this.alpha = alpha;
  11715. this.beta = beta;
  11716. this.radius = radius;
  11717. this.getViewMatrix();
  11718. }
  11719. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11720. //deprecated angularSensibility support
  11721. get: function () {
  11722. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11723. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11724. },
  11725. //deprecated angularSensibility support
  11726. set: function (value) {
  11727. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11728. this.angularSensibilityX = value;
  11729. this.angularSensibilityY = value;
  11730. },
  11731. enumerable: true,
  11732. configurable: true
  11733. });
  11734. // Cache
  11735. ArcRotateCamera.prototype._initCache = function () {
  11736. _super.prototype._initCache.call(this);
  11737. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11738. this._cache.alpha = undefined;
  11739. this._cache.beta = undefined;
  11740. this._cache.radius = undefined;
  11741. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11742. };
  11743. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11744. if (!ignoreParentClass) {
  11745. _super.prototype._updateCache.call(this);
  11746. }
  11747. this._cache.target.copyFrom(this.target);
  11748. this._cache.alpha = this.alpha;
  11749. this._cache.beta = this.beta;
  11750. this._cache.radius = this.radius;
  11751. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11752. };
  11753. // Synchronized
  11754. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11755. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11756. return false;
  11757. return this._cache.target.equals(this.target)
  11758. && this._cache.alpha === this.alpha
  11759. && this._cache.beta === this.beta
  11760. && this._cache.radius === this.radius
  11761. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11762. };
  11763. // Methods
  11764. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11765. var _this = this;
  11766. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11767. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11768. var previousPinchDistance = 0;
  11769. var pointers = new BABYLON.SmartCollection();
  11770. if (this._attachedElement) {
  11771. return;
  11772. }
  11773. this._attachedElement = element;
  11774. var engine = this.getEngine();
  11775. if (this._onPointerDown === undefined) {
  11776. this._onPointerDown = function (evt) {
  11777. // Manage panning with right click
  11778. _this._isRightClick = evt.button === 2;
  11779. // manage pointers
  11780. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11781. cacheSoloPointer = pointers.item(evt.pointerId);
  11782. if (!noPreventDefault) {
  11783. evt.preventDefault();
  11784. }
  11785. };
  11786. this._onPointerUp = function (evt) {
  11787. cacheSoloPointer = null;
  11788. previousPinchDistance = 0;
  11789. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11790. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11791. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11792. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11793. pointers.empty();
  11794. if (!noPreventDefault) {
  11795. evt.preventDefault();
  11796. }
  11797. };
  11798. this._onContextMenu = function (evt) {
  11799. evt.preventDefault();
  11800. };
  11801. this._onPointerMove = function (evt) {
  11802. if (!noPreventDefault) {
  11803. evt.preventDefault();
  11804. }
  11805. switch (pointers.count) {
  11806. case 1:
  11807. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11808. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11809. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11810. }
  11811. else {
  11812. var offsetX = evt.clientX - cacheSoloPointer.x;
  11813. var offsetY = evt.clientY - cacheSoloPointer.y;
  11814. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11815. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11816. }
  11817. cacheSoloPointer.x = evt.clientX;
  11818. cacheSoloPointer.y = evt.clientY;
  11819. break;
  11820. case 2:
  11821. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11822. pointers.item(evt.pointerId).x = evt.clientX;
  11823. pointers.item(evt.pointerId).y = evt.clientY;
  11824. var direction = _this.pinchInwards ? 1 : -1;
  11825. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11826. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11827. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11828. if (previousPinchDistance === 0) {
  11829. previousPinchDistance = pinchSquaredDistance;
  11830. return;
  11831. }
  11832. if (pinchSquaredDistance !== previousPinchDistance) {
  11833. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11834. previousPinchDistance = pinchSquaredDistance;
  11835. }
  11836. break;
  11837. default:
  11838. if (pointers.item(evt.pointerId)) {
  11839. pointers.item(evt.pointerId).x = evt.clientX;
  11840. pointers.item(evt.pointerId).y = evt.clientY;
  11841. }
  11842. }
  11843. };
  11844. this._onMouseMove = function (evt) {
  11845. if (!engine.isPointerLock) {
  11846. return;
  11847. }
  11848. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11849. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11850. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11851. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11852. if (!noPreventDefault) {
  11853. evt.preventDefault();
  11854. }
  11855. };
  11856. this._wheel = function (event) {
  11857. var delta = 0;
  11858. if (event.wheelDelta) {
  11859. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11860. }
  11861. else if (event.detail) {
  11862. delta = -event.detail / _this.wheelPrecision;
  11863. }
  11864. if (delta)
  11865. _this.inertialRadiusOffset += delta;
  11866. if (event.preventDefault) {
  11867. if (!noPreventDefault) {
  11868. event.preventDefault();
  11869. }
  11870. }
  11871. };
  11872. this._onKeyDown = function (evt) {
  11873. _this._isCtrlPushed = evt.ctrlKey;
  11874. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11875. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11876. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11877. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11878. var index = _this._keys.indexOf(evt.keyCode);
  11879. if (index === -1) {
  11880. _this._keys.push(evt.keyCode);
  11881. }
  11882. if (evt.preventDefault) {
  11883. if (!noPreventDefault) {
  11884. evt.preventDefault();
  11885. }
  11886. }
  11887. }
  11888. };
  11889. this._onKeyUp = function (evt) {
  11890. _this._isCtrlPushed = evt.ctrlKey;
  11891. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11892. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11893. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11894. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11895. var index = _this._keys.indexOf(evt.keyCode);
  11896. if (index >= 0) {
  11897. _this._keys.splice(index, 1);
  11898. }
  11899. if (evt.preventDefault) {
  11900. if (!noPreventDefault) {
  11901. evt.preventDefault();
  11902. }
  11903. }
  11904. }
  11905. };
  11906. this._onLostFocus = function () {
  11907. _this._keys = [];
  11908. pointers.empty();
  11909. previousPinchDistance = 0;
  11910. cacheSoloPointer = null;
  11911. };
  11912. this._onGestureStart = function (e) {
  11913. if (window.MSGesture === undefined) {
  11914. return;
  11915. }
  11916. if (!_this._MSGestureHandler) {
  11917. _this._MSGestureHandler = new MSGesture();
  11918. _this._MSGestureHandler.target = element;
  11919. }
  11920. _this._MSGestureHandler.addPointer(e.pointerId);
  11921. };
  11922. this._onGesture = function (e) {
  11923. _this.radius *= e.scale;
  11924. if (e.preventDefault) {
  11925. if (!noPreventDefault) {
  11926. e.stopPropagation();
  11927. e.preventDefault();
  11928. }
  11929. }
  11930. };
  11931. this._reset = function () {
  11932. _this._keys = [];
  11933. _this.inertialAlphaOffset = 0;
  11934. _this.inertialBetaOffset = 0;
  11935. _this.inertialRadiusOffset = 0;
  11936. pointers.empty();
  11937. previousPinchDistance = 0;
  11938. cacheSoloPointer = null;
  11939. };
  11940. }
  11941. if (!useCtrlForPanning) {
  11942. element.addEventListener("contextmenu", this._onContextMenu, false);
  11943. }
  11944. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11945. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11946. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11947. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11948. element.addEventListener("mousemove", this._onMouseMove, false);
  11949. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11950. element.addEventListener("MSGestureChange", this._onGesture, false);
  11951. element.addEventListener('mousewheel', this._wheel, false);
  11952. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11953. BABYLON.Tools.RegisterTopRootEvents([
  11954. { name: "keydown", handler: this._onKeyDown },
  11955. { name: "keyup", handler: this._onKeyUp },
  11956. { name: "blur", handler: this._onLostFocus }
  11957. ]);
  11958. };
  11959. ArcRotateCamera.prototype.detachControl = function (element) {
  11960. if (this._attachedElement !== element) {
  11961. return;
  11962. }
  11963. element.removeEventListener("contextmenu", this._onContextMenu);
  11964. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11965. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11966. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11967. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11968. element.removeEventListener("mousemove", this._onMouseMove);
  11969. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11970. element.removeEventListener("MSGestureChange", this._onGesture);
  11971. element.removeEventListener('mousewheel', this._wheel);
  11972. element.removeEventListener('DOMMouseScroll', this._wheel);
  11973. BABYLON.Tools.UnregisterTopRootEvents([
  11974. { name: "keydown", handler: this._onKeyDown },
  11975. { name: "keyup", handler: this._onKeyUp },
  11976. { name: "blur", handler: this._onLostFocus }
  11977. ]);
  11978. this._MSGestureHandler = null;
  11979. this._attachedElement = null;
  11980. if (this._reset) {
  11981. this._reset();
  11982. }
  11983. };
  11984. ArcRotateCamera.prototype._checkInputs = function () {
  11985. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11986. if (this._collisionTriggered) {
  11987. return;
  11988. }
  11989. // Keyboard
  11990. for (var index = 0; index < this._keys.length; index++) {
  11991. var keyCode = this._keys[index];
  11992. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11993. this.inertialAlphaOffset -= 0.01;
  11994. }
  11995. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11996. this.inertialBetaOffset -= 0.01;
  11997. }
  11998. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11999. this.inertialAlphaOffset += 0.01;
  12000. }
  12001. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12002. this.inertialBetaOffset += 0.01;
  12003. }
  12004. }
  12005. // Inertia
  12006. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12007. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12008. this.beta += this.inertialBetaOffset;
  12009. this.radius -= this.inertialRadiusOffset;
  12010. this.inertialAlphaOffset *= this.inertia;
  12011. this.inertialBetaOffset *= this.inertia;
  12012. this.inertialRadiusOffset *= this.inertia;
  12013. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12014. this.inertialAlphaOffset = 0;
  12015. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12016. this.inertialBetaOffset = 0;
  12017. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12018. this.inertialRadiusOffset = 0;
  12019. }
  12020. // Panning inertia
  12021. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12022. if (!this._localDirection) {
  12023. this._localDirection = BABYLON.Vector3.Zero();
  12024. this._transformedDirection = BABYLON.Vector3.Zero();
  12025. }
  12026. this.inertialPanningX *= this.inertia;
  12027. this.inertialPanningY *= this.inertia;
  12028. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12029. this.inertialPanningX = 0;
  12030. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12031. this.inertialPanningY = 0;
  12032. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12033. this._localDirection.multiplyInPlace(this.panningAxis);
  12034. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12035. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12036. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12037. if (!this.panningAxis.y) {
  12038. this._transformedDirection.y = 0;
  12039. }
  12040. this.target.addInPlace(this._transformedDirection);
  12041. }
  12042. // Limits
  12043. this._checkLimits();
  12044. _super.prototype._checkInputs.call(this);
  12045. };
  12046. ArcRotateCamera.prototype._checkLimits = function () {
  12047. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12048. if (this.allowUpsideDown && this.beta > Math.PI) {
  12049. this.beta = this.beta - (2 * Math.PI);
  12050. }
  12051. }
  12052. else {
  12053. if (this.beta < this.lowerBetaLimit) {
  12054. this.beta = this.lowerBetaLimit;
  12055. }
  12056. }
  12057. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12058. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12059. this.beta = this.beta + (2 * Math.PI);
  12060. }
  12061. }
  12062. else {
  12063. if (this.beta > this.upperBetaLimit) {
  12064. this.beta = this.upperBetaLimit;
  12065. }
  12066. }
  12067. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12068. this.alpha = this.lowerAlphaLimit;
  12069. }
  12070. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12071. this.alpha = this.upperAlphaLimit;
  12072. }
  12073. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12074. this.radius = this.lowerRadiusLimit;
  12075. }
  12076. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12077. this.radius = this.upperRadiusLimit;
  12078. }
  12079. };
  12080. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12081. var radiusv3 = this.position.subtract(this.target);
  12082. this.radius = radiusv3.length();
  12083. // Alpha
  12084. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12085. if (radiusv3.z < 0) {
  12086. this.alpha = 2 * Math.PI - this.alpha;
  12087. }
  12088. // Beta
  12089. this.beta = Math.acos(radiusv3.y / this.radius);
  12090. this._checkLimits();
  12091. };
  12092. ArcRotateCamera.prototype.setPosition = function (position) {
  12093. if (this.position.equals(position)) {
  12094. return;
  12095. }
  12096. this.position = position;
  12097. this.rebuildAnglesAndRadius();
  12098. };
  12099. ArcRotateCamera.prototype.setTarget = function (target) {
  12100. if (this.target.equals(target)) {
  12101. return;
  12102. }
  12103. this.target = target;
  12104. this.rebuildAnglesAndRadius();
  12105. };
  12106. ArcRotateCamera.prototype._getViewMatrix = function () {
  12107. // Compute
  12108. var cosa = Math.cos(this.alpha);
  12109. var sina = Math.sin(this.alpha);
  12110. var cosb = Math.cos(this.beta);
  12111. var sinb = Math.sin(this.beta);
  12112. if (sinb === 0) {
  12113. sinb = 0.0001;
  12114. }
  12115. var target = this.target;
  12116. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12117. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12118. this._collider.radius = this.collisionRadius;
  12119. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12120. this._collisionTriggered = true;
  12121. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12122. }
  12123. else {
  12124. this.position.copyFrom(this._newPosition);
  12125. var up = this.upVector;
  12126. if (this.allowUpsideDown && this.beta < 0) {
  12127. up = up.clone();
  12128. up = up.negate();
  12129. }
  12130. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12131. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12132. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12133. }
  12134. return this._viewMatrix;
  12135. };
  12136. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12137. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12138. meshes = meshes || this.getScene().meshes;
  12139. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12140. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12141. this.radius = distance * this.zoomOnFactor;
  12142. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12143. };
  12144. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12145. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12146. var meshesOrMinMaxVector;
  12147. var distance;
  12148. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12149. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12150. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12151. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12152. }
  12153. else {
  12154. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12155. distance = meshesOrMinMaxVectorAndDistance.distance;
  12156. }
  12157. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12158. if (!doNotUpdateMaxZ) {
  12159. this.maxZ = distance * 2;
  12160. }
  12161. };
  12162. /**
  12163. * @override
  12164. * Override Camera.createRigCamera
  12165. */
  12166. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12167. switch (this.cameraRigMode) {
  12168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12172. case BABYLON.Camera.RIG_MODE_VR:
  12173. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12174. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12175. }
  12176. return null;
  12177. };
  12178. /**
  12179. * @override
  12180. * Override Camera._updateRigCameras
  12181. */
  12182. ArcRotateCamera.prototype._updateRigCameras = function () {
  12183. switch (this.cameraRigMode) {
  12184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12188. case BABYLON.Camera.RIG_MODE_VR:
  12189. var camLeft = this._rigCameras[0];
  12190. var camRight = this._rigCameras[1];
  12191. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12192. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12193. camLeft.beta = camRight.beta = this.beta;
  12194. camLeft.radius = camRight.radius = this.radius;
  12195. break;
  12196. }
  12197. _super.prototype._updateRigCameras.call(this);
  12198. };
  12199. ArcRotateCamera.prototype.getTypeName = function () {
  12200. return "ArcRotateCamera";
  12201. };
  12202. __decorate([
  12203. BABYLON.serialize()
  12204. ], ArcRotateCamera.prototype, "alpha", void 0);
  12205. __decorate([
  12206. BABYLON.serialize()
  12207. ], ArcRotateCamera.prototype, "beta", void 0);
  12208. __decorate([
  12209. BABYLON.serialize()
  12210. ], ArcRotateCamera.prototype, "radius", void 0);
  12211. __decorate([
  12212. BABYLON.serializeAsVector3()
  12213. ], ArcRotateCamera.prototype, "target", void 0);
  12214. __decorate([
  12215. BABYLON.serialize()
  12216. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12217. __decorate([
  12218. BABYLON.serialize()
  12219. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12220. __decorate([
  12221. BABYLON.serialize()
  12222. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12223. __decorate([
  12224. BABYLON.serialize()
  12225. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12226. __decorate([
  12227. BABYLON.serialize()
  12228. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12229. __decorate([
  12230. BABYLON.serialize()
  12231. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12232. __decorate([
  12233. BABYLON.serialize()
  12234. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12235. __decorate([
  12236. BABYLON.serialize()
  12237. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12238. __decorate([
  12239. BABYLON.serialize()
  12240. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12241. __decorate([
  12242. BABYLON.serialize()
  12243. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12244. __decorate([
  12245. BABYLON.serialize()
  12246. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12247. __decorate([
  12248. BABYLON.serialize()
  12249. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12250. __decorate([
  12251. BABYLON.serialize()
  12252. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12253. __decorate([
  12254. BABYLON.serialize()
  12255. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12256. __decorate([
  12257. BABYLON.serialize()
  12258. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12259. __decorate([
  12260. BABYLON.serialize()
  12261. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12262. __decorate([
  12263. BABYLON.serialize()
  12264. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12265. __decorate([
  12266. BABYLON.serialize()
  12267. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12268. __decorate([
  12269. BABYLON.serialize()
  12270. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12271. __decorate([
  12272. BABYLON.serialize()
  12273. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12274. __decorate([
  12275. BABYLON.serialize()
  12276. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12277. __decorate([
  12278. BABYLON.serialize()
  12279. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12280. return ArcRotateCamera;
  12281. })(BABYLON.TargetCamera);
  12282. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12283. })(BABYLON || (BABYLON = {}));
  12284. var BABYLON;
  12285. (function (BABYLON) {
  12286. var RenderingManager = (function () {
  12287. function RenderingManager(scene) {
  12288. this._renderingGroups = new Array();
  12289. this._scene = scene;
  12290. }
  12291. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12292. if (this._scene._activeParticleSystems.length === 0) {
  12293. return;
  12294. }
  12295. // Particles
  12296. var activeCamera = this._scene.activeCamera;
  12297. var beforeParticlesDate = BABYLON.Tools.Now;
  12298. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12299. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12300. if (particleSystem.renderingGroupId !== index) {
  12301. continue;
  12302. }
  12303. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12304. continue;
  12305. }
  12306. this._clearDepthBuffer();
  12307. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12308. this._scene._activeParticles += particleSystem.render();
  12309. }
  12310. }
  12311. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12312. };
  12313. RenderingManager.prototype._renderSprites = function (index) {
  12314. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12315. return;
  12316. }
  12317. // Sprites
  12318. var activeCamera = this._scene.activeCamera;
  12319. var beforeSpritessDate = BABYLON.Tools.Now;
  12320. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12321. var spriteManager = this._scene.spriteManagers[id];
  12322. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12323. this._clearDepthBuffer();
  12324. spriteManager.render();
  12325. }
  12326. }
  12327. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12328. };
  12329. RenderingManager.prototype._clearDepthBuffer = function () {
  12330. if (this._depthBufferAlreadyCleaned) {
  12331. return;
  12332. }
  12333. this._scene.getEngine().clear(0, false, true);
  12334. this._depthBufferAlreadyCleaned = true;
  12335. };
  12336. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12337. if (this._currentRenderSprites) {
  12338. this._renderSprites(this._currentIndex);
  12339. }
  12340. if (this._currentRenderParticles) {
  12341. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12342. }
  12343. };
  12344. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12345. this._currentActiveMeshes = activeMeshes;
  12346. this._currentRenderParticles = renderParticles;
  12347. this._currentRenderSprites = renderSprites;
  12348. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12349. this._depthBufferAlreadyCleaned = index == 0;
  12350. var renderingGroup = this._renderingGroups[index];
  12351. var needToStepBack = false;
  12352. this._currentIndex = index;
  12353. if (renderingGroup) {
  12354. this._clearDepthBuffer();
  12355. if (!renderingGroup.onBeforeTransparentRendering) {
  12356. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12357. }
  12358. if (!renderingGroup.render(customRenderFunction)) {
  12359. this._renderingGroups.splice(index, 1);
  12360. needToStepBack = true;
  12361. this._renderSpritesAndParticles();
  12362. }
  12363. }
  12364. else {
  12365. this._renderSpritesAndParticles();
  12366. }
  12367. if (needToStepBack) {
  12368. index--;
  12369. }
  12370. }
  12371. };
  12372. RenderingManager.prototype.reset = function () {
  12373. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12374. if (renderingGroup) {
  12375. renderingGroup.prepare();
  12376. }
  12377. });
  12378. };
  12379. RenderingManager.prototype.dispatch = function (subMesh) {
  12380. var mesh = subMesh.getMesh();
  12381. var renderingGroupId = mesh.renderingGroupId || 0;
  12382. if (!this._renderingGroups[renderingGroupId]) {
  12383. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12384. }
  12385. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12386. };
  12387. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12388. return RenderingManager;
  12389. })();
  12390. BABYLON.RenderingManager = RenderingManager;
  12391. })(BABYLON || (BABYLON = {}));
  12392. var BABYLON;
  12393. (function (BABYLON) {
  12394. var RenderingGroup = (function () {
  12395. function RenderingGroup(index, scene) {
  12396. this.index = index;
  12397. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12398. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12399. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12400. this._scene = scene;
  12401. }
  12402. RenderingGroup.prototype.render = function (customRenderFunction) {
  12403. if (customRenderFunction) {
  12404. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12405. return true;
  12406. }
  12407. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12408. if (this.onBeforeTransparentRendering) {
  12409. this.onBeforeTransparentRendering();
  12410. }
  12411. return false;
  12412. }
  12413. var engine = this._scene.getEngine();
  12414. // Opaque
  12415. var subIndex;
  12416. var submesh;
  12417. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12418. submesh = this._opaqueSubMeshes.data[subIndex];
  12419. submesh.render(false);
  12420. }
  12421. // Alpha test
  12422. engine.setAlphaTesting(true);
  12423. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12424. submesh = this._alphaTestSubMeshes.data[subIndex];
  12425. submesh.render(false);
  12426. }
  12427. engine.setAlphaTesting(false);
  12428. if (this.onBeforeTransparentRendering) {
  12429. this.onBeforeTransparentRendering();
  12430. }
  12431. // Transparent
  12432. if (this._transparentSubMeshes.length) {
  12433. // Sorting
  12434. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12435. submesh = this._transparentSubMeshes.data[subIndex];
  12436. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12437. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12438. }
  12439. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12440. sortedArray.sort(function (a, b) {
  12441. // Alpha index first
  12442. if (a._alphaIndex > b._alphaIndex) {
  12443. return 1;
  12444. }
  12445. if (a._alphaIndex < b._alphaIndex) {
  12446. return -1;
  12447. }
  12448. // Then distance to camera
  12449. if (a._distanceToCamera < b._distanceToCamera) {
  12450. return 1;
  12451. }
  12452. if (a._distanceToCamera > b._distanceToCamera) {
  12453. return -1;
  12454. }
  12455. return 0;
  12456. });
  12457. // Rendering
  12458. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12459. submesh = sortedArray[subIndex];
  12460. submesh.render(true);
  12461. }
  12462. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12463. }
  12464. return true;
  12465. };
  12466. RenderingGroup.prototype.prepare = function () {
  12467. this._opaqueSubMeshes.reset();
  12468. this._transparentSubMeshes.reset();
  12469. this._alphaTestSubMeshes.reset();
  12470. };
  12471. RenderingGroup.prototype.dispatch = function (subMesh) {
  12472. var material = subMesh.getMaterial();
  12473. var mesh = subMesh.getMesh();
  12474. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12475. this._transparentSubMeshes.push(subMesh);
  12476. }
  12477. else if (material.needAlphaTesting()) {
  12478. this._alphaTestSubMeshes.push(subMesh);
  12479. }
  12480. else {
  12481. this._opaqueSubMeshes.push(subMesh); // Opaque
  12482. }
  12483. };
  12484. return RenderingGroup;
  12485. })();
  12486. BABYLON.RenderingGroup = RenderingGroup;
  12487. })(BABYLON || (BABYLON = {}));
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. /**
  12491. * Represents a scene to be rendered by the engine.
  12492. * @see http://doc.babylonjs.com/page.php?p=21911
  12493. */
  12494. var Scene = (function () {
  12495. /**
  12496. * @constructor
  12497. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12498. */
  12499. function Scene(engine) {
  12500. // Members
  12501. this.autoClear = true;
  12502. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12503. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12504. this.forceWireframe = false;
  12505. this.forcePointsCloud = false;
  12506. this.forceShowBoundingBoxes = false;
  12507. this.animationsEnabled = true;
  12508. this.constantlyUpdateMeshUnderPointer = false;
  12509. // Animations
  12510. this.animations = [];
  12511. 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
  12512. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12513. this._startingPointerTime = 0;
  12514. // Fog
  12515. /**
  12516. * is fog enabled on this scene.
  12517. * @type {boolean}
  12518. */
  12519. this.fogEnabled = true;
  12520. this.fogMode = Scene.FOGMODE_NONE;
  12521. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12522. this.fogDensity = 0.1;
  12523. this.fogStart = 0;
  12524. this.fogEnd = 1000.0;
  12525. // Lights
  12526. /**
  12527. * is shadow enabled on this scene.
  12528. * @type {boolean}
  12529. */
  12530. this.shadowsEnabled = true;
  12531. /**
  12532. * is light enabled on this scene.
  12533. * @type {boolean}
  12534. */
  12535. this.lightsEnabled = true;
  12536. /**
  12537. * All of the lights added to this scene.
  12538. * @see BABYLON.Light
  12539. * @type {BABYLON.Light[]}
  12540. */
  12541. this.lights = new Array();
  12542. // Cameras
  12543. /**
  12544. * All of the cameras added to this scene.
  12545. * @see BABYLON.Camera
  12546. * @type {BABYLON.Camera[]}
  12547. */
  12548. this.cameras = new Array();
  12549. this.activeCameras = new Array();
  12550. // Meshes
  12551. /**
  12552. * All of the (abstract) meshes added to this scene.
  12553. * @see BABYLON.AbstractMesh
  12554. * @type {BABYLON.AbstractMesh[]}
  12555. */
  12556. this.meshes = new Array();
  12557. // Geometries
  12558. this._geometries = new Array();
  12559. this.materials = new Array();
  12560. this.multiMaterials = new Array();
  12561. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12562. // Textures
  12563. this.texturesEnabled = true;
  12564. this.textures = new Array();
  12565. // Particles
  12566. this.particlesEnabled = true;
  12567. this.particleSystems = new Array();
  12568. // Sprites
  12569. this.spritesEnabled = true;
  12570. this.spriteManagers = new Array();
  12571. // Layers
  12572. this.layers = new Array();
  12573. // Skeletons
  12574. this.skeletonsEnabled = true;
  12575. this.skeletons = new Array();
  12576. // Lens flares
  12577. this.lensFlaresEnabled = true;
  12578. this.lensFlareSystems = new Array();
  12579. // Collisions
  12580. this.collisionsEnabled = true;
  12581. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12582. // Postprocesses
  12583. this.postProcessesEnabled = true;
  12584. // Customs render targets
  12585. this.renderTargetsEnabled = true;
  12586. this.dumpNextRenderTargets = false;
  12587. this.customRenderTargets = new Array();
  12588. // Imported meshes
  12589. this.importedMeshesFiles = new Array();
  12590. // Probes
  12591. this.probesEnabled = true;
  12592. this.reflectionProbes = new Array();
  12593. this._actionManagers = new Array();
  12594. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12595. // Procedural textures
  12596. this.proceduralTexturesEnabled = true;
  12597. this._proceduralTextures = new Array();
  12598. this.soundTracks = new Array();
  12599. this._audioEnabled = true;
  12600. this._headphone = false;
  12601. this._totalVertices = 0;
  12602. this._activeIndices = 0;
  12603. this._activeParticles = 0;
  12604. this._lastFrameDuration = 0;
  12605. this._evaluateActiveMeshesDuration = 0;
  12606. this._renderTargetsDuration = 0;
  12607. this._particlesDuration = 0;
  12608. this._renderDuration = 0;
  12609. this._spritesDuration = 0;
  12610. this._animationRatio = 0;
  12611. this._renderId = 0;
  12612. this._executeWhenReadyTimeoutId = -1;
  12613. this._toBeDisposed = new BABYLON.SmartArray(256);
  12614. this._onReadyCallbacks = new Array();
  12615. this._pendingData = []; //ANY
  12616. this._onBeforeRenderCallbacks = new Array();
  12617. this._onAfterRenderCallbacks = new Array();
  12618. this._activeMeshes = new BABYLON.SmartArray(256);
  12619. this._processedMaterials = new BABYLON.SmartArray(256);
  12620. this._renderTargets = new BABYLON.SmartArray(256);
  12621. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12622. this._activeSkeletons = new BABYLON.SmartArray(32);
  12623. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12624. this._activeBones = 0;
  12625. this._activeAnimatables = new Array();
  12626. this._transformMatrix = BABYLON.Matrix.Zero();
  12627. this._edgesRenderers = new BABYLON.SmartArray(16);
  12628. this._uniqueIdCounter = 0;
  12629. this._engine = engine;
  12630. engine.scenes.push(this);
  12631. this._renderingManager = new BABYLON.RenderingManager(this);
  12632. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12633. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12634. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12635. if (BABYLON.OutlineRenderer) {
  12636. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12637. }
  12638. this.attachControl();
  12639. this._debugLayer = new BABYLON.DebugLayer(this);
  12640. if (BABYLON.SoundTrack) {
  12641. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12642. }
  12643. //simplification queue
  12644. if (BABYLON.SimplificationQueue) {
  12645. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12646. }
  12647. //collision coordinator initialization. For now legacy per default.
  12648. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12649. }
  12650. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12651. get: function () {
  12652. return Scene._FOGMODE_NONE;
  12653. },
  12654. enumerable: true,
  12655. configurable: true
  12656. });
  12657. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12658. get: function () {
  12659. return Scene._FOGMODE_EXP;
  12660. },
  12661. enumerable: true,
  12662. configurable: true
  12663. });
  12664. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12665. get: function () {
  12666. return Scene._FOGMODE_EXP2;
  12667. },
  12668. enumerable: true,
  12669. configurable: true
  12670. });
  12671. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12672. get: function () {
  12673. return Scene._FOGMODE_LINEAR;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. Object.defineProperty(Scene.prototype, "debugLayer", {
  12679. // Properties
  12680. get: function () {
  12681. return this._debugLayer;
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12687. get: function () {
  12688. return this._workerCollisions;
  12689. },
  12690. set: function (enabled) {
  12691. enabled = (enabled && !!Worker);
  12692. this._workerCollisions = enabled;
  12693. if (this.collisionCoordinator) {
  12694. this.collisionCoordinator.destroy();
  12695. }
  12696. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12697. this.collisionCoordinator.init(this);
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12703. get: function () {
  12704. return this._selectionOctree;
  12705. },
  12706. enumerable: true,
  12707. configurable: true
  12708. });
  12709. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12710. /**
  12711. * The mesh that is currently under the pointer.
  12712. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12713. */
  12714. get: function () {
  12715. return this._pointerOverMesh;
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(Scene.prototype, "pointerX", {
  12721. /**
  12722. * Current on-screen X position of the pointer
  12723. * @return {number} X position of the pointer
  12724. */
  12725. get: function () {
  12726. return this._pointerX;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Scene.prototype, "pointerY", {
  12732. /**
  12733. * Current on-screen Y position of the pointer
  12734. * @return {number} Y position of the pointer
  12735. */
  12736. get: function () {
  12737. return this._pointerY;
  12738. },
  12739. enumerable: true,
  12740. configurable: true
  12741. });
  12742. Scene.prototype.getCachedMaterial = function () {
  12743. return this._cachedMaterial;
  12744. };
  12745. Scene.prototype.getBoundingBoxRenderer = function () {
  12746. return this._boundingBoxRenderer;
  12747. };
  12748. Scene.prototype.getOutlineRenderer = function () {
  12749. return this._outlineRenderer;
  12750. };
  12751. Scene.prototype.getEngine = function () {
  12752. return this._engine;
  12753. };
  12754. Scene.prototype.getTotalVertices = function () {
  12755. return this._totalVertices;
  12756. };
  12757. Scene.prototype.getActiveIndices = function () {
  12758. return this._activeIndices;
  12759. };
  12760. Scene.prototype.getActiveParticles = function () {
  12761. return this._activeParticles;
  12762. };
  12763. Scene.prototype.getActiveBones = function () {
  12764. return this._activeBones;
  12765. };
  12766. // Stats
  12767. Scene.prototype.getLastFrameDuration = function () {
  12768. return this._lastFrameDuration;
  12769. };
  12770. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12771. return this._evaluateActiveMeshesDuration;
  12772. };
  12773. Scene.prototype.getActiveMeshes = function () {
  12774. return this._activeMeshes;
  12775. };
  12776. Scene.prototype.getRenderTargetsDuration = function () {
  12777. return this._renderTargetsDuration;
  12778. };
  12779. Scene.prototype.getRenderDuration = function () {
  12780. return this._renderDuration;
  12781. };
  12782. Scene.prototype.getParticlesDuration = function () {
  12783. return this._particlesDuration;
  12784. };
  12785. Scene.prototype.getSpritesDuration = function () {
  12786. return this._spritesDuration;
  12787. };
  12788. Scene.prototype.getAnimationRatio = function () {
  12789. return this._animationRatio;
  12790. };
  12791. Scene.prototype.getRenderId = function () {
  12792. return this._renderId;
  12793. };
  12794. Scene.prototype.incrementRenderId = function () {
  12795. this._renderId++;
  12796. };
  12797. Scene.prototype._updatePointerPosition = function (evt) {
  12798. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12799. this._pointerX = evt.clientX - canvasRect.left;
  12800. this._pointerY = evt.clientY - canvasRect.top;
  12801. this._unTranslatedPointerX = this._pointerX;
  12802. this._unTranslatedPointerY = this._pointerY;
  12803. if (this.cameraToUseForPointers) {
  12804. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12805. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12806. }
  12807. };
  12808. // Pointers handling
  12809. Scene.prototype.attachControl = function () {
  12810. var _this = this;
  12811. var spritePredicate = function (sprite) {
  12812. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12813. };
  12814. this._onPointerMove = function (evt) {
  12815. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12816. return;
  12817. }
  12818. var canvas = _this._engine.getRenderingCanvas();
  12819. _this._updatePointerPosition(evt);
  12820. // Meshes
  12821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  12822. if (pickResult.hit && pickResult.pickedMesh) {
  12823. _this.setPointerOverSprite(null);
  12824. _this.setPointerOverMesh(pickResult.pickedMesh);
  12825. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12826. canvas.style.cursor = "pointer";
  12827. }
  12828. else {
  12829. canvas.style.cursor = "";
  12830. }
  12831. }
  12832. else {
  12833. _this.setPointerOverMesh(null);
  12834. // Sprites
  12835. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12836. if (pickResult.hit && pickResult.pickedSprite) {
  12837. canvas.style.cursor = "pointer";
  12838. _this.setPointerOverSprite(pickResult.pickedSprite);
  12839. }
  12840. else {
  12841. _this.setPointerOverSprite(null);
  12842. // Restore pointer
  12843. canvas.style.cursor = "";
  12844. }
  12845. }
  12846. if (_this.onPointerMove) {
  12847. _this.onPointerMove(evt, pickResult);
  12848. }
  12849. };
  12850. this._onPointerDown = function (evt) {
  12851. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12852. return;
  12853. }
  12854. _this._updatePointerPosition(evt);
  12855. _this._startingPointerPosition.x = _this._pointerX;
  12856. _this._startingPointerPosition.y = _this._pointerY;
  12857. _this._startingPointerTime = new Date().getTime();
  12858. var predicate = null;
  12859. // Meshes
  12860. _this._pickedDownMesh = null;
  12861. if (!_this.onPointerDown && !_this.onPointerPick) {
  12862. predicate = function (mesh) {
  12863. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12864. };
  12865. }
  12866. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12867. if (pickResult.hit && pickResult.pickedMesh) {
  12868. if (pickResult.pickedMesh.actionManager) {
  12869. _this._pickedDownMesh = pickResult.pickedMesh;
  12870. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12871. switch (evt.button) {
  12872. case 0:
  12873. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12874. break;
  12875. case 1:
  12876. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12877. break;
  12878. case 2:
  12879. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12880. break;
  12881. }
  12882. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12883. }
  12884. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12885. var that = _this;
  12886. window.setTimeout(function () {
  12887. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12888. if (pickResult.hit && pickResult.pickedMesh) {
  12889. if (pickResult.pickedMesh.actionManager) {
  12890. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12891. that._startingPointerTime = 0;
  12892. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12893. }
  12894. }
  12895. }
  12896. }, BABYLON.ActionManager.LongPressDelay);
  12897. }
  12898. }
  12899. }
  12900. if (_this.onPointerDown) {
  12901. _this.onPointerDown(evt, pickResult);
  12902. }
  12903. // Sprites
  12904. _this._pickedDownSprite = null;
  12905. if (_this.spriteManagers.length > 0) {
  12906. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12907. if (pickResult.hit && pickResult.pickedSprite) {
  12908. if (pickResult.pickedSprite.actionManager) {
  12909. _this._pickedDownSprite = pickResult.pickedSprite;
  12910. switch (evt.button) {
  12911. case 0:
  12912. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12913. break;
  12914. case 1:
  12915. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12916. break;
  12917. case 2:
  12918. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12919. break;
  12920. }
  12921. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12922. }
  12923. }
  12924. }
  12925. };
  12926. this._onPointerUp = function (evt) {
  12927. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12928. return;
  12929. }
  12930. var predicate = null;
  12931. _this._updatePointerPosition(evt);
  12932. if (!_this.onPointerUp && !_this.onPointerPick) {
  12933. predicate = function (mesh) {
  12934. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12935. };
  12936. }
  12937. // Meshes
  12938. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12939. if (pickResult.hit && pickResult.pickedMesh) {
  12940. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12941. _this.onPointerPick(evt, pickResult);
  12942. }
  12943. if (pickResult.pickedMesh.actionManager) {
  12944. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12945. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12946. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12947. }
  12948. }
  12949. }
  12950. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12951. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12952. }
  12953. if (_this.onPointerUp) {
  12954. _this.onPointerUp(evt, pickResult);
  12955. }
  12956. _this._startingPointerTime = 0;
  12957. // Sprites
  12958. if (_this.spriteManagers.length > 0) {
  12959. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12960. if (pickResult.hit && pickResult.pickedSprite) {
  12961. if (pickResult.pickedSprite.actionManager) {
  12962. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12963. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12964. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12965. }
  12966. }
  12967. }
  12968. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12969. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12970. }
  12971. }
  12972. };
  12973. this._onKeyDown = function (evt) {
  12974. if (_this.actionManager) {
  12975. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12976. }
  12977. };
  12978. this._onKeyUp = function (evt) {
  12979. if (_this.actionManager) {
  12980. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12981. }
  12982. };
  12983. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12984. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12985. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12986. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12987. // Wheel
  12988. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12989. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12990. BABYLON.Tools.RegisterTopRootEvents([
  12991. { name: "keydown", handler: this._onKeyDown },
  12992. { name: "keyup", handler: this._onKeyUp }
  12993. ]);
  12994. };
  12995. Scene.prototype.detachControl = function () {
  12996. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12997. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12998. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12999. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13000. // Wheel
  13001. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13002. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13003. BABYLON.Tools.UnregisterTopRootEvents([
  13004. { name: "keydown", handler: this._onKeyDown },
  13005. { name: "keyup", handler: this._onKeyUp }
  13006. ]);
  13007. };
  13008. // Ready
  13009. Scene.prototype.isReady = function () {
  13010. if (this._pendingData.length > 0) {
  13011. return false;
  13012. }
  13013. var index;
  13014. for (index = 0; index < this._geometries.length; index++) {
  13015. var geometry = this._geometries[index];
  13016. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13017. return false;
  13018. }
  13019. }
  13020. for (index = 0; index < this.meshes.length; index++) {
  13021. var mesh = this.meshes[index];
  13022. if (!mesh.isReady()) {
  13023. return false;
  13024. }
  13025. var mat = mesh.material;
  13026. if (mat) {
  13027. if (!mat.isReady(mesh)) {
  13028. return false;
  13029. }
  13030. }
  13031. }
  13032. return true;
  13033. };
  13034. Scene.prototype.resetCachedMaterial = function () {
  13035. this._cachedMaterial = null;
  13036. };
  13037. Scene.prototype.registerBeforeRender = function (func) {
  13038. this._onBeforeRenderCallbacks.push(func);
  13039. };
  13040. Scene.prototype.unregisterBeforeRender = function (func) {
  13041. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13042. if (index > -1) {
  13043. this._onBeforeRenderCallbacks.splice(index, 1);
  13044. }
  13045. };
  13046. Scene.prototype.registerAfterRender = function (func) {
  13047. this._onAfterRenderCallbacks.push(func);
  13048. };
  13049. Scene.prototype.unregisterAfterRender = function (func) {
  13050. var index = this._onAfterRenderCallbacks.indexOf(func);
  13051. if (index > -1) {
  13052. this._onAfterRenderCallbacks.splice(index, 1);
  13053. }
  13054. };
  13055. Scene.prototype._addPendingData = function (data) {
  13056. this._pendingData.push(data);
  13057. };
  13058. Scene.prototype._removePendingData = function (data) {
  13059. var index = this._pendingData.indexOf(data);
  13060. if (index !== -1) {
  13061. this._pendingData.splice(index, 1);
  13062. }
  13063. };
  13064. Scene.prototype.getWaitingItemsCount = function () {
  13065. return this._pendingData.length;
  13066. };
  13067. /**
  13068. * Registers a function to be executed when the scene is ready.
  13069. * @param {Function} func - the function to be executed.
  13070. */
  13071. Scene.prototype.executeWhenReady = function (func) {
  13072. var _this = this;
  13073. this._onReadyCallbacks.push(func);
  13074. if (this._executeWhenReadyTimeoutId !== -1) {
  13075. return;
  13076. }
  13077. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13078. _this._checkIsReady();
  13079. }, 150);
  13080. };
  13081. Scene.prototype._checkIsReady = function () {
  13082. var _this = this;
  13083. if (this.isReady()) {
  13084. this._onReadyCallbacks.forEach(function (func) {
  13085. func();
  13086. });
  13087. this._onReadyCallbacks = [];
  13088. this._executeWhenReadyTimeoutId = -1;
  13089. return;
  13090. }
  13091. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13092. _this._checkIsReady();
  13093. }, 150);
  13094. };
  13095. // Animations
  13096. /**
  13097. * Will start the animation sequence of a given target
  13098. * @param target - the target
  13099. * @param {number} from - from which frame should animation start
  13100. * @param {number} to - till which frame should animation run.
  13101. * @param {boolean} [loop] - should the animation loop
  13102. * @param {number} [speedRatio] - the speed in which to run the animation
  13103. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13104. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13105. * @return {BABYLON.Animatable} the animatable object created for this animation
  13106. * @see BABYLON.Animatable
  13107. * @see http://doc.babylonjs.com/page.php?p=22081
  13108. */
  13109. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13110. if (speedRatio === void 0) { speedRatio = 1.0; }
  13111. this.stopAnimation(target);
  13112. if (!animatable) {
  13113. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13114. }
  13115. // Local animations
  13116. if (target.animations) {
  13117. animatable.appendAnimations(target, target.animations);
  13118. }
  13119. // Children animations
  13120. if (target.getAnimatables) {
  13121. var animatables = target.getAnimatables();
  13122. for (var index = 0; index < animatables.length; index++) {
  13123. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13124. }
  13125. }
  13126. return animatable;
  13127. };
  13128. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13129. if (speedRatio === undefined) {
  13130. speedRatio = 1.0;
  13131. }
  13132. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13133. return animatable;
  13134. };
  13135. Scene.prototype.getAnimatableByTarget = function (target) {
  13136. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13137. if (this._activeAnimatables[index].target === target) {
  13138. return this._activeAnimatables[index];
  13139. }
  13140. }
  13141. return null;
  13142. };
  13143. Object.defineProperty(Scene.prototype, "Animatables", {
  13144. get: function () {
  13145. return this._activeAnimatables;
  13146. },
  13147. enumerable: true,
  13148. configurable: true
  13149. });
  13150. /**
  13151. * Will stop the animation of the given target
  13152. * @param target - the target
  13153. * @see beginAnimation
  13154. */
  13155. Scene.prototype.stopAnimation = function (target) {
  13156. var animatable = this.getAnimatableByTarget(target);
  13157. if (animatable) {
  13158. animatable.stop();
  13159. }
  13160. };
  13161. Scene.prototype._animate = function () {
  13162. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13163. return;
  13164. }
  13165. if (!this._animationStartDate) {
  13166. if (this._pendingData.length > 0) {
  13167. return;
  13168. }
  13169. this._animationStartDate = BABYLON.Tools.Now;
  13170. }
  13171. // Getting time
  13172. var now = BABYLON.Tools.Now;
  13173. var delay = now - this._animationStartDate;
  13174. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13175. this._activeAnimatables[index]._animate(delay);
  13176. }
  13177. };
  13178. // Matrix
  13179. Scene.prototype.getViewMatrix = function () {
  13180. return this._viewMatrix;
  13181. };
  13182. Scene.prototype.getProjectionMatrix = function () {
  13183. return this._projectionMatrix;
  13184. };
  13185. Scene.prototype.getTransformMatrix = function () {
  13186. return this._transformMatrix;
  13187. };
  13188. Scene.prototype.setTransformMatrix = function (view, projection) {
  13189. this._viewMatrix = view;
  13190. this._projectionMatrix = projection;
  13191. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13192. };
  13193. // Methods
  13194. Scene.prototype.addMesh = function (newMesh) {
  13195. newMesh.uniqueId = this._uniqueIdCounter++;
  13196. var position = this.meshes.push(newMesh);
  13197. //notify the collision coordinator
  13198. this.collisionCoordinator.onMeshAdded(newMesh);
  13199. if (this.onNewMeshAdded) {
  13200. this.onNewMeshAdded(newMesh, position, this);
  13201. }
  13202. };
  13203. Scene.prototype.removeMesh = function (toRemove) {
  13204. var index = this.meshes.indexOf(toRemove);
  13205. if (index !== -1) {
  13206. // Remove from the scene if mesh found
  13207. this.meshes.splice(index, 1);
  13208. }
  13209. //notify the collision coordinator
  13210. this.collisionCoordinator.onMeshRemoved(toRemove);
  13211. if (this.onMeshRemoved) {
  13212. this.onMeshRemoved(toRemove);
  13213. }
  13214. return index;
  13215. };
  13216. Scene.prototype.removeSkeleton = function (toRemove) {
  13217. var index = this.skeletons.indexOf(toRemove);
  13218. if (index !== -1) {
  13219. // Remove from the scene if mesh found
  13220. this.skeletons.splice(index, 1);
  13221. }
  13222. return index;
  13223. };
  13224. Scene.prototype.removeLight = function (toRemove) {
  13225. var index = this.lights.indexOf(toRemove);
  13226. if (index !== -1) {
  13227. // Remove from the scene if mesh found
  13228. this.lights.splice(index, 1);
  13229. }
  13230. if (this.onLightRemoved) {
  13231. this.onLightRemoved(toRemove);
  13232. }
  13233. return index;
  13234. };
  13235. Scene.prototype.removeCamera = function (toRemove) {
  13236. var index = this.cameras.indexOf(toRemove);
  13237. if (index !== -1) {
  13238. // Remove from the scene if mesh found
  13239. this.cameras.splice(index, 1);
  13240. }
  13241. // Remove from activeCameras
  13242. var index2 = this.activeCameras.indexOf(toRemove);
  13243. if (index2 !== -1) {
  13244. // Remove from the scene if mesh found
  13245. this.activeCameras.splice(index2, 1);
  13246. }
  13247. // Reset the activeCamera
  13248. if (this.activeCamera === toRemove) {
  13249. if (this.cameras.length > 0) {
  13250. this.activeCamera = this.cameras[0];
  13251. }
  13252. else {
  13253. this.activeCamera = null;
  13254. }
  13255. }
  13256. if (this.onCameraRemoved) {
  13257. this.onCameraRemoved(toRemove);
  13258. }
  13259. return index;
  13260. };
  13261. Scene.prototype.addLight = function (newLight) {
  13262. newLight.uniqueId = this._uniqueIdCounter++;
  13263. var position = this.lights.push(newLight);
  13264. if (this.onNewLightAdded) {
  13265. this.onNewLightAdded(newLight, position, this);
  13266. }
  13267. };
  13268. Scene.prototype.addCamera = function (newCamera) {
  13269. newCamera.uniqueId = this._uniqueIdCounter++;
  13270. var position = this.cameras.push(newCamera);
  13271. if (this.onNewCameraAdded) {
  13272. this.onNewCameraAdded(newCamera, position, this);
  13273. }
  13274. };
  13275. /**
  13276. * Switch active camera
  13277. * @param {Camera} newCamera - new active camera
  13278. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13279. */
  13280. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13281. if (attachControl === void 0) { attachControl = true; }
  13282. var canvas = this._engine.getRenderingCanvas();
  13283. this.activeCamera.detachControl(canvas);
  13284. this.activeCamera = newCamera;
  13285. if (attachControl) {
  13286. newCamera.attachControl(canvas);
  13287. }
  13288. };
  13289. /**
  13290. * sets the active camera of the scene using its ID
  13291. * @param {string} id - the camera's ID
  13292. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13293. * @see activeCamera
  13294. */
  13295. Scene.prototype.setActiveCameraByID = function (id) {
  13296. var camera = this.getCameraByID(id);
  13297. if (camera) {
  13298. this.activeCamera = camera;
  13299. return camera;
  13300. }
  13301. return null;
  13302. };
  13303. /**
  13304. * sets the active camera of the scene using its name
  13305. * @param {string} name - the camera's name
  13306. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13307. * @see activeCamera
  13308. */
  13309. Scene.prototype.setActiveCameraByName = function (name) {
  13310. var camera = this.getCameraByName(name);
  13311. if (camera) {
  13312. this.activeCamera = camera;
  13313. return camera;
  13314. }
  13315. return null;
  13316. };
  13317. /**
  13318. * get a material using its id
  13319. * @param {string} the material's ID
  13320. * @return {BABYLON.Material|null} the material or null if none found.
  13321. */
  13322. Scene.prototype.getMaterialByID = function (id) {
  13323. for (var index = 0; index < this.materials.length; index++) {
  13324. if (this.materials[index].id === id) {
  13325. return this.materials[index];
  13326. }
  13327. }
  13328. return null;
  13329. };
  13330. /**
  13331. * get a material using its name
  13332. * @param {string} the material's name
  13333. * @return {BABYLON.Material|null} the material or null if none found.
  13334. */
  13335. Scene.prototype.getMaterialByName = function (name) {
  13336. for (var index = 0; index < this.materials.length; index++) {
  13337. if (this.materials[index].name === name) {
  13338. return this.materials[index];
  13339. }
  13340. }
  13341. return null;
  13342. };
  13343. Scene.prototype.getLensFlareSystemByName = function (name) {
  13344. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13345. if (this.lensFlareSystems[index].name === name) {
  13346. return this.lensFlareSystems[index];
  13347. }
  13348. }
  13349. return null;
  13350. };
  13351. Scene.prototype.getCameraByID = function (id) {
  13352. for (var index = 0; index < this.cameras.length; index++) {
  13353. if (this.cameras[index].id === id) {
  13354. return this.cameras[index];
  13355. }
  13356. }
  13357. return null;
  13358. };
  13359. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13360. for (var index = 0; index < this.cameras.length; index++) {
  13361. if (this.cameras[index].uniqueId === uniqueId) {
  13362. return this.cameras[index];
  13363. }
  13364. }
  13365. return null;
  13366. };
  13367. /**
  13368. * get a camera using its name
  13369. * @param {string} the camera's name
  13370. * @return {BABYLON.Camera|null} the camera or null if none found.
  13371. */
  13372. Scene.prototype.getCameraByName = function (name) {
  13373. for (var index = 0; index < this.cameras.length; index++) {
  13374. if (this.cameras[index].name === name) {
  13375. return this.cameras[index];
  13376. }
  13377. }
  13378. return null;
  13379. };
  13380. /**
  13381. * get a bone using its id
  13382. * @param {string} the bone's id
  13383. * @return {BABYLON.Bone|null} the bone or null if not found
  13384. */
  13385. Scene.prototype.getBoneByID = function (id) {
  13386. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13387. var skeleton = this.skeletons[skeletonIndex];
  13388. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13389. if (skeleton.bones[boneIndex].id === id) {
  13390. return skeleton.bones[boneIndex];
  13391. }
  13392. }
  13393. }
  13394. return null;
  13395. };
  13396. /**
  13397. * get a bone using its id
  13398. * @param {string} the bone's name
  13399. * @return {BABYLON.Bone|null} the bone or null if not found
  13400. */
  13401. Scene.prototype.getBoneByName = function (name) {
  13402. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13403. var skeleton = this.skeletons[skeletonIndex];
  13404. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13405. if (skeleton.bones[boneIndex].name === name) {
  13406. return skeleton.bones[boneIndex];
  13407. }
  13408. }
  13409. }
  13410. return null;
  13411. };
  13412. /**
  13413. * get a light node using its name
  13414. * @param {string} the light's name
  13415. * @return {BABYLON.Light|null} the light or null if none found.
  13416. */
  13417. Scene.prototype.getLightByName = function (name) {
  13418. for (var index = 0; index < this.lights.length; index++) {
  13419. if (this.lights[index].name === name) {
  13420. return this.lights[index];
  13421. }
  13422. }
  13423. return null;
  13424. };
  13425. /**
  13426. * get a light node using its ID
  13427. * @param {string} the light's id
  13428. * @return {BABYLON.Light|null} the light or null if none found.
  13429. */
  13430. Scene.prototype.getLightByID = function (id) {
  13431. for (var index = 0; index < this.lights.length; index++) {
  13432. if (this.lights[index].id === id) {
  13433. return this.lights[index];
  13434. }
  13435. }
  13436. return null;
  13437. };
  13438. /**
  13439. * get a light node using its scene-generated unique ID
  13440. * @param {number} the light's unique id
  13441. * @return {BABYLON.Light|null} the light or null if none found.
  13442. */
  13443. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13444. for (var index = 0; index < this.lights.length; index++) {
  13445. if (this.lights[index].uniqueId === uniqueId) {
  13446. return this.lights[index];
  13447. }
  13448. }
  13449. return null;
  13450. };
  13451. /**
  13452. * get a particle system by id
  13453. * @param id {number} the particle system id
  13454. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13455. */
  13456. Scene.prototype.getParticleSystemByID = function (id) {
  13457. for (var index = 0; index < this.particleSystems.length; index++) {
  13458. if (this.particleSystems[index].id === id) {
  13459. return this.particleSystems[index];
  13460. }
  13461. }
  13462. return null;
  13463. };
  13464. /**
  13465. * get a geometry using its ID
  13466. * @param {string} the geometry's id
  13467. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13468. */
  13469. Scene.prototype.getGeometryByID = function (id) {
  13470. for (var index = 0; index < this._geometries.length; index++) {
  13471. if (this._geometries[index].id === id) {
  13472. return this._geometries[index];
  13473. }
  13474. }
  13475. return null;
  13476. };
  13477. /**
  13478. * add a new geometry to this scene.
  13479. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13480. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13481. * @return {boolean} was the geometry added or not
  13482. */
  13483. Scene.prototype.pushGeometry = function (geometry, force) {
  13484. if (!force && this.getGeometryByID(geometry.id)) {
  13485. return false;
  13486. }
  13487. this._geometries.push(geometry);
  13488. //notify the collision coordinator
  13489. this.collisionCoordinator.onGeometryAdded(geometry);
  13490. if (this.onGeometryAdded) {
  13491. this.onGeometryAdded(geometry);
  13492. }
  13493. return true;
  13494. };
  13495. /**
  13496. * Removes an existing geometry
  13497. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13498. * @return {boolean} was the geometry removed or not
  13499. */
  13500. Scene.prototype.removeGeometry = function (geometry) {
  13501. var index = this._geometries.indexOf(geometry);
  13502. if (index > -1) {
  13503. this._geometries.splice(index, 1);
  13504. //notify the collision coordinator
  13505. this.collisionCoordinator.onGeometryDeleted(geometry);
  13506. if (this.onGeometryRemoved) {
  13507. this.onGeometryRemoved(geometry);
  13508. }
  13509. return true;
  13510. }
  13511. return false;
  13512. };
  13513. Scene.prototype.getGeometries = function () {
  13514. return this._geometries;
  13515. };
  13516. /**
  13517. * Get the first added mesh found of a given ID
  13518. * @param {string} id - the id to search for
  13519. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13520. */
  13521. Scene.prototype.getMeshByID = function (id) {
  13522. for (var index = 0; index < this.meshes.length; index++) {
  13523. if (this.meshes[index].id === id) {
  13524. return this.meshes[index];
  13525. }
  13526. }
  13527. return null;
  13528. };
  13529. /**
  13530. * Get a mesh with its auto-generated unique id
  13531. * @param {number} uniqueId - the unique id to search for
  13532. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13533. */
  13534. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13535. for (var index = 0; index < this.meshes.length; index++) {
  13536. if (this.meshes[index].uniqueId === uniqueId) {
  13537. return this.meshes[index];
  13538. }
  13539. }
  13540. return null;
  13541. };
  13542. /**
  13543. * Get a the last added mesh found of a given ID
  13544. * @param {string} id - the id to search for
  13545. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13546. */
  13547. Scene.prototype.getLastMeshByID = function (id) {
  13548. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13549. if (this.meshes[index].id === id) {
  13550. return this.meshes[index];
  13551. }
  13552. }
  13553. return null;
  13554. };
  13555. /**
  13556. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13557. * @param {string} id - the id to search for
  13558. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13559. */
  13560. Scene.prototype.getLastEntryByID = function (id) {
  13561. var index;
  13562. for (index = this.meshes.length - 1; index >= 0; index--) {
  13563. if (this.meshes[index].id === id) {
  13564. return this.meshes[index];
  13565. }
  13566. }
  13567. for (index = this.cameras.length - 1; index >= 0; index--) {
  13568. if (this.cameras[index].id === id) {
  13569. return this.cameras[index];
  13570. }
  13571. }
  13572. for (index = this.lights.length - 1; index >= 0; index--) {
  13573. if (this.lights[index].id === id) {
  13574. return this.lights[index];
  13575. }
  13576. }
  13577. return null;
  13578. };
  13579. Scene.prototype.getNodeByID = function (id) {
  13580. var mesh = this.getMeshByID(id);
  13581. if (mesh) {
  13582. return mesh;
  13583. }
  13584. var light = this.getLightByID(id);
  13585. if (light) {
  13586. return light;
  13587. }
  13588. var camera = this.getCameraByID(id);
  13589. if (camera) {
  13590. return camera;
  13591. }
  13592. var bone = this.getBoneByID(id);
  13593. return bone;
  13594. };
  13595. Scene.prototype.getNodeByName = function (name) {
  13596. var mesh = this.getMeshByName(name);
  13597. if (mesh) {
  13598. return mesh;
  13599. }
  13600. var light = this.getLightByName(name);
  13601. if (light) {
  13602. return light;
  13603. }
  13604. var camera = this.getCameraByName(name);
  13605. if (camera) {
  13606. return camera;
  13607. }
  13608. var bone = this.getBoneByName(name);
  13609. return bone;
  13610. };
  13611. Scene.prototype.getMeshByName = function (name) {
  13612. for (var index = 0; index < this.meshes.length; index++) {
  13613. if (this.meshes[index].name === name) {
  13614. return this.meshes[index];
  13615. }
  13616. }
  13617. return null;
  13618. };
  13619. Scene.prototype.getSoundByName = function (name) {
  13620. var index;
  13621. if (BABYLON.AudioEngine) {
  13622. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13623. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13624. return this.mainSoundTrack.soundCollection[index];
  13625. }
  13626. }
  13627. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13628. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13629. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13630. return this.soundTracks[sdIndex].soundCollection[index];
  13631. }
  13632. }
  13633. }
  13634. }
  13635. return null;
  13636. };
  13637. Scene.prototype.getLastSkeletonByID = function (id) {
  13638. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13639. if (this.skeletons[index].id === id) {
  13640. return this.skeletons[index];
  13641. }
  13642. }
  13643. return null;
  13644. };
  13645. Scene.prototype.getSkeletonById = function (id) {
  13646. for (var index = 0; index < this.skeletons.length; index++) {
  13647. if (this.skeletons[index].id === id) {
  13648. return this.skeletons[index];
  13649. }
  13650. }
  13651. return null;
  13652. };
  13653. Scene.prototype.getSkeletonByName = function (name) {
  13654. for (var index = 0; index < this.skeletons.length; index++) {
  13655. if (this.skeletons[index].name === name) {
  13656. return this.skeletons[index];
  13657. }
  13658. }
  13659. return null;
  13660. };
  13661. Scene.prototype.isActiveMesh = function (mesh) {
  13662. return (this._activeMeshes.indexOf(mesh) !== -1);
  13663. };
  13664. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13665. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13666. var material = subMesh.getMaterial();
  13667. if (mesh.showSubMeshesBoundingBox) {
  13668. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13669. }
  13670. if (material) {
  13671. // Render targets
  13672. if (material.getRenderTargetTextures) {
  13673. if (this._processedMaterials.indexOf(material) === -1) {
  13674. this._processedMaterials.push(material);
  13675. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13676. }
  13677. }
  13678. // Dispatch
  13679. this._activeIndices += subMesh.indexCount;
  13680. this._renderingManager.dispatch(subMesh);
  13681. }
  13682. }
  13683. };
  13684. Scene.prototype._evaluateActiveMeshes = function () {
  13685. this.activeCamera._activeMeshes.reset();
  13686. this._activeMeshes.reset();
  13687. this._renderingManager.reset();
  13688. this._processedMaterials.reset();
  13689. this._activeParticleSystems.reset();
  13690. this._activeSkeletons.reset();
  13691. this._softwareSkinnedMeshes.reset();
  13692. this._boundingBoxRenderer.reset();
  13693. this._edgesRenderers.reset();
  13694. if (!this._frustumPlanes) {
  13695. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13696. }
  13697. else {
  13698. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13699. }
  13700. // Meshes
  13701. var meshes;
  13702. var len;
  13703. if (this._selectionOctree) {
  13704. var selection = this._selectionOctree.select(this._frustumPlanes);
  13705. meshes = selection.data;
  13706. len = selection.length;
  13707. }
  13708. else {
  13709. len = this.meshes.length;
  13710. meshes = this.meshes;
  13711. }
  13712. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13713. var mesh = meshes[meshIndex];
  13714. if (mesh.isBlocked) {
  13715. continue;
  13716. }
  13717. this._totalVertices += mesh.getTotalVertices();
  13718. if (!mesh.isReady() || !mesh.isEnabled()) {
  13719. continue;
  13720. }
  13721. mesh.computeWorldMatrix();
  13722. // Intersections
  13723. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13724. this._meshesForIntersections.pushNoDuplicate(mesh);
  13725. }
  13726. // Switch to current LOD
  13727. var meshLOD = mesh.getLOD(this.activeCamera);
  13728. if (!meshLOD) {
  13729. continue;
  13730. }
  13731. mesh._preActivate();
  13732. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13733. this._activeMeshes.push(mesh);
  13734. this.activeCamera._activeMeshes.push(mesh);
  13735. mesh._activate(this._renderId);
  13736. this._activeMesh(meshLOD);
  13737. }
  13738. }
  13739. // Particle systems
  13740. var beforeParticlesDate = BABYLON.Tools.Now;
  13741. if (this.particlesEnabled) {
  13742. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13743. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13744. var particleSystem = this.particleSystems[particleIndex];
  13745. if (!particleSystem.isStarted()) {
  13746. continue;
  13747. }
  13748. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13749. this._activeParticleSystems.push(particleSystem);
  13750. particleSystem.animate();
  13751. }
  13752. }
  13753. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13754. }
  13755. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13756. };
  13757. Scene.prototype._activeMesh = function (mesh) {
  13758. if (mesh.skeleton && this.skeletonsEnabled) {
  13759. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13760. if (!mesh.computeBonesUsingShaders) {
  13761. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13762. }
  13763. }
  13764. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13765. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13766. }
  13767. if (mesh._edgesRenderer) {
  13768. this._edgesRenderers.push(mesh._edgesRenderer);
  13769. }
  13770. if (mesh && mesh.subMeshes) {
  13771. // Submeshes Octrees
  13772. var len;
  13773. var subMeshes;
  13774. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13775. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13776. len = intersections.length;
  13777. subMeshes = intersections.data;
  13778. }
  13779. else {
  13780. subMeshes = mesh.subMeshes;
  13781. len = subMeshes.length;
  13782. }
  13783. for (var subIndex = 0; subIndex < len; subIndex++) {
  13784. var subMesh = subMeshes[subIndex];
  13785. this._evaluateSubMesh(subMesh, mesh);
  13786. }
  13787. }
  13788. };
  13789. Scene.prototype.updateTransformMatrix = function (force) {
  13790. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13791. };
  13792. Scene.prototype._renderForCamera = function (camera) {
  13793. var engine = this._engine;
  13794. this.activeCamera = camera;
  13795. if (!this.activeCamera)
  13796. throw new Error("Active camera not set");
  13797. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13798. // Viewport
  13799. engine.setViewport(this.activeCamera.viewport);
  13800. // Camera
  13801. this.resetCachedMaterial();
  13802. this._renderId++;
  13803. this.updateTransformMatrix();
  13804. if (this.beforeCameraRender) {
  13805. this.beforeCameraRender(this.activeCamera);
  13806. }
  13807. // Meshes
  13808. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13809. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13810. this._evaluateActiveMeshes();
  13811. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13812. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13813. // Skeletons
  13814. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13815. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13816. skeleton.prepare();
  13817. }
  13818. // Software skinning
  13819. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13820. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13821. mesh.applySkeleton(mesh.skeleton);
  13822. }
  13823. // Render targets
  13824. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13825. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13826. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13827. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13828. var renderTarget = this._renderTargets.data[renderIndex];
  13829. if (renderTarget._shouldRender()) {
  13830. this._renderId++;
  13831. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13832. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13833. }
  13834. }
  13835. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13836. this._renderId++;
  13837. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13838. }
  13839. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13840. // Prepare Frame
  13841. this.postProcessManager._prepareFrame();
  13842. var beforeRenderDate = BABYLON.Tools.Now;
  13843. // Backgrounds
  13844. var layerIndex;
  13845. var layer;
  13846. if (this.layers.length) {
  13847. engine.setDepthBuffer(false);
  13848. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13849. layer = this.layers[layerIndex];
  13850. if (layer.isBackground) {
  13851. layer.render();
  13852. }
  13853. }
  13854. engine.setDepthBuffer(true);
  13855. }
  13856. // Render
  13857. BABYLON.Tools.StartPerformanceCounter("Main render");
  13858. this._renderingManager.render(null, null, true, true);
  13859. BABYLON.Tools.EndPerformanceCounter("Main render");
  13860. // Bounding boxes
  13861. this._boundingBoxRenderer.render();
  13862. // Edges
  13863. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13864. this._edgesRenderers.data[edgesRendererIndex].render();
  13865. }
  13866. // Lens flares
  13867. if (this.lensFlaresEnabled) {
  13868. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13869. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13870. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13871. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13872. lensFlareSystem.render();
  13873. }
  13874. }
  13875. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13876. }
  13877. // Foregrounds
  13878. if (this.layers.length) {
  13879. engine.setDepthBuffer(false);
  13880. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13881. layer = this.layers[layerIndex];
  13882. if (!layer.isBackground) {
  13883. layer.render();
  13884. }
  13885. }
  13886. engine.setDepthBuffer(true);
  13887. }
  13888. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13889. // Finalize frame
  13890. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13891. // Update camera
  13892. this.activeCamera._updateFromScene();
  13893. // Reset some special arrays
  13894. this._renderTargets.reset();
  13895. if (this.afterCameraRender) {
  13896. this.afterCameraRender(this.activeCamera);
  13897. }
  13898. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13899. };
  13900. Scene.prototype._processSubCameras = function (camera) {
  13901. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13902. this._renderForCamera(camera);
  13903. return;
  13904. }
  13905. // rig cameras
  13906. for (var index = 0; index < camera._rigCameras.length; index++) {
  13907. this._renderForCamera(camera._rigCameras[index]);
  13908. }
  13909. this.activeCamera = camera;
  13910. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13911. // Update camera
  13912. this.activeCamera._updateFromScene();
  13913. };
  13914. Scene.prototype._checkIntersections = function () {
  13915. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13916. var sourceMesh = this._meshesForIntersections.data[index];
  13917. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13918. var action = sourceMesh.actionManager.actions[actionIndex];
  13919. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13920. var parameters = action.getTriggerParameter();
  13921. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13922. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13923. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13924. if (areIntersecting && currentIntersectionInProgress === -1) {
  13925. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13926. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13927. sourceMesh._intersectionsInProgress.push(otherMesh);
  13928. }
  13929. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13930. sourceMesh._intersectionsInProgress.push(otherMesh);
  13931. }
  13932. }
  13933. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13934. //They intersected, and now they don't.
  13935. //is this trigger an exit trigger? execute an event.
  13936. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13937. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13938. }
  13939. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13940. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13941. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13942. }
  13943. }
  13944. }
  13945. }
  13946. }
  13947. };
  13948. Scene.prototype.render = function () {
  13949. var startDate = BABYLON.Tools.Now;
  13950. this._particlesDuration = 0;
  13951. this._spritesDuration = 0;
  13952. this._activeParticles = 0;
  13953. this._renderDuration = 0;
  13954. this._renderTargetsDuration = 0;
  13955. this._evaluateActiveMeshesDuration = 0;
  13956. this._totalVertices = 0;
  13957. this._activeIndices = 0;
  13958. this._activeBones = 0;
  13959. this.getEngine().resetDrawCalls();
  13960. this._meshesForIntersections.reset();
  13961. this.resetCachedMaterial();
  13962. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13963. // Actions
  13964. if (this.actionManager) {
  13965. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13966. }
  13967. //Simplification Queue
  13968. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13969. this.simplificationQueue.executeNext();
  13970. }
  13971. // Animations
  13972. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13973. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13974. this._animate();
  13975. // Physics
  13976. if (this._physicsEngine) {
  13977. BABYLON.Tools.StartPerformanceCounter("Physics");
  13978. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13979. BABYLON.Tools.EndPerformanceCounter("Physics");
  13980. }
  13981. // Before render
  13982. if (this.beforeRender) {
  13983. this.beforeRender();
  13984. }
  13985. var callbackIndex;
  13986. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13987. this._onBeforeRenderCallbacks[callbackIndex]();
  13988. }
  13989. // Customs render targets
  13990. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13991. var engine = this.getEngine();
  13992. var currentActiveCamera = this.activeCamera;
  13993. if (this.renderTargetsEnabled) {
  13994. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13995. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13996. var renderTarget = this.customRenderTargets[customIndex];
  13997. if (renderTarget._shouldRender()) {
  13998. this._renderId++;
  13999. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14000. if (!this.activeCamera)
  14001. throw new Error("Active camera not set");
  14002. // Viewport
  14003. engine.setViewport(this.activeCamera.viewport);
  14004. // Camera
  14005. this.updateTransformMatrix();
  14006. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14007. }
  14008. }
  14009. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14010. this._renderId++;
  14011. }
  14012. if (this.customRenderTargets.length > 0) {
  14013. engine.restoreDefaultFramebuffer();
  14014. }
  14015. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14016. this.activeCamera = currentActiveCamera;
  14017. // Procedural textures
  14018. if (this.proceduralTexturesEnabled) {
  14019. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14020. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14021. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14022. if (proceduralTexture._shouldRender()) {
  14023. proceduralTexture.render();
  14024. }
  14025. }
  14026. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14027. }
  14028. // Clear
  14029. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14030. // Shadows
  14031. if (this.shadowsEnabled) {
  14032. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14033. var light = this.lights[lightIndex];
  14034. var shadowGenerator = light.getShadowGenerator();
  14035. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14036. this._renderTargets.push(shadowGenerator.getShadowMap());
  14037. }
  14038. }
  14039. }
  14040. // Depth renderer
  14041. if (this._depthRenderer) {
  14042. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14043. }
  14044. // RenderPipeline
  14045. this.postProcessRenderPipelineManager.update();
  14046. // Multi-cameras?
  14047. if (this.activeCameras.length > 0) {
  14048. var currentRenderId = this._renderId;
  14049. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14050. this._renderId = currentRenderId;
  14051. if (cameraIndex > 0) {
  14052. this._engine.clear(0, false, true);
  14053. }
  14054. this._processSubCameras(this.activeCameras[cameraIndex]);
  14055. }
  14056. }
  14057. else {
  14058. if (!this.activeCamera) {
  14059. throw new Error("No camera defined");
  14060. }
  14061. this._processSubCameras(this.activeCamera);
  14062. }
  14063. // Intersection checks
  14064. this._checkIntersections();
  14065. // Update the audio listener attached to the camera
  14066. if (BABYLON.AudioEngine) {
  14067. this._updateAudioParameters();
  14068. }
  14069. // After render
  14070. if (this.afterRender) {
  14071. this.afterRender();
  14072. }
  14073. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14074. this._onAfterRenderCallbacks[callbackIndex]();
  14075. }
  14076. // Cleaning
  14077. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14078. this._toBeDisposed.data[index].dispose();
  14079. this._toBeDisposed[index] = null;
  14080. }
  14081. this._toBeDisposed.reset();
  14082. if (this.dumpNextRenderTargets) {
  14083. this.dumpNextRenderTargets = false;
  14084. }
  14085. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14086. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14087. };
  14088. Scene.prototype._updateAudioParameters = function () {
  14089. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14090. return;
  14091. }
  14092. var listeningCamera;
  14093. var audioEngine = BABYLON.Engine.audioEngine;
  14094. if (this.activeCameras.length > 0) {
  14095. listeningCamera = this.activeCameras[0];
  14096. }
  14097. else {
  14098. listeningCamera = this.activeCamera;
  14099. }
  14100. if (listeningCamera && audioEngine.canUseWebAudio) {
  14101. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14102. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14103. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14104. cameraDirection.normalize();
  14105. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14106. var i;
  14107. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14108. var sound = this.mainSoundTrack.soundCollection[i];
  14109. if (sound.useCustomAttenuation) {
  14110. sound.updateDistanceFromListener();
  14111. }
  14112. }
  14113. for (i = 0; i < this.soundTracks.length; i++) {
  14114. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14115. sound = this.soundTracks[i].soundCollection[j];
  14116. if (sound.useCustomAttenuation) {
  14117. sound.updateDistanceFromListener();
  14118. }
  14119. }
  14120. }
  14121. }
  14122. };
  14123. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14124. // Audio
  14125. get: function () {
  14126. return this._audioEnabled;
  14127. },
  14128. set: function (value) {
  14129. this._audioEnabled = value;
  14130. if (BABYLON.AudioEngine) {
  14131. if (this._audioEnabled) {
  14132. this._enableAudio();
  14133. }
  14134. else {
  14135. this._disableAudio();
  14136. }
  14137. }
  14138. },
  14139. enumerable: true,
  14140. configurable: true
  14141. });
  14142. Scene.prototype._disableAudio = function () {
  14143. var i;
  14144. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14145. this.mainSoundTrack.soundCollection[i].pause();
  14146. }
  14147. for (i = 0; i < this.soundTracks.length; i++) {
  14148. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14149. this.soundTracks[i].soundCollection[j].pause();
  14150. }
  14151. }
  14152. };
  14153. Scene.prototype._enableAudio = function () {
  14154. var i;
  14155. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14156. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14157. this.mainSoundTrack.soundCollection[i].play();
  14158. }
  14159. }
  14160. for (i = 0; i < this.soundTracks.length; i++) {
  14161. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14162. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14163. this.soundTracks[i].soundCollection[j].play();
  14164. }
  14165. }
  14166. }
  14167. };
  14168. Object.defineProperty(Scene.prototype, "headphone", {
  14169. get: function () {
  14170. return this._headphone;
  14171. },
  14172. set: function (value) {
  14173. this._headphone = value;
  14174. if (BABYLON.AudioEngine) {
  14175. if (this._headphone) {
  14176. this._switchAudioModeForHeadphones();
  14177. }
  14178. else {
  14179. this._switchAudioModeForNormalSpeakers();
  14180. }
  14181. }
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. Scene.prototype._switchAudioModeForHeadphones = function () {
  14187. this.mainSoundTrack.switchPanningModelToHRTF();
  14188. for (var i = 0; i < this.soundTracks.length; i++) {
  14189. this.soundTracks[i].switchPanningModelToHRTF();
  14190. }
  14191. };
  14192. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14193. this.mainSoundTrack.switchPanningModelToEqualPower();
  14194. for (var i = 0; i < this.soundTracks.length; i++) {
  14195. this.soundTracks[i].switchPanningModelToEqualPower();
  14196. }
  14197. };
  14198. Scene.prototype.enableDepthRenderer = function () {
  14199. if (this._depthRenderer) {
  14200. return this._depthRenderer;
  14201. }
  14202. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14203. return this._depthRenderer;
  14204. };
  14205. Scene.prototype.disableDepthRenderer = function () {
  14206. if (!this._depthRenderer) {
  14207. return;
  14208. }
  14209. this._depthRenderer.dispose();
  14210. this._depthRenderer = null;
  14211. };
  14212. Scene.prototype.freezeMaterials = function () {
  14213. for (var i = 0; i < this.materials.length; i++) {
  14214. this.materials[i].freeze();
  14215. }
  14216. };
  14217. Scene.prototype.unfreezeMaterials = function () {
  14218. for (var i = 0; i < this.materials.length; i++) {
  14219. this.materials[i].unfreeze();
  14220. }
  14221. };
  14222. Scene.prototype.dispose = function () {
  14223. this.beforeRender = null;
  14224. this.afterRender = null;
  14225. this.skeletons = [];
  14226. this._boundingBoxRenderer.dispose();
  14227. if (this._depthRenderer) {
  14228. this._depthRenderer.dispose();
  14229. }
  14230. // Debug layer
  14231. this.debugLayer.hide();
  14232. // Events
  14233. if (this.onDispose) {
  14234. this.onDispose();
  14235. }
  14236. this._onBeforeRenderCallbacks = [];
  14237. this._onAfterRenderCallbacks = [];
  14238. this.detachControl();
  14239. // Release sounds & sounds tracks
  14240. if (BABYLON.AudioEngine) {
  14241. this.disposeSounds();
  14242. }
  14243. // Detach cameras
  14244. var canvas = this._engine.getRenderingCanvas();
  14245. var index;
  14246. for (index = 0; index < this.cameras.length; index++) {
  14247. this.cameras[index].detachControl(canvas);
  14248. }
  14249. // Release lights
  14250. while (this.lights.length) {
  14251. this.lights[0].dispose();
  14252. }
  14253. // Release meshes
  14254. while (this.meshes.length) {
  14255. this.meshes[0].dispose(true);
  14256. }
  14257. // Release cameras
  14258. while (this.cameras.length) {
  14259. this.cameras[0].dispose();
  14260. }
  14261. // Release materials
  14262. while (this.materials.length) {
  14263. this.materials[0].dispose();
  14264. }
  14265. // Release particles
  14266. while (this.particleSystems.length) {
  14267. this.particleSystems[0].dispose();
  14268. }
  14269. // Release sprites
  14270. while (this.spriteManagers.length) {
  14271. this.spriteManagers[0].dispose();
  14272. }
  14273. // Release layers
  14274. while (this.layers.length) {
  14275. this.layers[0].dispose();
  14276. }
  14277. // Release textures
  14278. while (this.textures.length) {
  14279. this.textures[0].dispose();
  14280. }
  14281. // Post-processes
  14282. this.postProcessManager.dispose();
  14283. // Physics
  14284. if (this._physicsEngine) {
  14285. this.disablePhysicsEngine();
  14286. }
  14287. // Remove from engine
  14288. index = this._engine.scenes.indexOf(this);
  14289. if (index > -1) {
  14290. this._engine.scenes.splice(index, 1);
  14291. }
  14292. this._engine.wipeCaches();
  14293. };
  14294. // Release sounds & sounds tracks
  14295. Scene.prototype.disposeSounds = function () {
  14296. this.mainSoundTrack.dispose();
  14297. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14298. this.soundTracks[scIndex].dispose();
  14299. }
  14300. };
  14301. // Octrees
  14302. Scene.prototype.getWorldExtends = function () {
  14303. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14304. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14305. for (var index = 0; index < this.meshes.length; index++) {
  14306. var mesh = this.meshes[index];
  14307. mesh.computeWorldMatrix(true);
  14308. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14309. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14310. BABYLON.Tools.CheckExtends(minBox, min, max);
  14311. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14312. }
  14313. return {
  14314. min: min,
  14315. max: max
  14316. };
  14317. };
  14318. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14319. if (maxCapacity === void 0) { maxCapacity = 64; }
  14320. if (maxDepth === void 0) { maxDepth = 2; }
  14321. if (!this._selectionOctree) {
  14322. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14323. }
  14324. var worldExtends = this.getWorldExtends();
  14325. // Update octree
  14326. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14327. return this._selectionOctree;
  14328. };
  14329. // Picking
  14330. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14331. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14332. var engine = this._engine;
  14333. if (!camera) {
  14334. if (!this.activeCamera)
  14335. throw new Error("Active camera not set");
  14336. camera = this.activeCamera;
  14337. }
  14338. var cameraViewport = camera.viewport;
  14339. var viewport = cameraViewport.toGlobal(engine);
  14340. // Moving coordinates to local viewport world
  14341. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14342. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14343. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14344. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14345. };
  14346. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14347. var engine = this._engine;
  14348. if (!camera) {
  14349. if (!this.activeCamera)
  14350. throw new Error("Active camera not set");
  14351. camera = this.activeCamera;
  14352. }
  14353. var cameraViewport = camera.viewport;
  14354. var viewport = cameraViewport.toGlobal(engine);
  14355. var identity = BABYLON.Matrix.Identity();
  14356. // Moving coordinates to local viewport world
  14357. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14358. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14359. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14360. };
  14361. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14362. var pickingInfo = null;
  14363. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14364. var mesh = this.meshes[meshIndex];
  14365. if (predicate) {
  14366. if (!predicate(mesh)) {
  14367. continue;
  14368. }
  14369. }
  14370. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14371. continue;
  14372. }
  14373. var world = mesh.getWorldMatrix();
  14374. var ray = rayFunction(world);
  14375. var result = mesh.intersects(ray, fastCheck);
  14376. if (!result || !result.hit)
  14377. continue;
  14378. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14379. continue;
  14380. pickingInfo = result;
  14381. if (fastCheck) {
  14382. break;
  14383. }
  14384. }
  14385. return pickingInfo || new BABYLON.PickingInfo();
  14386. };
  14387. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14388. var pickingInfo = null;
  14389. camera = camera || this.activeCamera;
  14390. if (this.spriteManagers.length > 0) {
  14391. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14392. var spriteManager = this.spriteManagers[spriteIndex];
  14393. if (!spriteManager.isPickable) {
  14394. continue;
  14395. }
  14396. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14397. if (!result || !result.hit)
  14398. continue;
  14399. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14400. continue;
  14401. pickingInfo = result;
  14402. if (fastCheck) {
  14403. break;
  14404. }
  14405. }
  14406. }
  14407. return pickingInfo || new BABYLON.PickingInfo();
  14408. };
  14409. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14410. var _this = this;
  14411. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14412. /// <param name="x">X position on screen</param>
  14413. /// <param name="y">Y position on screen</param>
  14414. /// <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>
  14415. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14416. /// <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>
  14417. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14418. };
  14419. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14420. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14421. /// <param name="x">X position on screen</param>
  14422. /// <param name="y">Y position on screen</param>
  14423. /// <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>
  14424. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14425. /// <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>
  14426. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14427. };
  14428. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14429. var _this = this;
  14430. return this._internalPick(function (world) {
  14431. if (!_this._pickWithRayInverseMatrix) {
  14432. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14433. }
  14434. world.invertToRef(_this._pickWithRayInverseMatrix);
  14435. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14436. }, predicate, fastCheck);
  14437. };
  14438. Scene.prototype.setPointerOverMesh = function (mesh) {
  14439. if (this._pointerOverMesh === mesh) {
  14440. return;
  14441. }
  14442. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14443. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14444. }
  14445. this._pointerOverMesh = mesh;
  14446. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14447. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14448. }
  14449. };
  14450. Scene.prototype.getPointerOverMesh = function () {
  14451. return this._pointerOverMesh;
  14452. };
  14453. Scene.prototype.setPointerOverSprite = function (sprite) {
  14454. if (this._pointerOverSprite === sprite) {
  14455. return;
  14456. }
  14457. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14458. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14459. }
  14460. this._pointerOverSprite = sprite;
  14461. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14462. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14463. }
  14464. };
  14465. Scene.prototype.getPointerOverSprite = function () {
  14466. return this._pointerOverSprite;
  14467. };
  14468. // Physics
  14469. Scene.prototype.getPhysicsEngine = function () {
  14470. return this._physicsEngine;
  14471. };
  14472. /**
  14473. * Enables physics to the current scene
  14474. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14475. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14476. * @return {boolean} was the physics engine initialized
  14477. */
  14478. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14479. if (this._physicsEngine) {
  14480. return true;
  14481. }
  14482. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14483. if (!this._physicsEngine.isSupported()) {
  14484. this._physicsEngine = null;
  14485. return false;
  14486. }
  14487. this._physicsEngine._initialize(gravity);
  14488. return true;
  14489. };
  14490. Scene.prototype.disablePhysicsEngine = function () {
  14491. if (!this._physicsEngine) {
  14492. return;
  14493. }
  14494. this._physicsEngine.dispose();
  14495. this._physicsEngine = undefined;
  14496. };
  14497. Scene.prototype.isPhysicsEnabled = function () {
  14498. return this._physicsEngine !== undefined;
  14499. };
  14500. /**
  14501. * Sets the gravity of the physics engine (and NOT of the scene)
  14502. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14503. */
  14504. Scene.prototype.setGravity = function (gravity) {
  14505. if (!this._physicsEngine) {
  14506. return;
  14507. }
  14508. this._physicsEngine._setGravity(gravity);
  14509. };
  14510. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14511. if (parts.parts) {
  14512. options = parts;
  14513. parts = parts.parts;
  14514. }
  14515. if (!this._physicsEngine) {
  14516. return null;
  14517. }
  14518. for (var index = 0; index < parts.length; index++) {
  14519. var mesh = parts[index].mesh;
  14520. mesh._physicImpostor = parts[index].impostor;
  14521. mesh._physicsMass = options.mass / parts.length;
  14522. mesh._physicsFriction = options.friction;
  14523. mesh._physicRestitution = options.restitution;
  14524. }
  14525. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14526. };
  14527. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14528. for (var index = 0; index < compound.parts.length; index++) {
  14529. var mesh = compound.parts[index].mesh;
  14530. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14531. this._physicsEngine._unregisterMesh(mesh);
  14532. }
  14533. };
  14534. // Misc.
  14535. Scene.prototype.createDefaultCameraOrLight = function () {
  14536. // Light
  14537. if (this.lights.length === 0) {
  14538. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14539. }
  14540. // Camera
  14541. if (!this.activeCamera) {
  14542. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14543. // Compute position
  14544. var worldExtends = this.getWorldExtends();
  14545. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14546. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14547. camera.setTarget(worldCenter);
  14548. this.activeCamera = camera;
  14549. }
  14550. };
  14551. // Tags
  14552. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14553. if (tagsQuery === undefined) {
  14554. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14555. return list;
  14556. }
  14557. var listByTags = [];
  14558. forEach = forEach || (function (item) { return; });
  14559. for (var i in list) {
  14560. var item = list[i];
  14561. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14562. listByTags.push(item);
  14563. forEach(item);
  14564. }
  14565. }
  14566. return listByTags;
  14567. };
  14568. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14569. return this._getByTags(this.meshes, tagsQuery, forEach);
  14570. };
  14571. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14572. return this._getByTags(this.cameras, tagsQuery, forEach);
  14573. };
  14574. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14575. return this._getByTags(this.lights, tagsQuery, forEach);
  14576. };
  14577. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14578. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14579. };
  14580. // Statics
  14581. Scene._FOGMODE_NONE = 0;
  14582. Scene._FOGMODE_EXP = 1;
  14583. Scene._FOGMODE_EXP2 = 2;
  14584. Scene._FOGMODE_LINEAR = 3;
  14585. Scene.MinDeltaTime = 1.0;
  14586. Scene.MaxDeltaTime = 1000.0;
  14587. return Scene;
  14588. })();
  14589. BABYLON.Scene = Scene;
  14590. })(BABYLON || (BABYLON = {}));
  14591. var BABYLON;
  14592. (function (BABYLON) {
  14593. var VertexBuffer = (function () {
  14594. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14595. if (engine instanceof BABYLON.Mesh) {
  14596. this._engine = engine.getScene().getEngine();
  14597. }
  14598. else {
  14599. this._engine = engine;
  14600. }
  14601. this._updatable = updatable;
  14602. this._data = data;
  14603. if (!postponeInternalCreation) {
  14604. this.create();
  14605. }
  14606. this._kind = kind;
  14607. if (stride) {
  14608. this._strideSize = stride;
  14609. return;
  14610. }
  14611. // Deduce stride from kind
  14612. switch (kind) {
  14613. case VertexBuffer.PositionKind:
  14614. this._strideSize = 3;
  14615. break;
  14616. case VertexBuffer.NormalKind:
  14617. this._strideSize = 3;
  14618. break;
  14619. case VertexBuffer.UVKind:
  14620. case VertexBuffer.UV2Kind:
  14621. case VertexBuffer.UV3Kind:
  14622. case VertexBuffer.UV4Kind:
  14623. case VertexBuffer.UV5Kind:
  14624. case VertexBuffer.UV6Kind:
  14625. this._strideSize = 2;
  14626. break;
  14627. case VertexBuffer.ColorKind:
  14628. this._strideSize = 4;
  14629. break;
  14630. case VertexBuffer.MatricesIndicesKind:
  14631. case VertexBuffer.MatricesIndicesExtraKind:
  14632. this._strideSize = 4;
  14633. break;
  14634. case VertexBuffer.MatricesWeightsKind:
  14635. case VertexBuffer.MatricesWeightsExtraKind:
  14636. this._strideSize = 4;
  14637. break;
  14638. }
  14639. }
  14640. // Properties
  14641. VertexBuffer.prototype.isUpdatable = function () {
  14642. return this._updatable;
  14643. };
  14644. VertexBuffer.prototype.getData = function () {
  14645. return this._data;
  14646. };
  14647. VertexBuffer.prototype.getBuffer = function () {
  14648. return this._buffer;
  14649. };
  14650. VertexBuffer.prototype.getStrideSize = function () {
  14651. return this._strideSize;
  14652. };
  14653. // Methods
  14654. VertexBuffer.prototype.create = function (data) {
  14655. if (!data && this._buffer) {
  14656. return; // nothing to do
  14657. }
  14658. data = data || this._data;
  14659. if (!this._buffer) {
  14660. if (this._updatable) {
  14661. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14662. }
  14663. else {
  14664. this._buffer = this._engine.createVertexBuffer(data);
  14665. }
  14666. }
  14667. if (this._updatable) {
  14668. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14669. this._data = data;
  14670. }
  14671. };
  14672. VertexBuffer.prototype.update = function (data) {
  14673. this.create(data);
  14674. };
  14675. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14676. if (!this._buffer) {
  14677. return;
  14678. }
  14679. if (this._updatable) {
  14680. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14681. this._data = null;
  14682. }
  14683. };
  14684. VertexBuffer.prototype.dispose = function () {
  14685. if (!this._buffer) {
  14686. return;
  14687. }
  14688. if (this._engine._releaseBuffer(this._buffer)) {
  14689. this._buffer = null;
  14690. }
  14691. };
  14692. Object.defineProperty(VertexBuffer, "PositionKind", {
  14693. get: function () {
  14694. return VertexBuffer._PositionKind;
  14695. },
  14696. enumerable: true,
  14697. configurable: true
  14698. });
  14699. Object.defineProperty(VertexBuffer, "NormalKind", {
  14700. get: function () {
  14701. return VertexBuffer._NormalKind;
  14702. },
  14703. enumerable: true,
  14704. configurable: true
  14705. });
  14706. Object.defineProperty(VertexBuffer, "UVKind", {
  14707. get: function () {
  14708. return VertexBuffer._UVKind;
  14709. },
  14710. enumerable: true,
  14711. configurable: true
  14712. });
  14713. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14714. get: function () {
  14715. return VertexBuffer._UV2Kind;
  14716. },
  14717. enumerable: true,
  14718. configurable: true
  14719. });
  14720. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14721. get: function () {
  14722. return VertexBuffer._UV3Kind;
  14723. },
  14724. enumerable: true,
  14725. configurable: true
  14726. });
  14727. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14728. get: function () {
  14729. return VertexBuffer._UV4Kind;
  14730. },
  14731. enumerable: true,
  14732. configurable: true
  14733. });
  14734. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14735. get: function () {
  14736. return VertexBuffer._UV5Kind;
  14737. },
  14738. enumerable: true,
  14739. configurable: true
  14740. });
  14741. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14742. get: function () {
  14743. return VertexBuffer._UV6Kind;
  14744. },
  14745. enumerable: true,
  14746. configurable: true
  14747. });
  14748. Object.defineProperty(VertexBuffer, "ColorKind", {
  14749. get: function () {
  14750. return VertexBuffer._ColorKind;
  14751. },
  14752. enumerable: true,
  14753. configurable: true
  14754. });
  14755. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14756. get: function () {
  14757. return VertexBuffer._MatricesIndicesKind;
  14758. },
  14759. enumerable: true,
  14760. configurable: true
  14761. });
  14762. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14763. get: function () {
  14764. return VertexBuffer._MatricesWeightsKind;
  14765. },
  14766. enumerable: true,
  14767. configurable: true
  14768. });
  14769. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14770. get: function () {
  14771. return VertexBuffer._MatricesIndicesExtraKind;
  14772. },
  14773. enumerable: true,
  14774. configurable: true
  14775. });
  14776. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14777. get: function () {
  14778. return VertexBuffer._MatricesWeightsExtraKind;
  14779. },
  14780. enumerable: true,
  14781. configurable: true
  14782. });
  14783. // Enums
  14784. VertexBuffer._PositionKind = "position";
  14785. VertexBuffer._NormalKind = "normal";
  14786. VertexBuffer._UVKind = "uv";
  14787. VertexBuffer._UV2Kind = "uv2";
  14788. VertexBuffer._UV3Kind = "uv3";
  14789. VertexBuffer._UV4Kind = "uv4";
  14790. VertexBuffer._UV5Kind = "uv5";
  14791. VertexBuffer._UV6Kind = "uv6";
  14792. VertexBuffer._ColorKind = "color";
  14793. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14794. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14795. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14796. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14797. return VertexBuffer;
  14798. })();
  14799. BABYLON.VertexBuffer = VertexBuffer;
  14800. })(BABYLON || (BABYLON = {}));
  14801. var BABYLON;
  14802. (function (BABYLON) {
  14803. /**
  14804. * Creates an instance based on a source mesh.
  14805. */
  14806. var InstancedMesh = (function (_super) {
  14807. __extends(InstancedMesh, _super);
  14808. function InstancedMesh(name, source) {
  14809. _super.call(this, name, source.getScene());
  14810. source.instances.push(this);
  14811. this._sourceMesh = source;
  14812. this.position.copyFrom(source.position);
  14813. this.rotation.copyFrom(source.rotation);
  14814. this.scaling.copyFrom(source.scaling);
  14815. if (source.rotationQuaternion) {
  14816. this.rotationQuaternion = source.rotationQuaternion.clone();
  14817. }
  14818. this.infiniteDistance = source.infiniteDistance;
  14819. this.setPivotMatrix(source.getPivotMatrix());
  14820. this.refreshBoundingInfo();
  14821. this._syncSubMeshes();
  14822. }
  14823. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14824. // Methods
  14825. get: function () {
  14826. return this._sourceMesh.receiveShadows;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(InstancedMesh.prototype, "material", {
  14832. get: function () {
  14833. return this._sourceMesh.material;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14839. get: function () {
  14840. return this._sourceMesh.visibility;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14846. get: function () {
  14847. return this._sourceMesh.skeleton;
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14853. get: function () {
  14854. return this._sourceMesh.renderingGroupId;
  14855. },
  14856. enumerable: true,
  14857. configurable: true
  14858. });
  14859. InstancedMesh.prototype.getTotalVertices = function () {
  14860. return this._sourceMesh.getTotalVertices();
  14861. };
  14862. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14863. get: function () {
  14864. return this._sourceMesh;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14870. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14871. };
  14872. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14873. return this._sourceMesh.isVerticesDataPresent(kind);
  14874. };
  14875. InstancedMesh.prototype.getIndices = function () {
  14876. return this._sourceMesh.getIndices();
  14877. };
  14878. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14879. get: function () {
  14880. return this._sourceMesh._positions;
  14881. },
  14882. enumerable: true,
  14883. configurable: true
  14884. });
  14885. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14886. var meshBB = this._sourceMesh.getBoundingInfo();
  14887. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14888. this._updateBoundingInfo();
  14889. };
  14890. InstancedMesh.prototype._preActivate = function () {
  14891. if (this._currentLOD) {
  14892. this._currentLOD._preActivate();
  14893. }
  14894. };
  14895. InstancedMesh.prototype._activate = function (renderId) {
  14896. if (this._currentLOD) {
  14897. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14898. }
  14899. };
  14900. InstancedMesh.prototype.getLOD = function (camera) {
  14901. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14902. if (this._currentLOD === this.sourceMesh) {
  14903. return this;
  14904. }
  14905. return this._currentLOD;
  14906. };
  14907. InstancedMesh.prototype._syncSubMeshes = function () {
  14908. this.releaseSubMeshes();
  14909. if (this._sourceMesh.subMeshes) {
  14910. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14911. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14912. }
  14913. }
  14914. };
  14915. InstancedMesh.prototype._generatePointsArray = function () {
  14916. return this._sourceMesh._generatePointsArray();
  14917. };
  14918. // Clone
  14919. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14920. var result = this._sourceMesh.createInstance(name);
  14921. // Deep copy
  14922. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14923. // Bounding info
  14924. this.refreshBoundingInfo();
  14925. // Parent
  14926. if (newParent) {
  14927. result.parent = newParent;
  14928. }
  14929. if (!doNotCloneChildren) {
  14930. // Children
  14931. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14932. var mesh = this.getScene().meshes[index];
  14933. if (mesh.parent === this) {
  14934. mesh.clone(mesh.name, result);
  14935. }
  14936. }
  14937. }
  14938. result.computeWorldMatrix(true);
  14939. return result;
  14940. };
  14941. // Dispoe
  14942. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14943. // Remove from mesh
  14944. var index = this._sourceMesh.instances.indexOf(this);
  14945. this._sourceMesh.instances.splice(index, 1);
  14946. _super.prototype.dispose.call(this, doNotRecurse);
  14947. };
  14948. return InstancedMesh;
  14949. })(BABYLON.AbstractMesh);
  14950. BABYLON.InstancedMesh = InstancedMesh;
  14951. })(BABYLON || (BABYLON = {}));
  14952. var BABYLON;
  14953. (function (BABYLON) {
  14954. var _InstancesBatch = (function () {
  14955. function _InstancesBatch() {
  14956. this.mustReturn = false;
  14957. this.visibleInstances = new Array();
  14958. this.renderSelf = new Array();
  14959. }
  14960. return _InstancesBatch;
  14961. })();
  14962. BABYLON._InstancesBatch = _InstancesBatch;
  14963. var Mesh = (function (_super) {
  14964. __extends(Mesh, _super);
  14965. /**
  14966. * @constructor
  14967. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14968. * @param {Scene} scene - The scene to add this mesh to.
  14969. * @param {Node} parent - The parent of this mesh, if it has one
  14970. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14971. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14972. * When false, achieved by calling a clone(), also passing False.
  14973. * This will make creation of children, recursive.
  14974. */
  14975. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14976. if (parent === void 0) { parent = null; }
  14977. _super.call(this, name, scene);
  14978. // Members
  14979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14980. this.instances = new Array();
  14981. this._LODLevels = new Array();
  14982. this._onBeforeRenderCallbacks = new Array();
  14983. this._onAfterRenderCallbacks = new Array();
  14984. this._visibleInstances = {};
  14985. this._renderIdForInstances = new Array();
  14986. this._batchCache = new _InstancesBatch();
  14987. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14988. this._sideOrientation = Mesh._DEFAULTSIDE;
  14989. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14990. if (source) {
  14991. // Geometry
  14992. if (source._geometry) {
  14993. source._geometry.applyToMesh(this);
  14994. }
  14995. // Deep copy
  14996. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14997. // Pivot
  14998. this.setPivotMatrix(source.getPivotMatrix());
  14999. this.id = name + "." + source.id;
  15000. // Material
  15001. this.material = source.material;
  15002. var index;
  15003. if (!doNotCloneChildren) {
  15004. // Children
  15005. for (index = 0; index < scene.meshes.length; index++) {
  15006. var mesh = scene.meshes[index];
  15007. if (mesh.parent === source) {
  15008. // doNotCloneChildren is always going to be False
  15009. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15010. }
  15011. }
  15012. }
  15013. // Particles
  15014. for (index = 0; index < scene.particleSystems.length; index++) {
  15015. var system = scene.particleSystems[index];
  15016. if (system.emitter === source) {
  15017. system.clone(system.name, this);
  15018. }
  15019. }
  15020. this.computeWorldMatrix(true);
  15021. }
  15022. // Parent
  15023. if (parent !== null) {
  15024. this.parent = parent;
  15025. }
  15026. }
  15027. Object.defineProperty(Mesh, "FRONTSIDE", {
  15028. get: function () {
  15029. return Mesh._FRONTSIDE;
  15030. },
  15031. enumerable: true,
  15032. configurable: true
  15033. });
  15034. Object.defineProperty(Mesh, "BACKSIDE", {
  15035. get: function () {
  15036. return Mesh._BACKSIDE;
  15037. },
  15038. enumerable: true,
  15039. configurable: true
  15040. });
  15041. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15042. get: function () {
  15043. return Mesh._DOUBLESIDE;
  15044. },
  15045. enumerable: true,
  15046. configurable: true
  15047. });
  15048. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15049. get: function () {
  15050. return Mesh._DEFAULTSIDE;
  15051. },
  15052. enumerable: true,
  15053. configurable: true
  15054. });
  15055. Object.defineProperty(Mesh, "NO_CAP", {
  15056. get: function () {
  15057. return Mesh._NO_CAP;
  15058. },
  15059. enumerable: true,
  15060. configurable: true
  15061. });
  15062. Object.defineProperty(Mesh, "CAP_START", {
  15063. get: function () {
  15064. return Mesh._CAP_START;
  15065. },
  15066. enumerable: true,
  15067. configurable: true
  15068. });
  15069. Object.defineProperty(Mesh, "CAP_END", {
  15070. get: function () {
  15071. return Mesh._CAP_END;
  15072. },
  15073. enumerable: true,
  15074. configurable: true
  15075. });
  15076. Object.defineProperty(Mesh, "CAP_ALL", {
  15077. get: function () {
  15078. return Mesh._CAP_ALL;
  15079. },
  15080. enumerable: true,
  15081. configurable: true
  15082. });
  15083. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15084. // Methods
  15085. get: function () {
  15086. return this._LODLevels.length > 0;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Mesh.prototype._sortLODLevels = function () {
  15092. this._LODLevels.sort(function (a, b) {
  15093. if (a.distance < b.distance) {
  15094. return 1;
  15095. }
  15096. if (a.distance > b.distance) {
  15097. return -1;
  15098. }
  15099. return 0;
  15100. });
  15101. };
  15102. /**
  15103. * Add a mesh as LOD level triggered at the given distance.
  15104. * @param {number} distance - the distance from the center of the object to show this level
  15105. * @param {Mesh} mesh - the mesh to be added as LOD level
  15106. * @return {Mesh} this mesh (for chaining)
  15107. */
  15108. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15109. if (mesh && mesh._masterMesh) {
  15110. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15111. return this;
  15112. }
  15113. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15114. this._LODLevels.push(level);
  15115. if (mesh) {
  15116. mesh._masterMesh = this;
  15117. }
  15118. this._sortLODLevels();
  15119. return this;
  15120. };
  15121. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15122. for (var index = 0; index < this._LODLevels.length; index++) {
  15123. var level = this._LODLevels[index];
  15124. if (level.distance === distance) {
  15125. return level.mesh;
  15126. }
  15127. }
  15128. return null;
  15129. };
  15130. /**
  15131. * Remove a mesh from the LOD array
  15132. * @param {Mesh} mesh - the mesh to be removed.
  15133. * @return {Mesh} this mesh (for chaining)
  15134. */
  15135. Mesh.prototype.removeLODLevel = function (mesh) {
  15136. for (var index = 0; index < this._LODLevels.length; index++) {
  15137. if (this._LODLevels[index].mesh === mesh) {
  15138. this._LODLevels.splice(index, 1);
  15139. if (mesh) {
  15140. mesh._masterMesh = null;
  15141. }
  15142. }
  15143. }
  15144. this._sortLODLevels();
  15145. return this;
  15146. };
  15147. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15148. if (!this._LODLevels || this._LODLevels.length === 0) {
  15149. return this;
  15150. }
  15151. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15152. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15153. if (this.onLODLevelSelection) {
  15154. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15155. }
  15156. return this;
  15157. }
  15158. for (var index = 0; index < this._LODLevels.length; index++) {
  15159. var level = this._LODLevels[index];
  15160. if (level.distance < distanceToCamera) {
  15161. if (level.mesh) {
  15162. level.mesh._preActivate();
  15163. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15164. }
  15165. if (this.onLODLevelSelection) {
  15166. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15167. }
  15168. return level.mesh;
  15169. }
  15170. }
  15171. if (this.onLODLevelSelection) {
  15172. this.onLODLevelSelection(distanceToCamera, this, this);
  15173. }
  15174. return this;
  15175. };
  15176. Object.defineProperty(Mesh.prototype, "geometry", {
  15177. get: function () {
  15178. return this._geometry;
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Mesh.prototype.getTotalVertices = function () {
  15184. if (!this._geometry) {
  15185. return 0;
  15186. }
  15187. return this._geometry.getTotalVertices();
  15188. };
  15189. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15190. if (!this._geometry) {
  15191. return null;
  15192. }
  15193. return this._geometry.getVerticesData(kind, copyWhenShared);
  15194. };
  15195. Mesh.prototype.getVertexBuffer = function (kind) {
  15196. if (!this._geometry) {
  15197. return undefined;
  15198. }
  15199. return this._geometry.getVertexBuffer(kind);
  15200. };
  15201. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15202. if (!this._geometry) {
  15203. if (this._delayInfo) {
  15204. return this._delayInfo.indexOf(kind) !== -1;
  15205. }
  15206. return false;
  15207. }
  15208. return this._geometry.isVerticesDataPresent(kind);
  15209. };
  15210. Mesh.prototype.getVerticesDataKinds = function () {
  15211. if (!this._geometry) {
  15212. var result = [];
  15213. if (this._delayInfo) {
  15214. for (var kind in this._delayInfo) {
  15215. result.push(kind);
  15216. }
  15217. }
  15218. return result;
  15219. }
  15220. return this._geometry.getVerticesDataKinds();
  15221. };
  15222. Mesh.prototype.getTotalIndices = function () {
  15223. if (!this._geometry) {
  15224. return 0;
  15225. }
  15226. return this._geometry.getTotalIndices();
  15227. };
  15228. Mesh.prototype.getIndices = function (copyWhenShared) {
  15229. if (!this._geometry) {
  15230. return [];
  15231. }
  15232. return this._geometry.getIndices(copyWhenShared);
  15233. };
  15234. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15235. get: function () {
  15236. return this._masterMesh !== null && this._masterMesh !== undefined;
  15237. },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Mesh.prototype.isReady = function () {
  15242. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15243. return false;
  15244. }
  15245. return _super.prototype.isReady.call(this);
  15246. };
  15247. Mesh.prototype.isDisposed = function () {
  15248. return this._isDisposed;
  15249. };
  15250. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15251. get: function () {
  15252. return this._sideOrientation;
  15253. },
  15254. set: function (sideO) {
  15255. this._sideOrientation = sideO;
  15256. },
  15257. enumerable: true,
  15258. configurable: true
  15259. });
  15260. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15261. get: function () {
  15262. return this._areNormalsFrozen;
  15263. },
  15264. enumerable: true,
  15265. configurable: true
  15266. });
  15267. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15268. Mesh.prototype.freezeNormals = function () {
  15269. this._areNormalsFrozen = true;
  15270. };
  15271. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15272. Mesh.prototype.unfreezeNormals = function () {
  15273. this._areNormalsFrozen = false;
  15274. };
  15275. // Methods
  15276. Mesh.prototype._preActivate = function () {
  15277. var sceneRenderId = this.getScene().getRenderId();
  15278. if (this._preActivateId === sceneRenderId) {
  15279. return;
  15280. }
  15281. this._preActivateId = sceneRenderId;
  15282. this._visibleInstances = null;
  15283. };
  15284. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15285. if (!this._visibleInstances) {
  15286. this._visibleInstances = {};
  15287. this._visibleInstances.defaultRenderId = renderId;
  15288. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15289. }
  15290. if (!this._visibleInstances[renderId]) {
  15291. this._visibleInstances[renderId] = new Array();
  15292. }
  15293. this._visibleInstances[renderId].push(instance);
  15294. };
  15295. Mesh.prototype.refreshBoundingInfo = function () {
  15296. if (this._boundingInfo.isLocked) {
  15297. return;
  15298. }
  15299. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15300. if (data) {
  15301. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15302. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15303. }
  15304. if (this.subMeshes) {
  15305. for (var index = 0; index < this.subMeshes.length; index++) {
  15306. this.subMeshes[index].refreshBoundingInfo();
  15307. }
  15308. }
  15309. this._updateBoundingInfo();
  15310. };
  15311. Mesh.prototype._createGlobalSubMesh = function () {
  15312. var totalVertices = this.getTotalVertices();
  15313. if (!totalVertices || !this.getIndices()) {
  15314. return null;
  15315. }
  15316. this.releaseSubMeshes();
  15317. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15318. };
  15319. Mesh.prototype.subdivide = function (count) {
  15320. if (count < 1) {
  15321. return;
  15322. }
  15323. var totalIndices = this.getTotalIndices();
  15324. var subdivisionSize = (totalIndices / count) | 0;
  15325. var offset = 0;
  15326. // Ensure that subdivisionSize is a multiple of 3
  15327. while (subdivisionSize % 3 !== 0) {
  15328. subdivisionSize++;
  15329. }
  15330. this.releaseSubMeshes();
  15331. for (var index = 0; index < count; index++) {
  15332. if (offset >= totalIndices) {
  15333. break;
  15334. }
  15335. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15336. offset += subdivisionSize;
  15337. }
  15338. this.synchronizeInstances();
  15339. };
  15340. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15341. if (!this._geometry) {
  15342. var vertexData = new BABYLON.VertexData();
  15343. vertexData.set(data, kind);
  15344. var scene = this.getScene();
  15345. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15346. }
  15347. else {
  15348. this._geometry.setVerticesData(kind, data, updatable, stride);
  15349. }
  15350. };
  15351. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15352. if (!this._geometry) {
  15353. return;
  15354. }
  15355. if (!makeItUnique) {
  15356. this._geometry.updateVerticesData(kind, data, updateExtends);
  15357. }
  15358. else {
  15359. this.makeGeometryUnique();
  15360. this.updateVerticesData(kind, data, updateExtends, false);
  15361. }
  15362. };
  15363. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15364. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15365. if (!this._geometry) {
  15366. return;
  15367. }
  15368. if (!makeItUnique) {
  15369. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15370. }
  15371. else {
  15372. this.makeGeometryUnique();
  15373. this.updateVerticesDataDirectly(kind, data, offset, false);
  15374. }
  15375. };
  15376. // Mesh positions update function :
  15377. // updates the mesh positions according to the positionFunction returned values.
  15378. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15379. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15380. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15381. if (computeNormals === void 0) { computeNormals = true; }
  15382. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15383. positionFunction(positions);
  15384. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15385. if (computeNormals) {
  15386. var indices = this.getIndices();
  15387. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15388. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15389. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15390. }
  15391. };
  15392. Mesh.prototype.makeGeometryUnique = function () {
  15393. if (!this._geometry) {
  15394. return;
  15395. }
  15396. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15397. geometry.applyToMesh(this);
  15398. };
  15399. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15400. if (!this._geometry) {
  15401. var vertexData = new BABYLON.VertexData();
  15402. vertexData.indices = indices;
  15403. var scene = this.getScene();
  15404. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15405. }
  15406. else {
  15407. this._geometry.setIndices(indices, totalVertices);
  15408. }
  15409. };
  15410. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15411. var engine = this.getScene().getEngine();
  15412. // Wireframe
  15413. var indexToBind;
  15414. if (this._unIndexed) {
  15415. indexToBind = null;
  15416. }
  15417. else {
  15418. switch (fillMode) {
  15419. case BABYLON.Material.PointFillMode:
  15420. indexToBind = null;
  15421. break;
  15422. case BABYLON.Material.WireFrameFillMode:
  15423. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15424. break;
  15425. default:
  15426. case BABYLON.Material.TriangleFillMode:
  15427. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15428. break;
  15429. }
  15430. }
  15431. // VBOs
  15432. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15433. };
  15434. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15435. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15436. return;
  15437. }
  15438. if (this.onBeforeDraw) {
  15439. this.onBeforeDraw();
  15440. }
  15441. var engine = this.getScene().getEngine();
  15442. // Draw order
  15443. switch (fillMode) {
  15444. case BABYLON.Material.PointFillMode:
  15445. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15446. break;
  15447. case BABYLON.Material.WireFrameFillMode:
  15448. if (this._unIndexed) {
  15449. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15450. }
  15451. else {
  15452. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15453. }
  15454. break;
  15455. default:
  15456. if (this._unIndexed) {
  15457. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15458. }
  15459. else {
  15460. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15461. }
  15462. }
  15463. };
  15464. Mesh.prototype.registerBeforeRender = function (func) {
  15465. this._onBeforeRenderCallbacks.push(func);
  15466. };
  15467. Mesh.prototype.unregisterBeforeRender = function (func) {
  15468. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15469. if (index > -1) {
  15470. this._onBeforeRenderCallbacks.splice(index, 1);
  15471. }
  15472. };
  15473. Mesh.prototype.registerAfterRender = function (func) {
  15474. this._onAfterRenderCallbacks.push(func);
  15475. };
  15476. Mesh.prototype.unregisterAfterRender = function (func) {
  15477. var index = this._onAfterRenderCallbacks.indexOf(func);
  15478. if (index > -1) {
  15479. this._onAfterRenderCallbacks.splice(index, 1);
  15480. }
  15481. };
  15482. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15483. var scene = this.getScene();
  15484. this._batchCache.mustReturn = false;
  15485. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15486. this._batchCache.visibleInstances[subMeshId] = null;
  15487. if (this._visibleInstances) {
  15488. var currentRenderId = scene.getRenderId();
  15489. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15490. var selfRenderId = this._renderId;
  15491. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15492. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15493. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15494. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15495. }
  15496. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15497. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15498. this._batchCache.mustReturn = true;
  15499. return this._batchCache;
  15500. }
  15501. if (currentRenderId !== selfRenderId) {
  15502. this._batchCache.renderSelf[subMeshId] = false;
  15503. }
  15504. }
  15505. this._renderIdForInstances[subMeshId] = currentRenderId;
  15506. }
  15507. return this._batchCache;
  15508. };
  15509. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15510. var visibleInstances = batch.visibleInstances[subMesh._id];
  15511. var matricesCount = visibleInstances.length + 1;
  15512. var bufferSize = matricesCount * 16 * 4;
  15513. while (this._instancesBufferSize < bufferSize) {
  15514. this._instancesBufferSize *= 2;
  15515. }
  15516. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15517. if (this._worldMatricesInstancesBuffer) {
  15518. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15519. }
  15520. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15521. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15522. }
  15523. var offset = 0;
  15524. var instancesCount = 0;
  15525. var world = this.getWorldMatrix();
  15526. if (batch.renderSelf[subMesh._id]) {
  15527. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15528. offset += 16;
  15529. instancesCount++;
  15530. }
  15531. if (visibleInstances) {
  15532. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15533. var instance = visibleInstances[instanceIndex];
  15534. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15535. offset += 16;
  15536. instancesCount++;
  15537. }
  15538. }
  15539. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15540. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15541. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15542. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15543. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15544. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15545. this._draw(subMesh, fillMode, instancesCount);
  15546. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15547. };
  15548. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15549. var scene = this.getScene();
  15550. var engine = scene.getEngine();
  15551. if (hardwareInstancedRendering) {
  15552. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15553. }
  15554. else {
  15555. if (batch.renderSelf[subMesh._id]) {
  15556. // Draw
  15557. if (onBeforeDraw) {
  15558. onBeforeDraw(false, this.getWorldMatrix());
  15559. }
  15560. this._draw(subMesh, fillMode);
  15561. }
  15562. if (batch.visibleInstances[subMesh._id]) {
  15563. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15564. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15565. // World
  15566. var world = instance.getWorldMatrix();
  15567. if (onBeforeDraw) {
  15568. onBeforeDraw(true, world);
  15569. }
  15570. // Draw
  15571. this._draw(subMesh, fillMode);
  15572. }
  15573. }
  15574. }
  15575. };
  15576. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15577. var scene = this.getScene();
  15578. // Managing instances
  15579. var batch = this._getInstancesRenderList(subMesh._id);
  15580. if (batch.mustReturn) {
  15581. return;
  15582. }
  15583. // Checking geometry state
  15584. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15585. return;
  15586. }
  15587. var callbackIndex;
  15588. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15589. this._onBeforeRenderCallbacks[callbackIndex](this);
  15590. }
  15591. var engine = scene.getEngine();
  15592. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15593. // Material
  15594. var effectiveMaterial = subMesh.getMaterial();
  15595. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15596. return;
  15597. }
  15598. // Outline - step 1
  15599. var savedDepthWrite = engine.getDepthWrite();
  15600. if (this.renderOutline) {
  15601. engine.setDepthWrite(false);
  15602. scene.getOutlineRenderer().render(subMesh, batch);
  15603. engine.setDepthWrite(savedDepthWrite);
  15604. }
  15605. effectiveMaterial._preBind();
  15606. var effect = effectiveMaterial.getEffect();
  15607. // Bind
  15608. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15609. this._bind(subMesh, effect, fillMode);
  15610. var world = this.getWorldMatrix();
  15611. effectiveMaterial.bind(world, this);
  15612. // Alpha mode
  15613. if (enableAlphaMode) {
  15614. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15615. }
  15616. // Draw
  15617. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15618. if (isInstance) {
  15619. effectiveMaterial.bindOnlyWorldMatrix(world);
  15620. }
  15621. });
  15622. // Unbind
  15623. effectiveMaterial.unbind();
  15624. // Outline - step 2
  15625. if (this.renderOutline && savedDepthWrite) {
  15626. engine.setDepthWrite(true);
  15627. engine.setColorWrite(false);
  15628. scene.getOutlineRenderer().render(subMesh, batch);
  15629. engine.setColorWrite(true);
  15630. }
  15631. // Overlay
  15632. if (this.renderOverlay) {
  15633. var currentMode = engine.getAlphaMode();
  15634. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15635. scene.getOutlineRenderer().render(subMesh, batch, true);
  15636. engine.setAlphaMode(currentMode);
  15637. }
  15638. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15639. this._onAfterRenderCallbacks[callbackIndex](this);
  15640. }
  15641. };
  15642. Mesh.prototype.getEmittedParticleSystems = function () {
  15643. var results = new Array();
  15644. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15645. var particleSystem = this.getScene().particleSystems[index];
  15646. if (particleSystem.emitter === this) {
  15647. results.push(particleSystem);
  15648. }
  15649. }
  15650. return results;
  15651. };
  15652. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15653. var results = new Array();
  15654. var descendants = this.getDescendants();
  15655. descendants.push(this);
  15656. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15657. var particleSystem = this.getScene().particleSystems[index];
  15658. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15659. results.push(particleSystem);
  15660. }
  15661. }
  15662. return results;
  15663. };
  15664. Mesh.prototype.getChildren = function () {
  15665. var results = [];
  15666. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15667. var mesh = this.getScene().meshes[index];
  15668. if (mesh.parent === this) {
  15669. results.push(mesh);
  15670. }
  15671. }
  15672. return results;
  15673. };
  15674. Mesh.prototype._checkDelayState = function () {
  15675. var _this = this;
  15676. var that = this;
  15677. var scene = this.getScene();
  15678. if (this._geometry) {
  15679. this._geometry.load(scene);
  15680. }
  15681. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15682. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15683. scene._addPendingData(that);
  15684. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15685. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15686. if (data instanceof ArrayBuffer) {
  15687. _this._delayLoadingFunction(data, _this);
  15688. }
  15689. else {
  15690. _this._delayLoadingFunction(JSON.parse(data), _this);
  15691. }
  15692. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15693. scene._removePendingData(_this);
  15694. }, function () { }, scene.database, getBinaryData);
  15695. }
  15696. };
  15697. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15698. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15699. return false;
  15700. }
  15701. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15702. return false;
  15703. }
  15704. this._checkDelayState();
  15705. return true;
  15706. };
  15707. Mesh.prototype.setMaterialByID = function (id) {
  15708. var materials = this.getScene().materials;
  15709. var index;
  15710. for (index = 0; index < materials.length; index++) {
  15711. if (materials[index].id === id) {
  15712. this.material = materials[index];
  15713. return;
  15714. }
  15715. }
  15716. // Multi
  15717. var multiMaterials = this.getScene().multiMaterials;
  15718. for (index = 0; index < multiMaterials.length; index++) {
  15719. if (multiMaterials[index].id === id) {
  15720. this.material = multiMaterials[index];
  15721. return;
  15722. }
  15723. }
  15724. };
  15725. Mesh.prototype.getAnimatables = function () {
  15726. var results = [];
  15727. if (this.material) {
  15728. results.push(this.material);
  15729. }
  15730. if (this.skeleton) {
  15731. results.push(this.skeleton);
  15732. }
  15733. return results;
  15734. };
  15735. // Geometry
  15736. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15737. // Position
  15738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15739. return;
  15740. }
  15741. this._resetPointsArrayCache();
  15742. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15743. var temp = [];
  15744. var index;
  15745. for (index = 0; index < data.length; index += 3) {
  15746. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15747. }
  15748. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15749. // Normals
  15750. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15751. return;
  15752. }
  15753. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15754. temp = [];
  15755. for (index = 0; index < data.length; index += 3) {
  15756. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15757. }
  15758. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15759. // flip faces?
  15760. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15761. this.flipFaces();
  15762. }
  15763. };
  15764. // Will apply current transform to mesh and reset world matrix
  15765. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15766. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15767. this.scaling.copyFromFloats(1, 1, 1);
  15768. this.position.copyFromFloats(0, 0, 0);
  15769. this.rotation.copyFromFloats(0, 0, 0);
  15770. //only if quaternion is already set
  15771. if (this.rotationQuaternion) {
  15772. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15773. }
  15774. this._worldMatrix = BABYLON.Matrix.Identity();
  15775. };
  15776. // Cache
  15777. Mesh.prototype._resetPointsArrayCache = function () {
  15778. this._positions = null;
  15779. };
  15780. Mesh.prototype._generatePointsArray = function () {
  15781. if (this._positions)
  15782. return true;
  15783. this._positions = [];
  15784. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15785. if (!data) {
  15786. return false;
  15787. }
  15788. for (var index = 0; index < data.length; index += 3) {
  15789. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15790. }
  15791. return true;
  15792. };
  15793. // Clone
  15794. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15795. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15796. };
  15797. // Dispose
  15798. Mesh.prototype.dispose = function (doNotRecurse) {
  15799. if (this._geometry) {
  15800. this._geometry.releaseForMesh(this, true);
  15801. }
  15802. // Instances
  15803. if (this._worldMatricesInstancesBuffer) {
  15804. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15805. this._worldMatricesInstancesBuffer = null;
  15806. }
  15807. while (this.instances.length) {
  15808. this.instances[0].dispose();
  15809. }
  15810. _super.prototype.dispose.call(this, doNotRecurse);
  15811. };
  15812. // Geometric tools
  15813. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15814. var _this = this;
  15815. var scene = this.getScene();
  15816. var onload = function (img) {
  15817. // Getting height map data
  15818. var canvas = document.createElement("canvas");
  15819. var context = canvas.getContext("2d");
  15820. var heightMapWidth = img.width;
  15821. var heightMapHeight = img.height;
  15822. canvas.width = heightMapWidth;
  15823. canvas.height = heightMapHeight;
  15824. context.drawImage(img, 0, 0);
  15825. // Create VertexData from map data
  15826. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15827. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15828. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15829. //execute success callback, if set
  15830. if (onSuccess) {
  15831. onSuccess(_this);
  15832. }
  15833. };
  15834. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15835. };
  15836. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15837. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15838. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15839. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15840. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15841. return;
  15842. }
  15843. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15844. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15845. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15846. var position = BABYLON.Vector3.Zero();
  15847. var normal = BABYLON.Vector3.Zero();
  15848. var uv = BABYLON.Vector2.Zero();
  15849. for (var index = 0; index < positions.length; index += 3) {
  15850. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15851. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15852. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15853. // Compute height
  15854. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15855. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15856. var pos = (u + v * heightMapWidth) * 4;
  15857. var r = buffer[pos] / 255.0;
  15858. var g = buffer[pos + 1] / 255.0;
  15859. var b = buffer[pos + 2] / 255.0;
  15860. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15861. normal.normalize();
  15862. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15863. position = position.add(normal);
  15864. position.toArray(positions, index);
  15865. }
  15866. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15867. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15868. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15869. };
  15870. Mesh.prototype.convertToFlatShadedMesh = function () {
  15871. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15872. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15873. var kinds = this.getVerticesDataKinds();
  15874. var vbs = [];
  15875. var data = [];
  15876. var newdata = [];
  15877. var updatableNormals = false;
  15878. var kindIndex;
  15879. var kind;
  15880. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15881. kind = kinds[kindIndex];
  15882. var vertexBuffer = this.getVertexBuffer(kind);
  15883. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15884. updatableNormals = vertexBuffer.isUpdatable();
  15885. kinds.splice(kindIndex, 1);
  15886. kindIndex--;
  15887. continue;
  15888. }
  15889. vbs[kind] = vertexBuffer;
  15890. data[kind] = vbs[kind].getData();
  15891. newdata[kind] = [];
  15892. }
  15893. // Save previous submeshes
  15894. var previousSubmeshes = this.subMeshes.slice(0);
  15895. var indices = this.getIndices();
  15896. var totalIndices = this.getTotalIndices();
  15897. // Generating unique vertices per face
  15898. var index;
  15899. for (index = 0; index < totalIndices; index++) {
  15900. var vertexIndex = indices[index];
  15901. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15902. kind = kinds[kindIndex];
  15903. var stride = vbs[kind].getStrideSize();
  15904. for (var offset = 0; offset < stride; offset++) {
  15905. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15906. }
  15907. }
  15908. }
  15909. // Updating faces & normal
  15910. var normals = [];
  15911. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15912. for (index = 0; index < totalIndices; index += 3) {
  15913. indices[index] = index;
  15914. indices[index + 1] = index + 1;
  15915. indices[index + 2] = index + 2;
  15916. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15917. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15918. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15919. var p1p2 = p1.subtract(p2);
  15920. var p3p2 = p3.subtract(p2);
  15921. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15922. // Store same normals for every vertex
  15923. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15924. normals.push(normal.x);
  15925. normals.push(normal.y);
  15926. normals.push(normal.z);
  15927. }
  15928. }
  15929. this.setIndices(indices);
  15930. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15931. // Updating vertex buffers
  15932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15933. kind = kinds[kindIndex];
  15934. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15935. }
  15936. // Updating submeshes
  15937. this.releaseSubMeshes();
  15938. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15939. var previousOne = previousSubmeshes[submeshIndex];
  15940. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15941. }
  15942. this.synchronizeInstances();
  15943. };
  15944. Mesh.prototype.convertToUnIndexedMesh = function () {
  15945. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15946. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15947. var kinds = this.getVerticesDataKinds();
  15948. var vbs = [];
  15949. var data = [];
  15950. var newdata = [];
  15951. var updatableNormals = false;
  15952. var kindIndex;
  15953. var kind;
  15954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15955. kind = kinds[kindIndex];
  15956. var vertexBuffer = this.getVertexBuffer(kind);
  15957. vbs[kind] = vertexBuffer;
  15958. data[kind] = vbs[kind].getData();
  15959. newdata[kind] = [];
  15960. }
  15961. // Save previous submeshes
  15962. var previousSubmeshes = this.subMeshes.slice(0);
  15963. var indices = this.getIndices();
  15964. var totalIndices = this.getTotalIndices();
  15965. // Generating unique vertices per face
  15966. var index;
  15967. for (index = 0; index < totalIndices; index++) {
  15968. var vertexIndex = indices[index];
  15969. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15970. kind = kinds[kindIndex];
  15971. var stride = vbs[kind].getStrideSize();
  15972. for (var offset = 0; offset < stride; offset++) {
  15973. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15974. }
  15975. }
  15976. }
  15977. // Updating indices
  15978. for (index = 0; index < totalIndices; index += 3) {
  15979. indices[index] = index;
  15980. indices[index + 1] = index + 1;
  15981. indices[index + 2] = index + 2;
  15982. }
  15983. this.setIndices(indices);
  15984. // Updating vertex buffers
  15985. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15986. kind = kinds[kindIndex];
  15987. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15988. }
  15989. // Updating submeshes
  15990. this.releaseSubMeshes();
  15991. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15992. var previousOne = previousSubmeshes[submeshIndex];
  15993. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15994. }
  15995. this._unIndexed = true;
  15996. this.synchronizeInstances();
  15997. };
  15998. // will inverse faces orientations, and invert normals too if specified
  15999. Mesh.prototype.flipFaces = function (flipNormals) {
  16000. if (flipNormals === void 0) { flipNormals = false; }
  16001. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16002. var i;
  16003. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16004. for (i = 0; i < vertex_data.normals.length; i++) {
  16005. vertex_data.normals[i] *= -1;
  16006. }
  16007. }
  16008. var temp;
  16009. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16010. // reassign indices
  16011. temp = vertex_data.indices[i + 1];
  16012. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16013. vertex_data.indices[i + 2] = temp;
  16014. }
  16015. vertex_data.applyToMesh(this);
  16016. };
  16017. // Instances
  16018. Mesh.prototype.createInstance = function (name) {
  16019. return new BABYLON.InstancedMesh(name, this);
  16020. };
  16021. Mesh.prototype.synchronizeInstances = function () {
  16022. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16023. var instance = this.instances[instanceIndex];
  16024. instance._syncSubMeshes();
  16025. }
  16026. };
  16027. /**
  16028. * Simplify the mesh according to the given array of settings.
  16029. * Function will return immediately and will simplify async.
  16030. * @param settings a collection of simplification settings.
  16031. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16032. * @param type the type of simplification to run.
  16033. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16034. */
  16035. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16036. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16037. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16038. this.getScene().simplificationQueue.addTask({
  16039. settings: settings,
  16040. parallelProcessing: parallelProcessing,
  16041. mesh: this,
  16042. simplificationType: simplificationType,
  16043. successCallback: successCallback
  16044. });
  16045. };
  16046. /**
  16047. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16048. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16049. * This should be used together with the simplification to avoid disappearing triangles.
  16050. * @param successCallback an optional success callback to be called after the optimization finished.
  16051. */
  16052. Mesh.prototype.optimizeIndices = function (successCallback) {
  16053. var _this = this;
  16054. var indices = this.getIndices();
  16055. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16056. var vectorPositions = [];
  16057. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16058. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16059. }
  16060. var dupes = [];
  16061. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16062. var realPos = vectorPositions.length - 1 - iteration;
  16063. var testedPosition = vectorPositions[realPos];
  16064. for (var j = 0; j < realPos; ++j) {
  16065. var againstPosition = vectorPositions[j];
  16066. if (testedPosition.equals(againstPosition)) {
  16067. dupes[realPos] = j;
  16068. break;
  16069. }
  16070. }
  16071. }, function () {
  16072. for (var i = 0; i < indices.length; ++i) {
  16073. indices[i] = dupes[indices[i]] || indices[i];
  16074. }
  16075. //indices are now reordered
  16076. var originalSubMeshes = _this.subMeshes.slice(0);
  16077. _this.setIndices(indices);
  16078. _this.subMeshes = originalSubMeshes;
  16079. if (successCallback) {
  16080. successCallback(_this);
  16081. }
  16082. });
  16083. };
  16084. // Statics
  16085. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16086. var mesh = new Mesh(parsedMesh.name, scene);
  16087. mesh.id = parsedMesh.id;
  16088. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16089. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16090. if (parsedMesh.rotationQuaternion) {
  16091. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16092. }
  16093. else if (parsedMesh.rotation) {
  16094. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16095. }
  16096. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16097. if (parsedMesh.localMatrix) {
  16098. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16099. }
  16100. else if (parsedMesh.pivotMatrix) {
  16101. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16102. }
  16103. mesh.setEnabled(parsedMesh.isEnabled);
  16104. mesh.isVisible = parsedMesh.isVisible;
  16105. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16106. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16107. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16108. if (parsedMesh.applyFog !== undefined) {
  16109. mesh.applyFog = parsedMesh.applyFog;
  16110. }
  16111. if (parsedMesh.pickable !== undefined) {
  16112. mesh.isPickable = parsedMesh.pickable;
  16113. }
  16114. if (parsedMesh.alphaIndex !== undefined) {
  16115. mesh.alphaIndex = parsedMesh.alphaIndex;
  16116. }
  16117. mesh.receiveShadows = parsedMesh.receiveShadows;
  16118. mesh.billboardMode = parsedMesh.billboardMode;
  16119. if (parsedMesh.visibility !== undefined) {
  16120. mesh.visibility = parsedMesh.visibility;
  16121. }
  16122. mesh.checkCollisions = parsedMesh.checkCollisions;
  16123. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16124. // freezeWorldMatrix
  16125. if (parsedMesh.freezeWorldMatrix) {
  16126. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16127. }
  16128. // Parent
  16129. if (parsedMesh.parentId) {
  16130. mesh._waitingParentId = parsedMesh.parentId;
  16131. }
  16132. // Actions
  16133. if (parsedMesh.actions !== undefined) {
  16134. mesh._waitingActions = parsedMesh.actions;
  16135. }
  16136. // Geometry
  16137. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16138. if (parsedMesh.delayLoadingFile) {
  16139. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16140. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16141. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16142. if (parsedMesh._binaryInfo) {
  16143. mesh._binaryInfo = parsedMesh._binaryInfo;
  16144. }
  16145. mesh._delayInfo = [];
  16146. if (parsedMesh.hasUVs) {
  16147. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16148. }
  16149. if (parsedMesh.hasUVs2) {
  16150. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16151. }
  16152. if (parsedMesh.hasUVs3) {
  16153. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16154. }
  16155. if (parsedMesh.hasUVs4) {
  16156. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16157. }
  16158. if (parsedMesh.hasUVs5) {
  16159. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16160. }
  16161. if (parsedMesh.hasUVs6) {
  16162. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16163. }
  16164. if (parsedMesh.hasColors) {
  16165. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16166. }
  16167. if (parsedMesh.hasMatricesIndices) {
  16168. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16169. }
  16170. if (parsedMesh.hasMatricesWeights) {
  16171. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16172. }
  16173. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16174. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16175. mesh._checkDelayState();
  16176. }
  16177. }
  16178. else {
  16179. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16180. }
  16181. // Material
  16182. if (parsedMesh.materialId) {
  16183. mesh.setMaterialByID(parsedMesh.materialId);
  16184. }
  16185. else {
  16186. mesh.material = null;
  16187. }
  16188. // Skeleton
  16189. if (parsedMesh.skeletonId > -1) {
  16190. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16191. if (parsedMesh.numBoneInfluencers) {
  16192. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16193. }
  16194. }
  16195. // Physics
  16196. if (parsedMesh.physicsImpostor) {
  16197. if (!scene.isPhysicsEnabled()) {
  16198. scene.enablePhysics();
  16199. }
  16200. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16201. }
  16202. // Animations
  16203. if (parsedMesh.animations) {
  16204. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16205. var parsedAnimation = parsedMesh.animations[animationIndex];
  16206. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16207. }
  16208. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16209. }
  16210. if (parsedMesh.autoAnimate) {
  16211. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16212. }
  16213. // Layer Mask
  16214. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16215. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16216. }
  16217. else {
  16218. mesh.layerMask = 0x0FFFFFFF;
  16219. }
  16220. // Instances
  16221. if (parsedMesh.instances) {
  16222. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16223. var parsedInstance = parsedMesh.instances[index];
  16224. var instance = mesh.createInstance(parsedInstance.name);
  16225. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16226. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16227. if (parsedInstance.rotationQuaternion) {
  16228. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16229. }
  16230. else if (parsedInstance.rotation) {
  16231. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16232. }
  16233. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16234. instance.checkCollisions = mesh.checkCollisions;
  16235. if (parsedMesh.animations) {
  16236. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16237. parsedAnimation = parsedMesh.animations[animationIndex];
  16238. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16239. }
  16240. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16241. }
  16242. }
  16243. }
  16244. return mesh;
  16245. };
  16246. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16247. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16248. pathArray: pathArray,
  16249. closeArray: closeArray,
  16250. closePath: closePath,
  16251. offset: offset,
  16252. updatable: updatable,
  16253. sideOrientation: sideOrientation,
  16254. instance: instance
  16255. }, scene);
  16256. };
  16257. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16258. var options = {
  16259. radius: radius,
  16260. tessellation: tessellation,
  16261. sideOrientation: sideOrientation,
  16262. updatable: updatable
  16263. };
  16264. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16265. };
  16266. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16267. var options = {
  16268. size: size,
  16269. sideOrientation: sideOrientation,
  16270. updatable: updatable
  16271. };
  16272. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16273. };
  16274. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16275. var options = {
  16276. segments: segments,
  16277. diameterX: diameter,
  16278. diameterY: diameter,
  16279. diameterZ: diameter,
  16280. sideOrientation: sideOrientation,
  16281. updatable: updatable
  16282. };
  16283. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16284. };
  16285. // Cylinder and cone
  16286. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16287. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16288. if (scene !== undefined) {
  16289. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16290. updatable = scene;
  16291. }
  16292. scene = subdivisions;
  16293. subdivisions = 1;
  16294. }
  16295. var options = {
  16296. height: height,
  16297. diameterTop: diameterTop,
  16298. diameterBottom: diameterBottom,
  16299. tessellation: tessellation,
  16300. subdivisions: subdivisions,
  16301. sideOrientation: sideOrientation,
  16302. updatable: updatable
  16303. };
  16304. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16305. };
  16306. // Torus (Code from SharpDX.org)
  16307. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16308. var options = {
  16309. diameter: diameter,
  16310. thickness: thickness,
  16311. tessellation: tessellation,
  16312. sideOrientation: sideOrientation,
  16313. updatable: updatable
  16314. };
  16315. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16316. };
  16317. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16318. var options = {
  16319. radius: radius,
  16320. tube: tube,
  16321. radialSegments: radialSegments,
  16322. tubularSegments: tubularSegments,
  16323. p: p,
  16324. q: q,
  16325. sideOrientation: sideOrientation,
  16326. updatable: updatable
  16327. };
  16328. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16329. };
  16330. // Lines
  16331. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16332. var options = {
  16333. points: points,
  16334. updatable: updatable,
  16335. instance: instance
  16336. };
  16337. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16338. };
  16339. // Dashed Lines
  16340. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16341. var options = {
  16342. points: points,
  16343. dashSize: dashSize,
  16344. gapSize: gapSize,
  16345. dashNb: dashNb,
  16346. updatable: updatable
  16347. };
  16348. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16349. };
  16350. // Extrusion
  16351. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16352. var options = {
  16353. shape: shape,
  16354. path: path,
  16355. scale: scale,
  16356. rotation: rotation,
  16357. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16358. sideOrientation: sideOrientation,
  16359. instance: instance,
  16360. updatable: updatable
  16361. };
  16362. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16363. };
  16364. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16365. var options = {
  16366. shape: shape,
  16367. path: path,
  16368. scaleFunction: scaleFunction,
  16369. rotationFunction: rotationFunction,
  16370. ribbonCloseArray: ribbonCloseArray,
  16371. ribbonClosePath: ribbonClosePath,
  16372. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16373. sideOrientation: sideOrientation,
  16374. instance: instance,
  16375. updatable: updatable
  16376. };
  16377. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16378. };
  16379. // Lathe
  16380. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16381. var options = {
  16382. shape: shape,
  16383. radius: radius,
  16384. tessellation: tessellation,
  16385. sideOrientation: sideOrientation,
  16386. updatable: updatable
  16387. };
  16388. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16389. };
  16390. // Plane & ground
  16391. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16392. var options = {
  16393. size: size,
  16394. width: size,
  16395. height: size,
  16396. sideOrientation: sideOrientation,
  16397. updatable: updatable
  16398. };
  16399. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16400. };
  16401. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16402. var options = {
  16403. width: width,
  16404. height: height,
  16405. subdivisions: subdivisions,
  16406. updatable: updatable
  16407. };
  16408. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16409. };
  16410. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16411. var options = {
  16412. xmin: xmin,
  16413. zmin: zmin,
  16414. xmax: xmax,
  16415. zmax: zmax,
  16416. subdivisions: subdivisions,
  16417. precision: precision,
  16418. updatable: updatable
  16419. };
  16420. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16421. };
  16422. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16423. var options = {
  16424. width: width,
  16425. height: height,
  16426. subdivisions: subdivisions,
  16427. minHeight: minHeight,
  16428. maxHeight: maxHeight,
  16429. updatable: updatable,
  16430. onReady: onReady
  16431. };
  16432. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16433. };
  16434. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16435. var options = {
  16436. path: path,
  16437. radius: radius,
  16438. tessellation: tessellation,
  16439. radiusFunction: radiusFunction,
  16440. arc: 1,
  16441. cap: cap,
  16442. updatable: updatable,
  16443. sideOrientation: sideOrientation,
  16444. instance: instance
  16445. };
  16446. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16447. };
  16448. Mesh.CreatePolyhedron = function (name, options, scene) {
  16449. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16450. };
  16451. Mesh.CreateIcoSphere = function (name, options, scene) {
  16452. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16453. };
  16454. // Decals
  16455. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16456. var options = {
  16457. position: position,
  16458. normal: normal,
  16459. size: size,
  16460. angle: angle
  16461. };
  16462. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16463. };
  16464. // Skeletons
  16465. /**
  16466. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16467. */
  16468. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16469. var source;
  16470. if (!this._sourcePositions) {
  16471. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16472. this._sourcePositions = new Float32Array(source);
  16473. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16474. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16475. }
  16476. }
  16477. return this._sourcePositions;
  16478. };
  16479. /**
  16480. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16481. */
  16482. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16483. var source;
  16484. if (!this._sourceNormals) {
  16485. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16486. this._sourceNormals = new Float32Array(source);
  16487. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16488. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16489. }
  16490. }
  16491. return this._sourceNormals;
  16492. };
  16493. /**
  16494. * Update the vertex buffers by applying transformation from the bones
  16495. * @param {skeleton} skeleton to apply
  16496. */
  16497. Mesh.prototype.applySkeleton = function (skeleton) {
  16498. if (!this.geometry) {
  16499. return;
  16500. }
  16501. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16502. return;
  16503. }
  16504. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16505. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16506. return this;
  16507. }
  16508. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16509. return this;
  16510. }
  16511. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16512. return this;
  16513. }
  16514. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16515. return this;
  16516. }
  16517. if (!this._sourcePositions) {
  16518. this.setPositionsForCPUSkinning();
  16519. }
  16520. if (!this._sourceNormals) {
  16521. this.setNormalsForCPUSkinning();
  16522. }
  16523. // positionsData checks for not being Float32Array will only pass at most once
  16524. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16525. if (!(positionsData instanceof Float32Array)) {
  16526. positionsData = new Float32Array(positionsData);
  16527. }
  16528. // normalsData checks for not being Float32Array will only pass at most once
  16529. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16530. if (!(normalsData instanceof Float32Array)) {
  16531. normalsData = new Float32Array(normalsData);
  16532. }
  16533. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16534. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16535. var needExtras = this.numBoneInfluencers > 4;
  16536. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16537. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16538. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16539. var tempVector3 = BABYLON.Vector3.Zero();
  16540. var finalMatrix = new BABYLON.Matrix();
  16541. var tempMatrix = new BABYLON.Matrix();
  16542. var matWeightIdx = 0;
  16543. var inf;
  16544. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16545. var weight;
  16546. for (inf = 0; inf < 4; inf++) {
  16547. weight = matricesWeightsData[matWeightIdx + inf];
  16548. if (weight > 0) {
  16549. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16550. finalMatrix.addToSelf(tempMatrix);
  16551. }
  16552. else
  16553. break;
  16554. }
  16555. if (needExtras) {
  16556. for (inf = 0; inf < 4; inf++) {
  16557. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16558. if (weight > 0) {
  16559. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16560. finalMatrix.addToSelf(tempMatrix);
  16561. }
  16562. else
  16563. break;
  16564. }
  16565. }
  16566. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16567. tempVector3.toArray(positionsData, index);
  16568. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16569. tempVector3.toArray(normalsData, index);
  16570. finalMatrix.reset();
  16571. }
  16572. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16573. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16574. return this;
  16575. };
  16576. // Tools
  16577. Mesh.MinMax = function (meshes) {
  16578. var minVector = null;
  16579. var maxVector = null;
  16580. for (var i in meshes) {
  16581. var mesh = meshes[i];
  16582. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16583. if (!minVector) {
  16584. minVector = boundingBox.minimumWorld;
  16585. maxVector = boundingBox.maximumWorld;
  16586. continue;
  16587. }
  16588. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16589. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16590. }
  16591. return {
  16592. min: minVector,
  16593. max: maxVector
  16594. };
  16595. };
  16596. Mesh.Center = function (meshesOrMinMaxVector) {
  16597. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16599. };
  16600. /**
  16601. * Merge the array of meshes into a single mesh for performance reasons.
  16602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16606. */
  16607. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16608. if (disposeSource === void 0) { disposeSource = true; }
  16609. var index;
  16610. if (!allow32BitsIndices) {
  16611. var totalVertices = 0;
  16612. // Counting vertices
  16613. for (index = 0; index < meshes.length; index++) {
  16614. if (meshes[index]) {
  16615. totalVertices += meshes[index].getTotalVertices();
  16616. if (totalVertices > 65536) {
  16617. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16618. return null;
  16619. }
  16620. }
  16621. }
  16622. }
  16623. // Merge
  16624. var vertexData;
  16625. var otherVertexData;
  16626. var source;
  16627. for (index = 0; index < meshes.length; index++) {
  16628. if (meshes[index]) {
  16629. meshes[index].computeWorldMatrix(true);
  16630. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16631. otherVertexData.transform(meshes[index].getWorldMatrix());
  16632. if (vertexData) {
  16633. vertexData.merge(otherVertexData);
  16634. }
  16635. else {
  16636. vertexData = otherVertexData;
  16637. source = meshes[index];
  16638. }
  16639. }
  16640. }
  16641. if (!meshSubclass) {
  16642. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16643. }
  16644. vertexData.applyToMesh(meshSubclass);
  16645. // Setting properties
  16646. meshSubclass.material = source.material;
  16647. meshSubclass.checkCollisions = source.checkCollisions;
  16648. // Cleaning
  16649. if (disposeSource) {
  16650. for (index = 0; index < meshes.length; index++) {
  16651. if (meshes[index]) {
  16652. meshes[index].dispose();
  16653. }
  16654. }
  16655. }
  16656. return meshSubclass;
  16657. };
  16658. // Consts
  16659. Mesh._FRONTSIDE = 0;
  16660. Mesh._BACKSIDE = 1;
  16661. Mesh._DOUBLESIDE = 2;
  16662. Mesh._DEFAULTSIDE = 0;
  16663. Mesh._NO_CAP = 0;
  16664. Mesh._CAP_START = 1;
  16665. Mesh._CAP_END = 2;
  16666. Mesh._CAP_ALL = 3;
  16667. return Mesh;
  16668. })(BABYLON.AbstractMesh);
  16669. BABYLON.Mesh = Mesh;
  16670. })(BABYLON || (BABYLON = {}));
  16671. var BABYLON;
  16672. (function (BABYLON) {
  16673. var SubMesh = (function () {
  16674. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16675. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16676. this.materialIndex = materialIndex;
  16677. this.verticesStart = verticesStart;
  16678. this.verticesCount = verticesCount;
  16679. this.indexStart = indexStart;
  16680. this.indexCount = indexCount;
  16681. this._renderId = 0;
  16682. this._mesh = mesh;
  16683. this._renderingMesh = renderingMesh || mesh;
  16684. mesh.subMeshes.push(this);
  16685. this._trianglePlanes = [];
  16686. this._id = mesh.subMeshes.length - 1;
  16687. if (createBoundingBox) {
  16688. this.refreshBoundingInfo();
  16689. mesh.computeWorldMatrix(true);
  16690. }
  16691. }
  16692. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16693. get: function () {
  16694. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16695. },
  16696. enumerable: true,
  16697. configurable: true
  16698. });
  16699. SubMesh.prototype.getBoundingInfo = function () {
  16700. if (this.IsGlobal) {
  16701. return this._mesh.getBoundingInfo();
  16702. }
  16703. return this._boundingInfo;
  16704. };
  16705. SubMesh.prototype.getMesh = function () {
  16706. return this._mesh;
  16707. };
  16708. SubMesh.prototype.getRenderingMesh = function () {
  16709. return this._renderingMesh;
  16710. };
  16711. SubMesh.prototype.getMaterial = function () {
  16712. var rootMaterial = this._renderingMesh.material;
  16713. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16714. var multiMaterial = rootMaterial;
  16715. return multiMaterial.getSubMaterial(this.materialIndex);
  16716. }
  16717. if (!rootMaterial) {
  16718. return this._mesh.getScene().defaultMaterial;
  16719. }
  16720. return rootMaterial;
  16721. };
  16722. // Methods
  16723. SubMesh.prototype.refreshBoundingInfo = function () {
  16724. this._lastColliderWorldVertices = null;
  16725. if (this.IsGlobal) {
  16726. return;
  16727. }
  16728. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16729. if (!data) {
  16730. this._boundingInfo = this._mesh._boundingInfo;
  16731. return;
  16732. }
  16733. var indices = this._renderingMesh.getIndices();
  16734. var extend;
  16735. //is this the only submesh?
  16736. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16737. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16738. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16739. }
  16740. else {
  16741. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16742. }
  16743. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16744. };
  16745. SubMesh.prototype._checkCollision = function (collider) {
  16746. return this.getBoundingInfo()._checkCollision(collider);
  16747. };
  16748. SubMesh.prototype.updateBoundingInfo = function (world) {
  16749. if (!this.getBoundingInfo()) {
  16750. this.refreshBoundingInfo();
  16751. }
  16752. this.getBoundingInfo().update(world);
  16753. };
  16754. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16755. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16756. };
  16757. SubMesh.prototype.render = function (enableAlphaMode) {
  16758. this._renderingMesh.render(this, enableAlphaMode);
  16759. };
  16760. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16761. if (!this._linesIndexBuffer) {
  16762. var linesIndices = [];
  16763. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16764. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16765. }
  16766. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16767. this.linesIndexCount = linesIndices.length;
  16768. }
  16769. return this._linesIndexBuffer;
  16770. };
  16771. SubMesh.prototype.canIntersects = function (ray) {
  16772. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16773. };
  16774. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16775. var intersectInfo = null;
  16776. // Triangles test
  16777. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16778. var p0 = positions[indices[index]];
  16779. var p1 = positions[indices[index + 1]];
  16780. var p2 = positions[indices[index + 2]];
  16781. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16782. if (currentIntersectInfo) {
  16783. if (currentIntersectInfo.distance < 0) {
  16784. continue;
  16785. }
  16786. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16787. intersectInfo = currentIntersectInfo;
  16788. intersectInfo.faceId = index / 3;
  16789. if (fastCheck) {
  16790. break;
  16791. }
  16792. }
  16793. }
  16794. }
  16795. return intersectInfo;
  16796. };
  16797. // Clone
  16798. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16799. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16800. if (!this.IsGlobal) {
  16801. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16802. }
  16803. return result;
  16804. };
  16805. // Dispose
  16806. SubMesh.prototype.dispose = function () {
  16807. if (this._linesIndexBuffer) {
  16808. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16809. this._linesIndexBuffer = null;
  16810. }
  16811. // Remove from mesh
  16812. var index = this._mesh.subMeshes.indexOf(this);
  16813. this._mesh.subMeshes.splice(index, 1);
  16814. };
  16815. // Statics
  16816. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16817. var minVertexIndex = Number.MAX_VALUE;
  16818. var maxVertexIndex = -Number.MAX_VALUE;
  16819. renderingMesh = renderingMesh || mesh;
  16820. var indices = renderingMesh.getIndices();
  16821. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16822. var vertexIndex = indices[index];
  16823. if (vertexIndex < minVertexIndex)
  16824. minVertexIndex = vertexIndex;
  16825. if (vertexIndex > maxVertexIndex)
  16826. maxVertexIndex = vertexIndex;
  16827. }
  16828. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16829. };
  16830. return SubMesh;
  16831. })();
  16832. BABYLON.SubMesh = SubMesh;
  16833. })(BABYLON || (BABYLON = {}));
  16834. var BABYLON;
  16835. (function (BABYLON) {
  16836. var MeshBuilder = (function () {
  16837. function MeshBuilder() {
  16838. }
  16839. MeshBuilder.CreateBox = function (name, options, scene) {
  16840. var box = new BABYLON.Mesh(name, scene);
  16841. var vertexData = BABYLON.VertexData.CreateBox(options);
  16842. vertexData.applyToMesh(box, options.updatable);
  16843. return box;
  16844. };
  16845. MeshBuilder.CreateSphere = function (name, options, scene) {
  16846. var sphere = new BABYLON.Mesh(name, scene);
  16847. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16848. vertexData.applyToMesh(sphere, options.updatable);
  16849. return sphere;
  16850. };
  16851. MeshBuilder.CreateDisc = function (name, options, scene) {
  16852. var disc = new BABYLON.Mesh(name, scene);
  16853. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16854. vertexData.applyToMesh(disc, options.updatable);
  16855. return disc;
  16856. };
  16857. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16858. var sphere = new BABYLON.Mesh(name, scene);
  16859. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16860. vertexData.applyToMesh(sphere, options.updatable);
  16861. return sphere;
  16862. };
  16863. ;
  16864. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16865. var pathArray = options.pathArray;
  16866. var closeArray = options.closeArray;
  16867. var closePath = options.closePath;
  16868. var offset = options.offset;
  16869. var sideOrientation = options.sideOrientation;
  16870. var instance = options.instance;
  16871. var updatable = options.updatable;
  16872. if (instance) {
  16873. // positionFunction : ribbon case
  16874. // only pathArray and sideOrientation parameters are taken into account for positions update
  16875. var positionFunction = function (positions) {
  16876. var minlg = pathArray[0].length;
  16877. var i = 0;
  16878. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16879. for (var si = 1; si <= ns; si++) {
  16880. for (var p = 0; p < pathArray.length; p++) {
  16881. var path = pathArray[p];
  16882. var l = path.length;
  16883. minlg = (minlg < l) ? minlg : l;
  16884. var j = 0;
  16885. while (j < minlg) {
  16886. positions[i] = path[j].x;
  16887. positions[i + 1] = path[j].y;
  16888. positions[i + 2] = path[j].z;
  16889. j++;
  16890. i += 3;
  16891. }
  16892. if (instance._closePath) {
  16893. positions[i] = path[0].x;
  16894. positions[i + 1] = path[0].y;
  16895. positions[i + 2] = path[0].z;
  16896. i += 3;
  16897. }
  16898. }
  16899. }
  16900. };
  16901. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16902. positionFunction(positions);
  16903. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16904. if (!(instance.areNormalsFrozen)) {
  16905. var indices = instance.getIndices();
  16906. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16907. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16908. if (instance._closePath) {
  16909. var indexFirst = 0;
  16910. var indexLast = 0;
  16911. for (var p = 0; p < pathArray.length; p++) {
  16912. indexFirst = instance._idx[p] * 3;
  16913. if (p + 1 < pathArray.length) {
  16914. indexLast = (instance._idx[p + 1] - 1) * 3;
  16915. }
  16916. else {
  16917. indexLast = normals.length - 3;
  16918. }
  16919. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16920. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16921. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16922. normals[indexLast] = normals[indexFirst];
  16923. normals[indexLast + 1] = normals[indexFirst + 1];
  16924. normals[indexLast + 2] = normals[indexFirst + 2];
  16925. }
  16926. }
  16927. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16928. }
  16929. return instance;
  16930. }
  16931. else {
  16932. var ribbon = new BABYLON.Mesh(name, scene);
  16933. ribbon.sideOrientation = sideOrientation;
  16934. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16935. if (closePath) {
  16936. ribbon._idx = vertexData._idx;
  16937. }
  16938. ribbon._closePath = closePath;
  16939. ribbon._closeArray = closeArray;
  16940. vertexData.applyToMesh(ribbon, updatable);
  16941. return ribbon;
  16942. }
  16943. };
  16944. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16945. var cylinder = new BABYLON.Mesh(name, scene);
  16946. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16947. vertexData.applyToMesh(cylinder, options.updatable);
  16948. return cylinder;
  16949. };
  16950. MeshBuilder.CreateTorus = function (name, options, scene) {
  16951. var torus = new BABYLON.Mesh(name, scene);
  16952. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16953. vertexData.applyToMesh(torus, options.updatable);
  16954. return torus;
  16955. };
  16956. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16957. var torusKnot = new BABYLON.Mesh(name, scene);
  16958. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16959. vertexData.applyToMesh(torusKnot, options.updatable);
  16960. return torusKnot;
  16961. };
  16962. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  16963. var instance = options.instance;
  16964. var lines = options.lines;
  16965. if (instance) {
  16966. var positionFunction = function (positions) {
  16967. var i = 0;
  16968. for (var l = 0; l < lines.length; l++) {
  16969. var points = lines[l];
  16970. for (var p = 0; p < points.length; p++) {
  16971. positions[i] = points[p].x;
  16972. positions[i + 1] = points[p].y;
  16973. positions[i + 2] = points[p].z;
  16974. i += 3;
  16975. }
  16976. }
  16977. };
  16978. instance.updateMeshPositions(positionFunction, false);
  16979. return instance;
  16980. }
  16981. // line system creation
  16982. var lineSystem = new BABYLON.LinesMesh(name, scene);
  16983. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  16984. vertexData.applyToMesh(lineSystem, options.updatable);
  16985. return lineSystem;
  16986. };
  16987. MeshBuilder.CreateLines = function (name, options, scene) {
  16988. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  16989. return lines;
  16990. };
  16991. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16992. var points = options.points;
  16993. var instance = options.instance;
  16994. var gapSize = options.gapSize;
  16995. var dashNb = options.dashNb;
  16996. var dashSize = options.dashSize;
  16997. if (instance) {
  16998. var positionFunction = function (positions) {
  16999. var curvect = BABYLON.Vector3.Zero();
  17000. var nbSeg = positions.length / 6;
  17001. var lg = 0;
  17002. var nb = 0;
  17003. var shft = 0;
  17004. var dashshft = 0;
  17005. var curshft = 0;
  17006. var p = 0;
  17007. var i = 0;
  17008. var j = 0;
  17009. for (i = 0; i < points.length - 1; i++) {
  17010. points[i + 1].subtractToRef(points[i], curvect);
  17011. lg += curvect.length();
  17012. }
  17013. shft = lg / nbSeg;
  17014. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17015. for (i = 0; i < points.length - 1; i++) {
  17016. points[i + 1].subtractToRef(points[i], curvect);
  17017. nb = Math.floor(curvect.length() / shft);
  17018. curvect.normalize();
  17019. j = 0;
  17020. while (j < nb && p < positions.length) {
  17021. curshft = shft * j;
  17022. positions[p] = points[i].x + curshft * curvect.x;
  17023. positions[p + 1] = points[i].y + curshft * curvect.y;
  17024. positions[p + 2] = points[i].z + curshft * curvect.z;
  17025. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17026. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17027. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17028. p += 6;
  17029. j++;
  17030. }
  17031. }
  17032. while (p < positions.length) {
  17033. positions[p] = points[i].x;
  17034. positions[p + 1] = points[i].y;
  17035. positions[p + 2] = points[i].z;
  17036. p += 3;
  17037. }
  17038. };
  17039. instance.updateMeshPositions(positionFunction, false);
  17040. return instance;
  17041. }
  17042. // dashed lines creation
  17043. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17044. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17045. vertexData.applyToMesh(dashedLines, options.updatable);
  17046. dashedLines.dashSize = dashSize;
  17047. dashedLines.gapSize = gapSize;
  17048. return dashedLines;
  17049. };
  17050. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17051. var path = options.path;
  17052. var shape = options.shape;
  17053. var scale = options.scale || 1;
  17054. var rotation = options.rotation || 0;
  17055. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17056. var updatable = options.updatable;
  17057. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17058. var instance = options.instance;
  17059. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17060. };
  17061. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17062. var path = options.path;
  17063. var shape = options.shape;
  17064. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17065. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17066. var ribbonCloseArray = options.ribbonCloseArray || false;
  17067. var ribbonClosePath = options.ribbonClosePath || false;
  17068. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17069. var updatable = options.updatable;
  17070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17071. var instance = options.instance;
  17072. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17073. };
  17074. MeshBuilder.CreateLathe = function (name, options, scene) {
  17075. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17076. var closed = (options.closed === undefined) ? true : options.closed;
  17077. var shape = options.shape;
  17078. var radius = options.radius || 1;
  17079. var tessellation = options.tessellation || 64;
  17080. var updatable = options.updatable;
  17081. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17082. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17083. var pi2 = Math.PI * 2;
  17084. var paths = new Array();
  17085. var i = 0;
  17086. var p = 0;
  17087. var step = pi2 / tessellation * arc;
  17088. var rotated;
  17089. var path = new Array();
  17090. ;
  17091. for (i = 0; i <= tessellation; i++) {
  17092. var path = [];
  17093. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17094. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17095. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17096. }
  17097. for (p = 0; p < shape.length; p++) {
  17098. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17099. path.push(rotated);
  17100. }
  17101. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17102. 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));
  17103. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17104. }
  17105. paths.push(path);
  17106. }
  17107. // lathe ribbon
  17108. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17109. return lathe;
  17110. };
  17111. MeshBuilder.CreatePlane = function (name, options, scene) {
  17112. var plane = new BABYLON.Mesh(name, scene);
  17113. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17114. vertexData.applyToMesh(plane, options.updatable);
  17115. if (options.sourcePlane) {
  17116. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17117. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17118. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17119. plane.rotate(vectorProduct, product);
  17120. }
  17121. return plane;
  17122. };
  17123. MeshBuilder.CreateGround = function (name, options, scene) {
  17124. var ground = new BABYLON.GroundMesh(name, scene);
  17125. ground._setReady(false);
  17126. ground._subdivisions = options.subdivisions || 1;
  17127. ground._width = options.width || 1;
  17128. ground._height = options.height || 1;
  17129. ground._maxX = ground._width / 2;
  17130. ground._maxZ = ground._height / 2;
  17131. ground._minX = -ground._maxX;
  17132. ground._minZ = -ground._maxZ;
  17133. var vertexData = BABYLON.VertexData.CreateGround(options);
  17134. vertexData.applyToMesh(ground, options.updatable);
  17135. ground._setReady(true);
  17136. return ground;
  17137. };
  17138. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17139. var tiledGround = new BABYLON.Mesh(name, scene);
  17140. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17141. vertexData.applyToMesh(tiledGround, options.updatable);
  17142. return tiledGround;
  17143. };
  17144. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17145. var width = options.width || 10;
  17146. var height = options.height || 10;
  17147. var subdivisions = options.subdivisions || 1;
  17148. var minHeight = options.minHeight;
  17149. var maxHeight = options.maxHeight || 10;
  17150. var updatable = options.updatable;
  17151. var onReady = options.onReady;
  17152. var ground = new BABYLON.GroundMesh(name, scene);
  17153. ground._subdivisions = subdivisions;
  17154. ground._width = width;
  17155. ground._height = height;
  17156. ground._maxX = ground._width / 2;
  17157. ground._maxZ = ground._height / 2;
  17158. ground._minX = -ground._maxX;
  17159. ground._minZ = -ground._maxZ;
  17160. ground._setReady(false);
  17161. var onload = function (img) {
  17162. // Getting height map data
  17163. var canvas = document.createElement("canvas");
  17164. var context = canvas.getContext("2d");
  17165. var bufferWidth = img.width;
  17166. var bufferHeight = img.height;
  17167. canvas.width = bufferWidth;
  17168. canvas.height = bufferHeight;
  17169. context.drawImage(img, 0, 0);
  17170. // Create VertexData from map data
  17171. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17172. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17173. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17174. width: width, height: height,
  17175. subdivisions: subdivisions,
  17176. minHeight: minHeight, maxHeight: maxHeight,
  17177. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17178. });
  17179. vertexData.applyToMesh(ground, updatable);
  17180. ground._setReady(true);
  17181. //execute ready callback, if set
  17182. if (onReady) {
  17183. onReady(ground);
  17184. }
  17185. };
  17186. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17187. return ground;
  17188. };
  17189. MeshBuilder.CreateTube = function (name, options, scene) {
  17190. var path = options.path;
  17191. var radius = options.radius || 1;
  17192. var tessellation = options.tessellation || 64;
  17193. var radiusFunction = options.radiusFunction;
  17194. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17195. var updatable = options.updatable;
  17196. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17197. var instance = options.instance;
  17198. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17199. // tube geometry
  17200. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17201. var tangents = path3D.getTangents();
  17202. var normals = path3D.getNormals();
  17203. var distances = path3D.getDistances();
  17204. var pi2 = Math.PI * 2;
  17205. var step = pi2 / tessellation * arc;
  17206. var returnRadius = function () { return radius; };
  17207. var radiusFunctionFinal = radiusFunction || returnRadius;
  17208. var circlePath;
  17209. var rad;
  17210. var normal;
  17211. var rotated;
  17212. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17213. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17214. for (var i = 0; i < path.length; i++) {
  17215. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17216. circlePath = Array(); // current circle array
  17217. normal = normals[i]; // current normal
  17218. for (var t = 0; t < tessellation; t++) {
  17219. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17220. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17221. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17222. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17223. circlePath[t] = rotated;
  17224. }
  17225. circlePaths[index] = circlePath;
  17226. index++;
  17227. }
  17228. // cap
  17229. var capPath = function (nbPoints, pathIndex) {
  17230. var pointCap = Array();
  17231. for (var i = 0; i < nbPoints; i++) {
  17232. pointCap.push(path[pathIndex]);
  17233. }
  17234. return pointCap;
  17235. };
  17236. switch (cap) {
  17237. case BABYLON.Mesh.NO_CAP:
  17238. break;
  17239. case BABYLON.Mesh.CAP_START:
  17240. circlePaths[0] = capPath(tessellation, 0);
  17241. circlePaths[1] = circlePaths[2].slice(0);
  17242. break;
  17243. case BABYLON.Mesh.CAP_END:
  17244. circlePaths[index] = circlePaths[index - 1].slice(0);
  17245. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17246. break;
  17247. case BABYLON.Mesh.CAP_ALL:
  17248. circlePaths[0] = capPath(tessellation, 0);
  17249. circlePaths[1] = circlePaths[2].slice(0);
  17250. circlePaths[index] = circlePaths[index - 1].slice(0);
  17251. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17252. break;
  17253. default:
  17254. break;
  17255. }
  17256. return circlePaths;
  17257. };
  17258. var path3D;
  17259. var pathArray;
  17260. if (instance) {
  17261. var arc = options.arc || instance.arc;
  17262. path3D = (instance.path3D).update(path);
  17263. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17264. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17265. instance.path3D = path3D;
  17266. instance.pathArray = pathArray;
  17267. instance.arc = arc;
  17268. return instance;
  17269. }
  17270. // tube creation
  17271. path3D = new BABYLON.Path3D(path);
  17272. var newPathArray = new Array();
  17273. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17274. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17275. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17276. tube.pathArray = pathArray;
  17277. tube.path3D = path3D;
  17278. tube.tessellation = tessellation;
  17279. tube.cap = cap;
  17280. tube.arc = options.arc;
  17281. return tube;
  17282. };
  17283. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17284. var polyhedron = new BABYLON.Mesh(name, scene);
  17285. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17286. vertexData.applyToMesh(polyhedron, options.updatable);
  17287. return polyhedron;
  17288. };
  17289. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17290. var indices = sourceMesh.getIndices();
  17291. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17292. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17293. var position = options.position || BABYLON.Vector3.Zero();
  17294. var normal = options.normal || BABYLON.Vector3.Up();
  17295. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17296. var angle = options.angle || 0;
  17297. // Getting correct rotation
  17298. if (!normal) {
  17299. var target = new BABYLON.Vector3(0, 0, 1);
  17300. var camera = sourceMesh.getScene().activeCamera;
  17301. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17302. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17303. }
  17304. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17305. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17306. var pitch = Math.atan2(normal.y, len);
  17307. // Matrix
  17308. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17309. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17310. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17311. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17312. var vertexData = new BABYLON.VertexData();
  17313. vertexData.indices = [];
  17314. vertexData.positions = [];
  17315. vertexData.normals = [];
  17316. vertexData.uvs = [];
  17317. var currentVertexDataIndex = 0;
  17318. var extractDecalVector3 = function (indexId) {
  17319. var vertexId = indices[indexId];
  17320. var result = new BABYLON.PositionNormalVertex();
  17321. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17322. // Send vector to decal local world
  17323. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17324. // Get normal
  17325. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17326. return result;
  17327. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17328. var clip = function (vertices, axis) {
  17329. if (vertices.length === 0) {
  17330. return vertices;
  17331. }
  17332. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17333. var clipVertices = function (v0, v1) {
  17334. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17335. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17336. };
  17337. var result = new Array();
  17338. for (var index = 0; index < vertices.length; index += 3) {
  17339. var v1Out;
  17340. var v2Out;
  17341. var v3Out;
  17342. var total = 0;
  17343. var nV1, nV2, nV3, nV4;
  17344. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17345. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17346. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17347. v1Out = d1 > 0;
  17348. v2Out = d2 > 0;
  17349. v3Out = d3 > 0;
  17350. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17351. switch (total) {
  17352. case 0:
  17353. result.push(vertices[index]);
  17354. result.push(vertices[index + 1]);
  17355. result.push(vertices[index + 2]);
  17356. break;
  17357. case 1:
  17358. if (v1Out) {
  17359. nV1 = vertices[index + 1];
  17360. nV2 = vertices[index + 2];
  17361. nV3 = clipVertices(vertices[index], nV1);
  17362. nV4 = clipVertices(vertices[index], nV2);
  17363. }
  17364. if (v2Out) {
  17365. nV1 = vertices[index];
  17366. nV2 = vertices[index + 2];
  17367. nV3 = clipVertices(vertices[index + 1], nV1);
  17368. nV4 = clipVertices(vertices[index + 1], nV2);
  17369. result.push(nV3);
  17370. result.push(nV2.clone());
  17371. result.push(nV1.clone());
  17372. result.push(nV2.clone());
  17373. result.push(nV3.clone());
  17374. result.push(nV4);
  17375. break;
  17376. }
  17377. if (v3Out) {
  17378. nV1 = vertices[index];
  17379. nV2 = vertices[index + 1];
  17380. nV3 = clipVertices(vertices[index + 2], nV1);
  17381. nV4 = clipVertices(vertices[index + 2], nV2);
  17382. }
  17383. result.push(nV1.clone());
  17384. result.push(nV2.clone());
  17385. result.push(nV3);
  17386. result.push(nV4);
  17387. result.push(nV3.clone());
  17388. result.push(nV2.clone());
  17389. break;
  17390. case 2:
  17391. if (!v1Out) {
  17392. nV1 = vertices[index].clone();
  17393. nV2 = clipVertices(nV1, vertices[index + 1]);
  17394. nV3 = clipVertices(nV1, vertices[index + 2]);
  17395. result.push(nV1);
  17396. result.push(nV2);
  17397. result.push(nV3);
  17398. }
  17399. if (!v2Out) {
  17400. nV1 = vertices[index + 1].clone();
  17401. nV2 = clipVertices(nV1, vertices[index + 2]);
  17402. nV3 = clipVertices(nV1, vertices[index]);
  17403. result.push(nV1);
  17404. result.push(nV2);
  17405. result.push(nV3);
  17406. }
  17407. if (!v3Out) {
  17408. nV1 = vertices[index + 2].clone();
  17409. nV2 = clipVertices(nV1, vertices[index]);
  17410. nV3 = clipVertices(nV1, vertices[index + 1]);
  17411. result.push(nV1);
  17412. result.push(nV2);
  17413. result.push(nV3);
  17414. }
  17415. break;
  17416. case 3:
  17417. break;
  17418. }
  17419. }
  17420. return result;
  17421. };
  17422. for (var index = 0; index < indices.length; index += 3) {
  17423. var faceVertices = new Array();
  17424. faceVertices.push(extractDecalVector3(index));
  17425. faceVertices.push(extractDecalVector3(index + 1));
  17426. faceVertices.push(extractDecalVector3(index + 2));
  17427. // Clip
  17428. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17429. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17430. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17431. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17432. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17433. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17434. if (faceVertices.length === 0) {
  17435. continue;
  17436. }
  17437. // Add UVs and get back to world
  17438. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17439. var vertex = faceVertices[vIndex];
  17440. //TODO check for Int32Array
  17441. vertexData.indices.push(currentVertexDataIndex);
  17442. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17443. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17444. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17445. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17446. currentVertexDataIndex++;
  17447. }
  17448. }
  17449. // Return mesh
  17450. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17451. vertexData.applyToMesh(decal);
  17452. decal.position = position.clone();
  17453. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17454. return decal;
  17455. };
  17456. // Privates
  17457. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17458. // extrusion geometry
  17459. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17460. var tangents = path3D.getTangents();
  17461. var normals = path3D.getNormals();
  17462. var binormals = path3D.getBinormals();
  17463. var distances = path3D.getDistances();
  17464. var angle = 0;
  17465. var returnScale = function () { return scale; };
  17466. var returnRotation = function () { return rotation; };
  17467. var rotate = custom ? rotateFunction : returnRotation;
  17468. var scl = custom ? scaleFunction : returnScale;
  17469. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17470. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17471. for (var i = 0; i < curve.length; i++) {
  17472. var shapePath = new Array();
  17473. var angleStep = rotate(i, distances[i]);
  17474. var scaleRatio = scl(i, distances[i]);
  17475. for (var p = 0; p < shape.length; p++) {
  17476. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17477. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17478. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17479. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17480. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17481. shapePath[p] = rotated;
  17482. }
  17483. shapePaths[index] = shapePath;
  17484. angle += angleStep;
  17485. index++;
  17486. }
  17487. // cap
  17488. var capPath = function (shapePath) {
  17489. var pointCap = Array();
  17490. var barycenter = BABYLON.Vector3.Zero();
  17491. var i;
  17492. for (i = 0; i < shapePath.length; i++) {
  17493. barycenter.addInPlace(shapePath[i]);
  17494. }
  17495. barycenter.scaleInPlace(1 / shapePath.length);
  17496. for (i = 0; i < shapePath.length; i++) {
  17497. pointCap.push(barycenter);
  17498. }
  17499. return pointCap;
  17500. };
  17501. switch (cap) {
  17502. case BABYLON.Mesh.NO_CAP:
  17503. break;
  17504. case BABYLON.Mesh.CAP_START:
  17505. shapePaths[0] = capPath(shapePaths[2]);
  17506. shapePaths[1] = shapePaths[2].slice(0);
  17507. break;
  17508. case BABYLON.Mesh.CAP_END:
  17509. shapePaths[index] = shapePaths[index - 1];
  17510. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17511. break;
  17512. case BABYLON.Mesh.CAP_ALL:
  17513. shapePaths[0] = capPath(shapePaths[2]);
  17514. shapePaths[1] = shapePaths[2].slice(0);
  17515. shapePaths[index] = shapePaths[index - 1];
  17516. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17517. break;
  17518. default:
  17519. break;
  17520. }
  17521. return shapePaths;
  17522. };
  17523. var path3D;
  17524. var pathArray;
  17525. if (instance) {
  17526. path3D = (instance.path3D).update(curve);
  17527. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17528. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17529. return instance;
  17530. }
  17531. // extruded shape creation
  17532. path3D = new BABYLON.Path3D(curve);
  17533. var newShapePaths = new Array();
  17534. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17535. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17536. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17537. extrudedGeneric.pathArray = pathArray;
  17538. extrudedGeneric.path3D = path3D;
  17539. extrudedGeneric.cap = cap;
  17540. return extrudedGeneric;
  17541. };
  17542. return MeshBuilder;
  17543. })();
  17544. BABYLON.MeshBuilder = MeshBuilder;
  17545. })(BABYLON || (BABYLON = {}));
  17546. var BABYLON;
  17547. (function (BABYLON) {
  17548. var BaseTexture = (function () {
  17549. function BaseTexture(scene) {
  17550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17551. this.hasAlpha = false;
  17552. this.getAlphaFromRGB = false;
  17553. this.level = 1;
  17554. this.isCube = false;
  17555. this.isRenderTarget = false;
  17556. this.animations = new Array();
  17557. this.coordinatesIndex = 0;
  17558. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17559. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17560. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17561. this.anisotropicFilteringLevel = 4;
  17562. this._scene = scene;
  17563. this._scene.textures.push(this);
  17564. }
  17565. BaseTexture.prototype.getScene = function () {
  17566. return this._scene;
  17567. };
  17568. BaseTexture.prototype.getTextureMatrix = function () {
  17569. return null;
  17570. };
  17571. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17572. return null;
  17573. };
  17574. BaseTexture.prototype.getInternalTexture = function () {
  17575. return this._texture;
  17576. };
  17577. BaseTexture.prototype.isReady = function () {
  17578. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17579. return true;
  17580. }
  17581. if (this._texture) {
  17582. return this._texture.isReady;
  17583. }
  17584. return false;
  17585. };
  17586. BaseTexture.prototype.getSize = function () {
  17587. if (this._texture._width) {
  17588. return { width: this._texture._width, height: this._texture._height };
  17589. }
  17590. if (this._texture._size) {
  17591. return { width: this._texture._size, height: this._texture._size };
  17592. }
  17593. return { width: 0, height: 0 };
  17594. };
  17595. BaseTexture.prototype.getBaseSize = function () {
  17596. if (!this.isReady())
  17597. return { width: 0, height: 0 };
  17598. if (this._texture._size) {
  17599. return { width: this._texture._size, height: this._texture._size };
  17600. }
  17601. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17602. };
  17603. BaseTexture.prototype.scale = function (ratio) {
  17604. };
  17605. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17606. get: function () {
  17607. return false;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17613. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17614. for (var index = 0; index < texturesCache.length; index++) {
  17615. var texturesCacheEntry = texturesCache[index];
  17616. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17617. texturesCache.splice(index, 1);
  17618. return;
  17619. }
  17620. }
  17621. };
  17622. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17623. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17624. for (var index = 0; index < texturesCache.length; index++) {
  17625. var texturesCacheEntry = texturesCache[index];
  17626. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17627. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17628. texturesCacheEntry.references++;
  17629. return texturesCacheEntry;
  17630. }
  17631. }
  17632. }
  17633. return null;
  17634. };
  17635. BaseTexture.prototype.delayLoad = function () {
  17636. };
  17637. BaseTexture.prototype.clone = function () {
  17638. return null;
  17639. };
  17640. BaseTexture.prototype.releaseInternalTexture = function () {
  17641. if (this._texture) {
  17642. this._scene.getEngine().releaseInternalTexture(this._texture);
  17643. delete this._texture;
  17644. }
  17645. };
  17646. BaseTexture.prototype.dispose = function () {
  17647. // Animations
  17648. this.getScene().stopAnimation(this);
  17649. // Remove from scene
  17650. var index = this._scene.textures.indexOf(this);
  17651. if (index >= 0) {
  17652. this._scene.textures.splice(index, 1);
  17653. }
  17654. if (this._texture === undefined) {
  17655. return;
  17656. }
  17657. // Release
  17658. this.releaseInternalTexture();
  17659. // Callback
  17660. if (this.onDispose) {
  17661. this.onDispose();
  17662. }
  17663. };
  17664. BaseTexture.prototype.serialize = function () {
  17665. var serializationObject = {};
  17666. if (!this.name) {
  17667. return null;
  17668. }
  17669. serializationObject.name = this.name;
  17670. serializationObject.hasAlpha = this.hasAlpha;
  17671. serializationObject.level = this.level;
  17672. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17673. serializationObject.coordinatesMode = this.coordinatesMode;
  17674. serializationObject.wrapU = this.wrapU;
  17675. serializationObject.wrapV = this.wrapV;
  17676. // Animations
  17677. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17678. return serializationObject;
  17679. };
  17680. return BaseTexture;
  17681. })();
  17682. BABYLON.BaseTexture = BaseTexture;
  17683. })(BABYLON || (BABYLON = {}));
  17684. var BABYLON;
  17685. (function (BABYLON) {
  17686. var Texture = (function (_super) {
  17687. __extends(Texture, _super);
  17688. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17689. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17690. if (onLoad === void 0) { onLoad = null; }
  17691. if (onError === void 0) { onError = null; }
  17692. if (buffer === void 0) { buffer = null; }
  17693. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17694. _super.call(this, scene);
  17695. this.uOffset = 0;
  17696. this.vOffset = 0;
  17697. this.uScale = 1.0;
  17698. this.vScale = 1.0;
  17699. this.uAng = 0;
  17700. this.vAng = 0;
  17701. this.wAng = 0;
  17702. this.name = url;
  17703. this.url = url;
  17704. this._noMipmap = noMipmap;
  17705. this._invertY = invertY;
  17706. this._samplingMode = samplingMode;
  17707. this._buffer = buffer;
  17708. this._deleteBuffer = deleteBuffer;
  17709. if (!url) {
  17710. return;
  17711. }
  17712. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17713. if (!this._texture) {
  17714. if (!scene.useDelayedTextureLoading) {
  17715. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17716. if (deleteBuffer) {
  17717. delete this._buffer;
  17718. }
  17719. }
  17720. else {
  17721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17722. this._delayedOnLoad = onLoad;
  17723. this._delayedOnError = onError;
  17724. }
  17725. }
  17726. else {
  17727. BABYLON.Tools.SetImmediate(function () {
  17728. if (onLoad) {
  17729. onLoad();
  17730. }
  17731. });
  17732. }
  17733. }
  17734. Texture.prototype.delayLoad = function () {
  17735. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17736. return;
  17737. }
  17738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17739. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17740. if (!this._texture) {
  17741. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17742. if (this._deleteBuffer) {
  17743. delete this._buffer;
  17744. }
  17745. }
  17746. };
  17747. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17748. if (!this._texture) {
  17749. return;
  17750. }
  17751. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17752. };
  17753. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17754. x *= this.uScale;
  17755. y *= this.vScale;
  17756. x -= 0.5 * this.uScale;
  17757. y -= 0.5 * this.vScale;
  17758. z -= 0.5;
  17759. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17760. t.x += 0.5 * this.uScale + this.uOffset;
  17761. t.y += 0.5 * this.vScale + this.vOffset;
  17762. t.z += 0.5;
  17763. };
  17764. Texture.prototype.getTextureMatrix = function () {
  17765. if (this.uOffset === this._cachedUOffset &&
  17766. this.vOffset === this._cachedVOffset &&
  17767. this.uScale === this._cachedUScale &&
  17768. this.vScale === this._cachedVScale &&
  17769. this.uAng === this._cachedUAng &&
  17770. this.vAng === this._cachedVAng &&
  17771. this.wAng === this._cachedWAng) {
  17772. return this._cachedTextureMatrix;
  17773. }
  17774. this._cachedUOffset = this.uOffset;
  17775. this._cachedVOffset = this.vOffset;
  17776. this._cachedUScale = this.uScale;
  17777. this._cachedVScale = this.vScale;
  17778. this._cachedUAng = this.uAng;
  17779. this._cachedVAng = this.vAng;
  17780. this._cachedWAng = this.wAng;
  17781. if (!this._cachedTextureMatrix) {
  17782. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17783. this._rowGenerationMatrix = new BABYLON.Matrix();
  17784. this._t0 = BABYLON.Vector3.Zero();
  17785. this._t1 = BABYLON.Vector3.Zero();
  17786. this._t2 = BABYLON.Vector3.Zero();
  17787. }
  17788. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17789. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17790. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17791. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17792. this._t1.subtractInPlace(this._t0);
  17793. this._t2.subtractInPlace(this._t0);
  17794. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17795. this._cachedTextureMatrix.m[0] = this._t1.x;
  17796. this._cachedTextureMatrix.m[1] = this._t1.y;
  17797. this._cachedTextureMatrix.m[2] = this._t1.z;
  17798. this._cachedTextureMatrix.m[4] = this._t2.x;
  17799. this._cachedTextureMatrix.m[5] = this._t2.y;
  17800. this._cachedTextureMatrix.m[6] = this._t2.z;
  17801. this._cachedTextureMatrix.m[8] = this._t0.x;
  17802. this._cachedTextureMatrix.m[9] = this._t0.y;
  17803. this._cachedTextureMatrix.m[10] = this._t0.z;
  17804. return this._cachedTextureMatrix;
  17805. };
  17806. Texture.prototype.getReflectionTextureMatrix = function () {
  17807. if (this.uOffset === this._cachedUOffset &&
  17808. this.vOffset === this._cachedVOffset &&
  17809. this.uScale === this._cachedUScale &&
  17810. this.vScale === this._cachedVScale &&
  17811. this.coordinatesMode === this._cachedCoordinatesMode) {
  17812. return this._cachedTextureMatrix;
  17813. }
  17814. if (!this._cachedTextureMatrix) {
  17815. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17816. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17817. }
  17818. this._cachedCoordinatesMode = this.coordinatesMode;
  17819. switch (this.coordinatesMode) {
  17820. case Texture.PLANAR_MODE:
  17821. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17822. this._cachedTextureMatrix[0] = this.uScale;
  17823. this._cachedTextureMatrix[5] = this.vScale;
  17824. this._cachedTextureMatrix[12] = this.uOffset;
  17825. this._cachedTextureMatrix[13] = this.vOffset;
  17826. break;
  17827. case Texture.PROJECTION_MODE:
  17828. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17829. this._projectionModeMatrix.m[0] = 0.5;
  17830. this._projectionModeMatrix.m[5] = -0.5;
  17831. this._projectionModeMatrix.m[10] = 0.0;
  17832. this._projectionModeMatrix.m[12] = 0.5;
  17833. this._projectionModeMatrix.m[13] = 0.5;
  17834. this._projectionModeMatrix.m[14] = 1.0;
  17835. this._projectionModeMatrix.m[15] = 1.0;
  17836. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17837. break;
  17838. default:
  17839. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17840. break;
  17841. }
  17842. return this._cachedTextureMatrix;
  17843. };
  17844. Texture.prototype.clone = function () {
  17845. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17846. // Base texture
  17847. newTexture.hasAlpha = this.hasAlpha;
  17848. newTexture.level = this.level;
  17849. newTexture.wrapU = this.wrapU;
  17850. newTexture.wrapV = this.wrapV;
  17851. newTexture.coordinatesIndex = this.coordinatesIndex;
  17852. newTexture.coordinatesMode = this.coordinatesMode;
  17853. // Texture
  17854. newTexture.uOffset = this.uOffset;
  17855. newTexture.vOffset = this.vOffset;
  17856. newTexture.uScale = this.uScale;
  17857. newTexture.vScale = this.vScale;
  17858. newTexture.uAng = this.uAng;
  17859. newTexture.vAng = this.vAng;
  17860. newTexture.wAng = this.wAng;
  17861. return newTexture;
  17862. };
  17863. Texture.prototype.serialize = function () {
  17864. if (!this.name) {
  17865. return null;
  17866. }
  17867. var serializationObject = _super.prototype.serialize.call(this);
  17868. serializationObject.uOffset = this.uOffset;
  17869. serializationObject.vOffset = this.vOffset;
  17870. serializationObject.uScale = this.uScale;
  17871. serializationObject.vScale = this.vScale;
  17872. serializationObject.uAng = this.uAng;
  17873. serializationObject.vAng = this.vAng;
  17874. serializationObject.wAng = this.wAng;
  17875. return serializationObject;
  17876. };
  17877. // Statics
  17878. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17879. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17880. if (onLoad === void 0) { onLoad = null; }
  17881. if (onError === void 0) { onError = null; }
  17882. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17883. };
  17884. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17885. if (parsedTexture.isCube) {
  17886. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17887. }
  17888. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17889. return null;
  17890. }
  17891. var texture;
  17892. if (parsedTexture.mirrorPlane) {
  17893. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17894. texture._waitingRenderList = parsedTexture.renderList;
  17895. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17896. }
  17897. else if (parsedTexture.isRenderTarget) {
  17898. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17899. texture._waitingRenderList = parsedTexture.renderList;
  17900. }
  17901. else {
  17902. if (parsedTexture.base64String) {
  17903. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17904. }
  17905. else {
  17906. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17907. }
  17908. }
  17909. texture.name = parsedTexture.name;
  17910. texture.hasAlpha = parsedTexture.hasAlpha;
  17911. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17912. texture.level = parsedTexture.level;
  17913. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17914. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17915. texture.uOffset = parsedTexture.uOffset;
  17916. texture.vOffset = parsedTexture.vOffset;
  17917. texture.uScale = parsedTexture.uScale;
  17918. texture.vScale = parsedTexture.vScale;
  17919. texture.uAng = parsedTexture.uAng;
  17920. texture.vAng = parsedTexture.vAng;
  17921. texture.wAng = parsedTexture.wAng;
  17922. texture.wrapU = parsedTexture.wrapU;
  17923. texture.wrapV = parsedTexture.wrapV;
  17924. // Animations
  17925. if (parsedTexture.animations) {
  17926. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17927. var parsedAnimation = parsedTexture.animations[animationIndex];
  17928. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17929. }
  17930. }
  17931. return texture;
  17932. };
  17933. // Constants
  17934. Texture.NEAREST_SAMPLINGMODE = 1;
  17935. Texture.BILINEAR_SAMPLINGMODE = 2;
  17936. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17937. Texture.EXPLICIT_MODE = 0;
  17938. Texture.SPHERICAL_MODE = 1;
  17939. Texture.PLANAR_MODE = 2;
  17940. Texture.CUBIC_MODE = 3;
  17941. Texture.PROJECTION_MODE = 4;
  17942. Texture.SKYBOX_MODE = 5;
  17943. Texture.INVCUBIC_MODE = 6;
  17944. Texture.EQUIRECTANGULAR_MODE = 7;
  17945. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17946. Texture.CLAMP_ADDRESSMODE = 0;
  17947. Texture.WRAP_ADDRESSMODE = 1;
  17948. Texture.MIRROR_ADDRESSMODE = 2;
  17949. return Texture;
  17950. })(BABYLON.BaseTexture);
  17951. BABYLON.Texture = Texture;
  17952. })(BABYLON || (BABYLON = {}));
  17953. var BABYLON;
  17954. (function (BABYLON) {
  17955. var CubeTexture = (function (_super) {
  17956. __extends(CubeTexture, _super);
  17957. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17958. _super.call(this, scene);
  17959. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17960. this.name = rootUrl;
  17961. this.url = rootUrl;
  17962. this._noMipmap = noMipmap;
  17963. this.hasAlpha = false;
  17964. if (!rootUrl && !files) {
  17965. return;
  17966. }
  17967. this._texture = this._getFromCache(rootUrl, noMipmap);
  17968. if (!files) {
  17969. if (!extensions) {
  17970. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17971. }
  17972. files = [];
  17973. for (var index = 0; index < extensions.length; index++) {
  17974. files.push(rootUrl + extensions[index]);
  17975. }
  17976. this._extensions = extensions;
  17977. }
  17978. this._files = files;
  17979. if (!this._texture) {
  17980. if (!scene.useDelayedTextureLoading) {
  17981. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17982. }
  17983. else {
  17984. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17985. }
  17986. }
  17987. this.isCube = true;
  17988. this._textureMatrix = BABYLON.Matrix.Identity();
  17989. }
  17990. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17991. return new CubeTexture("", scene, null, noMipmap, files);
  17992. };
  17993. CubeTexture.prototype.clone = function () {
  17994. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17995. // Base texture
  17996. newTexture.level = this.level;
  17997. newTexture.wrapU = this.wrapU;
  17998. newTexture.wrapV = this.wrapV;
  17999. newTexture.coordinatesIndex = this.coordinatesIndex;
  18000. newTexture.coordinatesMode = this.coordinatesMode;
  18001. return newTexture;
  18002. };
  18003. // Methods
  18004. CubeTexture.prototype.delayLoad = function () {
  18005. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18006. return;
  18007. }
  18008. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18009. this._texture = this._getFromCache(this.url, this._noMipmap);
  18010. if (!this._texture) {
  18011. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18012. }
  18013. };
  18014. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18015. return this._textureMatrix;
  18016. };
  18017. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18018. var texture = null;
  18019. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18020. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18021. texture.name = parsedTexture.name;
  18022. texture.hasAlpha = parsedTexture.hasAlpha;
  18023. texture.level = parsedTexture.level;
  18024. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18025. }
  18026. return texture;
  18027. };
  18028. CubeTexture.prototype.serialize = function () {
  18029. if (!this.name) {
  18030. return null;
  18031. }
  18032. var serializationObject = {};
  18033. serializationObject.name = this.name;
  18034. serializationObject.hasAlpha = this.hasAlpha;
  18035. serializationObject.isCube = true;
  18036. serializationObject.level = this.level;
  18037. serializationObject.coordinatesMode = this.coordinatesMode;
  18038. return serializationObject;
  18039. };
  18040. return CubeTexture;
  18041. })(BABYLON.BaseTexture);
  18042. BABYLON.CubeTexture = CubeTexture;
  18043. })(BABYLON || (BABYLON = {}));
  18044. var BABYLON;
  18045. (function (BABYLON) {
  18046. var RenderTargetTexture = (function (_super) {
  18047. __extends(RenderTargetTexture, _super);
  18048. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18049. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18050. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18051. if (isCube === void 0) { isCube = false; }
  18052. _super.call(this, null, scene, !generateMipMaps);
  18053. this.isCube = isCube;
  18054. this.renderList = new Array();
  18055. this.renderParticles = true;
  18056. this.renderSprites = false;
  18057. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18058. this._currentRefreshId = -1;
  18059. this._refreshRate = 1;
  18060. this.name = name;
  18061. this.isRenderTarget = true;
  18062. this._size = size;
  18063. this._generateMipMaps = generateMipMaps;
  18064. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18065. if (isCube) {
  18066. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18067. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18068. this._textureMatrix = BABYLON.Matrix.Identity();
  18069. }
  18070. else {
  18071. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18072. }
  18073. // Rendering groups
  18074. this._renderingManager = new BABYLON.RenderingManager(scene);
  18075. }
  18076. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18077. get: function () {
  18078. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18079. },
  18080. enumerable: true,
  18081. configurable: true
  18082. });
  18083. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18084. get: function () {
  18085. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18091. get: function () {
  18092. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18093. },
  18094. enumerable: true,
  18095. configurable: true
  18096. });
  18097. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18098. this._currentRefreshId = -1;
  18099. };
  18100. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18101. get: function () {
  18102. return this._refreshRate;
  18103. },
  18104. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18105. set: function (value) {
  18106. this._refreshRate = value;
  18107. this.resetRefreshCounter();
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. RenderTargetTexture.prototype._shouldRender = function () {
  18113. if (this._currentRefreshId === -1) {
  18114. this._currentRefreshId = 1;
  18115. return true;
  18116. }
  18117. if (this.refreshRate === this._currentRefreshId) {
  18118. this._currentRefreshId = 1;
  18119. return true;
  18120. }
  18121. this._currentRefreshId++;
  18122. return false;
  18123. };
  18124. RenderTargetTexture.prototype.isReady = function () {
  18125. if (!this.getScene().renderTargetsEnabled) {
  18126. return false;
  18127. }
  18128. return _super.prototype.isReady.call(this);
  18129. };
  18130. RenderTargetTexture.prototype.getRenderSize = function () {
  18131. return this._size;
  18132. };
  18133. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18134. get: function () {
  18135. return true;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. RenderTargetTexture.prototype.scale = function (ratio) {
  18141. var newSize = this._size * ratio;
  18142. this.resize(newSize, this._generateMipMaps);
  18143. };
  18144. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18145. if (this.isCube) {
  18146. return this._textureMatrix;
  18147. }
  18148. return _super.prototype.getReflectionTextureMatrix.call(this);
  18149. };
  18150. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18151. this.releaseInternalTexture();
  18152. if (this.isCube) {
  18153. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18154. }
  18155. else {
  18156. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18157. }
  18158. };
  18159. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18160. var scene = this.getScene();
  18161. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18162. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18163. }
  18164. if (this._waitingRenderList) {
  18165. this.renderList = [];
  18166. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18167. var id = this._waitingRenderList[index];
  18168. this.renderList.push(scene.getMeshByID(id));
  18169. }
  18170. delete this._waitingRenderList;
  18171. }
  18172. if (this.renderList && this.renderList.length === 0) {
  18173. return;
  18174. }
  18175. // Prepare renderingManager
  18176. this._renderingManager.reset();
  18177. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18178. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18179. var mesh = currentRenderList[meshIndex];
  18180. if (mesh) {
  18181. if (!mesh.isReady()) {
  18182. // Reset _currentRefreshId
  18183. this.resetRefreshCounter();
  18184. continue;
  18185. }
  18186. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18187. mesh._activate(scene.getRenderId());
  18188. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18189. var subMesh = mesh.subMeshes[subIndex];
  18190. scene._activeIndices += subMesh.indexCount;
  18191. this._renderingManager.dispatch(subMesh);
  18192. }
  18193. }
  18194. }
  18195. }
  18196. if (this.isCube) {
  18197. for (var face = 0; face < 6; face++) {
  18198. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18199. scene.incrementRenderId();
  18200. }
  18201. }
  18202. else {
  18203. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18204. }
  18205. if (this.onAfterUnbind) {
  18206. this.onAfterUnbind();
  18207. }
  18208. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18209. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18210. }
  18211. scene.resetCachedMaterial();
  18212. };
  18213. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18214. var scene = this.getScene();
  18215. var engine = scene.getEngine();
  18216. // Bind
  18217. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18218. if (this.isCube) {
  18219. engine.bindFramebuffer(this._texture, faceIndex);
  18220. }
  18221. else {
  18222. engine.bindFramebuffer(this._texture);
  18223. }
  18224. }
  18225. if (this.onBeforeRender) {
  18226. this.onBeforeRender(faceIndex);
  18227. }
  18228. // Clear
  18229. if (this.onClear) {
  18230. this.onClear(engine);
  18231. }
  18232. else {
  18233. engine.clear(scene.clearColor, true, true);
  18234. }
  18235. if (!this._doNotChangeAspectRatio) {
  18236. scene.updateTransformMatrix(true);
  18237. }
  18238. // Render
  18239. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18240. if (useCameraPostProcess) {
  18241. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18242. }
  18243. if (!this._doNotChangeAspectRatio) {
  18244. scene.updateTransformMatrix(true);
  18245. }
  18246. if (this.onAfterRender) {
  18247. this.onAfterRender(faceIndex);
  18248. }
  18249. // Dump ?
  18250. if (dumpForDebug) {
  18251. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18252. }
  18253. // Unbind
  18254. if (!this.isCube || faceIndex === 5) {
  18255. if (this.isCube) {
  18256. if (faceIndex === 5) {
  18257. engine.generateMipMapsForCubemap(this._texture);
  18258. }
  18259. }
  18260. engine.unBindFramebuffer(this._texture, this.isCube);
  18261. }
  18262. };
  18263. RenderTargetTexture.prototype.clone = function () {
  18264. var textureSize = this.getSize();
  18265. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18266. // Base texture
  18267. newTexture.hasAlpha = this.hasAlpha;
  18268. newTexture.level = this.level;
  18269. // RenderTarget Texture
  18270. newTexture.coordinatesMode = this.coordinatesMode;
  18271. newTexture.renderList = this.renderList.slice(0);
  18272. return newTexture;
  18273. };
  18274. RenderTargetTexture.prototype.serialize = function () {
  18275. if (!this.name) {
  18276. return null;
  18277. }
  18278. var serializationObject = _super.prototype.serialize.call(this);
  18279. serializationObject.renderTargetSize = this.getRenderSize();
  18280. serializationObject.renderList = [];
  18281. for (var index = 0; index < this.renderList.length; index++) {
  18282. serializationObject.renderList.push(this.renderList[index].id);
  18283. }
  18284. return serializationObject;
  18285. };
  18286. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18287. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18288. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18289. return RenderTargetTexture;
  18290. })(BABYLON.Texture);
  18291. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18292. })(BABYLON || (BABYLON = {}));
  18293. var BABYLON;
  18294. (function (BABYLON) {
  18295. var ProceduralTexture = (function (_super) {
  18296. __extends(ProceduralTexture, _super);
  18297. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18298. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18299. if (isCube === void 0) { isCube = false; }
  18300. _super.call(this, null, scene, !generateMipMaps);
  18301. this.isCube = isCube;
  18302. this.isEnabled = true;
  18303. this._currentRefreshId = -1;
  18304. this._refreshRate = 1;
  18305. this._vertexDeclaration = [2];
  18306. this._vertexStrideSize = 2 * 4;
  18307. this._uniforms = new Array();
  18308. this._samplers = new Array();
  18309. this._textures = new Array();
  18310. this._floats = new Array();
  18311. this._floatsArrays = {};
  18312. this._colors3 = new Array();
  18313. this._colors4 = new Array();
  18314. this._vectors2 = new Array();
  18315. this._vectors3 = new Array();
  18316. this._matrices = new Array();
  18317. this._fallbackTextureUsed = false;
  18318. scene._proceduralTextures.push(this);
  18319. this.name = name;
  18320. this.isRenderTarget = true;
  18321. this._size = size;
  18322. this._generateMipMaps = generateMipMaps;
  18323. this.setFragment(fragment);
  18324. this._fallbackTexture = fallbackTexture;
  18325. if (isCube) {
  18326. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18327. this.setFloat("face", 0);
  18328. }
  18329. else {
  18330. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18331. }
  18332. // VBO
  18333. var vertices = [];
  18334. vertices.push(1, 1);
  18335. vertices.push(-1, 1);
  18336. vertices.push(-1, -1);
  18337. vertices.push(1, -1);
  18338. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18339. // Indices
  18340. var indices = [];
  18341. indices.push(0);
  18342. indices.push(1);
  18343. indices.push(2);
  18344. indices.push(0);
  18345. indices.push(2);
  18346. indices.push(3);
  18347. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18348. }
  18349. ProceduralTexture.prototype.reset = function () {
  18350. if (this._effect === undefined) {
  18351. return;
  18352. }
  18353. var engine = this.getScene().getEngine();
  18354. engine._releaseEffect(this._effect);
  18355. };
  18356. ProceduralTexture.prototype.isReady = function () {
  18357. var _this = this;
  18358. var engine = this.getScene().getEngine();
  18359. var shaders;
  18360. if (!this._fragment) {
  18361. return false;
  18362. }
  18363. if (this._fallbackTextureUsed) {
  18364. return true;
  18365. }
  18366. if (this._fragment.fragmentElement !== undefined) {
  18367. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18368. }
  18369. else {
  18370. shaders = { vertex: "procedural", fragment: this._fragment };
  18371. }
  18372. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18373. _this.releaseInternalTexture();
  18374. if (_this._fallbackTexture) {
  18375. _this._texture = _this._fallbackTexture._texture;
  18376. _this._texture.references++;
  18377. }
  18378. _this._fallbackTextureUsed = true;
  18379. });
  18380. return this._effect.isReady();
  18381. };
  18382. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18383. this._currentRefreshId = -1;
  18384. };
  18385. ProceduralTexture.prototype.setFragment = function (fragment) {
  18386. this._fragment = fragment;
  18387. };
  18388. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18389. get: function () {
  18390. return this._refreshRate;
  18391. },
  18392. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18393. set: function (value) {
  18394. this._refreshRate = value;
  18395. this.resetRefreshCounter();
  18396. },
  18397. enumerable: true,
  18398. configurable: true
  18399. });
  18400. ProceduralTexture.prototype._shouldRender = function () {
  18401. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18402. return false;
  18403. }
  18404. if (this._fallbackTextureUsed) {
  18405. return false;
  18406. }
  18407. if (this._currentRefreshId === -1) {
  18408. this._currentRefreshId = 1;
  18409. return true;
  18410. }
  18411. if (this.refreshRate === this._currentRefreshId) {
  18412. this._currentRefreshId = 1;
  18413. return true;
  18414. }
  18415. this._currentRefreshId++;
  18416. return false;
  18417. };
  18418. ProceduralTexture.prototype.getRenderSize = function () {
  18419. return this._size;
  18420. };
  18421. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18422. if (this._fallbackTextureUsed) {
  18423. return;
  18424. }
  18425. this.releaseInternalTexture();
  18426. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18427. };
  18428. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18429. if (this._uniforms.indexOf(uniformName) === -1) {
  18430. this._uniforms.push(uniformName);
  18431. }
  18432. };
  18433. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18434. if (this._samplers.indexOf(name) === -1) {
  18435. this._samplers.push(name);
  18436. }
  18437. this._textures[name] = texture;
  18438. return this;
  18439. };
  18440. ProceduralTexture.prototype.setFloat = function (name, value) {
  18441. this._checkUniform(name);
  18442. this._floats[name] = value;
  18443. return this;
  18444. };
  18445. ProceduralTexture.prototype.setFloats = function (name, value) {
  18446. this._checkUniform(name);
  18447. this._floatsArrays[name] = value;
  18448. return this;
  18449. };
  18450. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18451. this._checkUniform(name);
  18452. this._colors3[name] = value;
  18453. return this;
  18454. };
  18455. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18456. this._checkUniform(name);
  18457. this._colors4[name] = value;
  18458. return this;
  18459. };
  18460. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18461. this._checkUniform(name);
  18462. this._vectors2[name] = value;
  18463. return this;
  18464. };
  18465. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18466. this._checkUniform(name);
  18467. this._vectors3[name] = value;
  18468. return this;
  18469. };
  18470. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18471. this._checkUniform(name);
  18472. this._matrices[name] = value;
  18473. return this;
  18474. };
  18475. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18476. var scene = this.getScene();
  18477. var engine = scene.getEngine();
  18478. // Render
  18479. engine.enableEffect(this._effect);
  18480. engine.setState(false);
  18481. // Texture
  18482. for (var name in this._textures) {
  18483. this._effect.setTexture(name, this._textures[name]);
  18484. }
  18485. // Float
  18486. for (name in this._floats) {
  18487. this._effect.setFloat(name, this._floats[name]);
  18488. }
  18489. // Floats
  18490. for (name in this._floatsArrays) {
  18491. this._effect.setArray(name, this._floatsArrays[name]);
  18492. }
  18493. // Color3
  18494. for (name in this._colors3) {
  18495. this._effect.setColor3(name, this._colors3[name]);
  18496. }
  18497. // Color4
  18498. for (name in this._colors4) {
  18499. var color = this._colors4[name];
  18500. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18501. }
  18502. // Vector2
  18503. for (name in this._vectors2) {
  18504. this._effect.setVector2(name, this._vectors2[name]);
  18505. }
  18506. // Vector3
  18507. for (name in this._vectors3) {
  18508. this._effect.setVector3(name, this._vectors3[name]);
  18509. }
  18510. // Matrix
  18511. for (name in this._matrices) {
  18512. this._effect.setMatrix(name, this._matrices[name]);
  18513. }
  18514. // VBOs
  18515. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18516. if (this.isCube) {
  18517. for (var face = 0; face < 6; face++) {
  18518. engine.bindFramebuffer(this._texture, face);
  18519. this._effect.setFloat("face", face);
  18520. // Clear
  18521. engine.clear(scene.clearColor, true, true);
  18522. // Draw order
  18523. engine.draw(true, 0, 6);
  18524. // Mipmaps
  18525. if (face === 5) {
  18526. engine.generateMipMapsForCubemap(this._texture);
  18527. }
  18528. }
  18529. }
  18530. else {
  18531. engine.bindFramebuffer(this._texture);
  18532. // Clear
  18533. engine.clear(scene.clearColor, true, true);
  18534. // Draw order
  18535. engine.draw(true, 0, 6);
  18536. }
  18537. // Unbind
  18538. engine.unBindFramebuffer(this._texture, this.isCube);
  18539. if (this.onGenerated) {
  18540. this.onGenerated();
  18541. }
  18542. };
  18543. ProceduralTexture.prototype.clone = function () {
  18544. var textureSize = this.getSize();
  18545. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18546. // Base texture
  18547. newTexture.hasAlpha = this.hasAlpha;
  18548. newTexture.level = this.level;
  18549. // RenderTarget Texture
  18550. newTexture.coordinatesMode = this.coordinatesMode;
  18551. return newTexture;
  18552. };
  18553. ProceduralTexture.prototype.dispose = function () {
  18554. var index = this.getScene()._proceduralTextures.indexOf(this);
  18555. if (index >= 0) {
  18556. this.getScene()._proceduralTextures.splice(index, 1);
  18557. }
  18558. _super.prototype.dispose.call(this);
  18559. };
  18560. return ProceduralTexture;
  18561. })(BABYLON.Texture);
  18562. BABYLON.ProceduralTexture = ProceduralTexture;
  18563. })(BABYLON || (BABYLON = {}));
  18564. var BABYLON;
  18565. (function (BABYLON) {
  18566. var MirrorTexture = (function (_super) {
  18567. __extends(MirrorTexture, _super);
  18568. function MirrorTexture(name, size, scene, generateMipMaps) {
  18569. var _this = this;
  18570. _super.call(this, name, size, scene, generateMipMaps, true);
  18571. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18572. this._transformMatrix = BABYLON.Matrix.Zero();
  18573. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18574. this.onBeforeRender = function () {
  18575. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18576. _this._savedViewMatrix = scene.getViewMatrix();
  18577. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18578. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18579. scene.clipPlane = _this.mirrorPlane;
  18580. scene.getEngine().cullBackFaces = false;
  18581. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18582. };
  18583. this.onAfterRender = function () {
  18584. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18585. scene.getEngine().cullBackFaces = true;
  18586. scene._mirroredCameraPosition = null;
  18587. delete scene.clipPlane;
  18588. };
  18589. }
  18590. MirrorTexture.prototype.clone = function () {
  18591. var textureSize = this.getSize();
  18592. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18593. // Base texture
  18594. newTexture.hasAlpha = this.hasAlpha;
  18595. newTexture.level = this.level;
  18596. // Mirror Texture
  18597. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18598. newTexture.renderList = this.renderList.slice(0);
  18599. return newTexture;
  18600. };
  18601. MirrorTexture.prototype.serialize = function () {
  18602. if (!this.name) {
  18603. return null;
  18604. }
  18605. var serializationObject = _super.prototype.serialize.call(this);
  18606. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18607. return serializationObject;
  18608. };
  18609. return MirrorTexture;
  18610. })(BABYLON.RenderTargetTexture);
  18611. BABYLON.MirrorTexture = MirrorTexture;
  18612. })(BABYLON || (BABYLON = {}));
  18613. var BABYLON;
  18614. (function (BABYLON) {
  18615. /**
  18616. * Creates a refraction texture used by refraction channel of the standard material.
  18617. * @param name the texture name
  18618. * @param size size of the underlying texture
  18619. * @param scene root scene
  18620. */
  18621. var RefractionTexture = (function (_super) {
  18622. __extends(RefractionTexture, _super);
  18623. function RefractionTexture(name, size, scene, generateMipMaps) {
  18624. var _this = this;
  18625. _super.call(this, name, size, scene, generateMipMaps, true);
  18626. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18627. this.depth = 2.0;
  18628. this.onBeforeRender = function () {
  18629. scene.clipPlane = _this.refractionPlane;
  18630. };
  18631. this.onAfterRender = function () {
  18632. delete scene.clipPlane;
  18633. };
  18634. }
  18635. RefractionTexture.prototype.clone = function () {
  18636. var textureSize = this.getSize();
  18637. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18638. // Base texture
  18639. newTexture.hasAlpha = this.hasAlpha;
  18640. newTexture.level = this.level;
  18641. // Refraction Texture
  18642. newTexture.refractionPlane = this.refractionPlane.clone();
  18643. newTexture.renderList = this.renderList.slice(0);
  18644. newTexture.depth = this.depth;
  18645. return newTexture;
  18646. };
  18647. RefractionTexture.prototype.serialize = function () {
  18648. if (!this.name) {
  18649. return null;
  18650. }
  18651. var serializationObject = _super.prototype.serialize.call(this);
  18652. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18653. serializationObject.depth = this.depth;
  18654. return serializationObject;
  18655. };
  18656. return RefractionTexture;
  18657. })(BABYLON.RenderTargetTexture);
  18658. BABYLON.RefractionTexture = RefractionTexture;
  18659. })(BABYLON || (BABYLON = {}));
  18660. var BABYLON;
  18661. (function (BABYLON) {
  18662. var DynamicTexture = (function (_super) {
  18663. __extends(DynamicTexture, _super);
  18664. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18666. _super.call(this, null, scene, !generateMipMaps);
  18667. this.name = name;
  18668. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18669. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18670. this._generateMipMaps = generateMipMaps;
  18671. if (options.getContext) {
  18672. this._canvas = options;
  18673. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18674. }
  18675. else {
  18676. this._canvas = document.createElement("canvas");
  18677. if (options.width) {
  18678. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18679. }
  18680. else {
  18681. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18682. }
  18683. }
  18684. var textureSize = this.getSize();
  18685. this._canvas.width = textureSize.width;
  18686. this._canvas.height = textureSize.height;
  18687. this._context = this._canvas.getContext("2d");
  18688. }
  18689. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18690. get: function () {
  18691. return true;
  18692. },
  18693. enumerable: true,
  18694. configurable: true
  18695. });
  18696. DynamicTexture.prototype.scale = function (ratio) {
  18697. var textureSize = this.getSize();
  18698. textureSize.width *= ratio;
  18699. textureSize.height *= ratio;
  18700. this._canvas.width = textureSize.width;
  18701. this._canvas.height = textureSize.height;
  18702. this.releaseInternalTexture();
  18703. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18704. };
  18705. DynamicTexture.prototype.getContext = function () {
  18706. return this._context;
  18707. };
  18708. DynamicTexture.prototype.clear = function () {
  18709. var size = this.getSize();
  18710. this._context.fillRect(0, 0, size.width, size.height);
  18711. };
  18712. DynamicTexture.prototype.update = function (invertY) {
  18713. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18714. };
  18715. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18716. if (update === void 0) { update = true; }
  18717. var size = this.getSize();
  18718. if (clearColor) {
  18719. this._context.fillStyle = clearColor;
  18720. this._context.fillRect(0, 0, size.width, size.height);
  18721. }
  18722. this._context.font = font;
  18723. if (x === null) {
  18724. var textSize = this._context.measureText(text);
  18725. x = (size.width - textSize.width) / 2;
  18726. }
  18727. this._context.fillStyle = color;
  18728. this._context.fillText(text, x, y);
  18729. if (update) {
  18730. this.update(invertY);
  18731. }
  18732. };
  18733. DynamicTexture.prototype.clone = function () {
  18734. var textureSize = this.getSize();
  18735. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18736. // Base texture
  18737. newTexture.hasAlpha = this.hasAlpha;
  18738. newTexture.level = this.level;
  18739. // Dynamic Texture
  18740. newTexture.wrapU = this.wrapU;
  18741. newTexture.wrapV = this.wrapV;
  18742. return newTexture;
  18743. };
  18744. return DynamicTexture;
  18745. })(BABYLON.Texture);
  18746. BABYLON.DynamicTexture = DynamicTexture;
  18747. })(BABYLON || (BABYLON = {}));
  18748. var BABYLON;
  18749. (function (BABYLON) {
  18750. var VideoTexture = (function (_super) {
  18751. __extends(VideoTexture, _super);
  18752. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18753. var _this = this;
  18754. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18755. if (invertY === void 0) { invertY = false; }
  18756. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18757. _super.call(this, null, scene, !generateMipMaps, invertY);
  18758. this._autoLaunch = true;
  18759. this.name = name;
  18760. this.video = document.createElement("video");
  18761. this.video.autoplay = false;
  18762. this.video.loop = true;
  18763. this.video.addEventListener("canplaythrough", function () {
  18764. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18765. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18766. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18767. }
  18768. else {
  18769. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18770. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18771. generateMipMaps = false;
  18772. }
  18773. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18774. _this._texture.isReady = true;
  18775. });
  18776. urls.forEach(function (url) {
  18777. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18778. var source = document.createElement("source");
  18779. source.src = url;
  18780. _this.video.appendChild(source);
  18781. });
  18782. this._lastUpdate = BABYLON.Tools.Now;
  18783. }
  18784. VideoTexture.prototype.update = function () {
  18785. if (this._autoLaunch) {
  18786. this._autoLaunch = false;
  18787. this.video.play();
  18788. }
  18789. var now = BABYLON.Tools.Now;
  18790. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18791. return false;
  18792. }
  18793. this._lastUpdate = now;
  18794. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18795. return true;
  18796. };
  18797. return VideoTexture;
  18798. })(BABYLON.Texture);
  18799. BABYLON.VideoTexture = VideoTexture;
  18800. })(BABYLON || (BABYLON = {}));
  18801. var BABYLON;
  18802. (function (BABYLON) {
  18803. var CustomProceduralTexture = (function (_super) {
  18804. __extends(CustomProceduralTexture, _super);
  18805. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18806. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18807. this._animate = true;
  18808. this._time = 0;
  18809. this._texturePath = texturePath;
  18810. //Try to load json
  18811. this.loadJson(texturePath);
  18812. this.refreshRate = 1;
  18813. }
  18814. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18815. var _this = this;
  18816. var that = this;
  18817. function noConfigFile() {
  18818. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18819. try {
  18820. that.setFragment(that._texturePath);
  18821. }
  18822. catch (ex) {
  18823. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18824. }
  18825. }
  18826. var configFileUrl = jsonUrl + "/config.json";
  18827. var xhr = new XMLHttpRequest();
  18828. xhr.open("GET", configFileUrl, true);
  18829. xhr.addEventListener("load", function () {
  18830. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18831. try {
  18832. _this._config = JSON.parse(xhr.response);
  18833. _this.updateShaderUniforms();
  18834. _this.updateTextures();
  18835. _this.setFragment(_this._texturePath + "/custom");
  18836. _this._animate = _this._config.animate;
  18837. _this.refreshRate = _this._config.refreshrate;
  18838. }
  18839. catch (ex) {
  18840. noConfigFile();
  18841. }
  18842. }
  18843. else {
  18844. noConfigFile();
  18845. }
  18846. }, false);
  18847. xhr.addEventListener("error", function () {
  18848. noConfigFile();
  18849. }, false);
  18850. try {
  18851. xhr.send();
  18852. }
  18853. catch (ex) {
  18854. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18855. }
  18856. };
  18857. CustomProceduralTexture.prototype.isReady = function () {
  18858. if (!_super.prototype.isReady.call(this)) {
  18859. return false;
  18860. }
  18861. for (var name in this._textures) {
  18862. var texture = this._textures[name];
  18863. if (!texture.isReady()) {
  18864. return false;
  18865. }
  18866. }
  18867. return true;
  18868. };
  18869. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18870. if (this._animate) {
  18871. this._time += this.getScene().getAnimationRatio() * 0.03;
  18872. this.updateShaderUniforms();
  18873. }
  18874. _super.prototype.render.call(this, useCameraPostProcess);
  18875. };
  18876. CustomProceduralTexture.prototype.updateTextures = function () {
  18877. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18878. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18879. }
  18880. };
  18881. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18882. if (this._config) {
  18883. for (var j = 0; j < this._config.uniforms.length; j++) {
  18884. var uniform = this._config.uniforms[j];
  18885. switch (uniform.type) {
  18886. case "float":
  18887. this.setFloat(uniform.name, uniform.value);
  18888. break;
  18889. case "color3":
  18890. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18891. break;
  18892. case "color4":
  18893. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18894. break;
  18895. case "vector2":
  18896. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18897. break;
  18898. case "vector3":
  18899. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18900. break;
  18901. }
  18902. }
  18903. }
  18904. this.setFloat("time", this._time);
  18905. };
  18906. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18907. get: function () {
  18908. return this._animate;
  18909. },
  18910. set: function (value) {
  18911. this._animate = value;
  18912. },
  18913. enumerable: true,
  18914. configurable: true
  18915. });
  18916. return CustomProceduralTexture;
  18917. })(BABYLON.ProceduralTexture);
  18918. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18919. })(BABYLON || (BABYLON = {}));
  18920. var BABYLON;
  18921. (function (BABYLON) {
  18922. var EffectFallbacks = (function () {
  18923. function EffectFallbacks() {
  18924. this._defines = {};
  18925. this._currentRank = 32;
  18926. this._maxRank = -1;
  18927. }
  18928. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18929. if (!this._defines[rank]) {
  18930. if (rank < this._currentRank) {
  18931. this._currentRank = rank;
  18932. }
  18933. if (rank > this._maxRank) {
  18934. this._maxRank = rank;
  18935. }
  18936. this._defines[rank] = new Array();
  18937. }
  18938. this._defines[rank].push(define);
  18939. };
  18940. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18941. this._meshRank = rank;
  18942. this._mesh = mesh;
  18943. if (rank > this._maxRank) {
  18944. this._maxRank = rank;
  18945. }
  18946. };
  18947. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18948. get: function () {
  18949. return this._currentRank <= this._maxRank;
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18955. var currentFallbacks = this._defines[this._currentRank];
  18956. for (var index = 0; index < currentFallbacks.length; index++) {
  18957. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18958. }
  18959. if (this._mesh && this._currentRank === this._meshRank) {
  18960. this._mesh.computeBonesUsingShaders = false;
  18961. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18962. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18963. }
  18964. this._currentRank++;
  18965. return currentDefines;
  18966. };
  18967. return EffectFallbacks;
  18968. })();
  18969. BABYLON.EffectFallbacks = EffectFallbacks;
  18970. var Effect = (function () {
  18971. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18972. var _this = this;
  18973. this._isReady = false;
  18974. this._compilationError = "";
  18975. this._valueCache = [];
  18976. this._engine = engine;
  18977. this.name = baseName;
  18978. this.defines = defines;
  18979. this._uniformsNames = uniformsNames.concat(samplers);
  18980. this._samplers = samplers;
  18981. this._attributesNames = attributesNames;
  18982. this.onError = onError;
  18983. this.onCompiled = onCompiled;
  18984. var vertexSource;
  18985. var fragmentSource;
  18986. if (baseName.vertexElement) {
  18987. vertexSource = document.getElementById(baseName.vertexElement);
  18988. if (!vertexSource) {
  18989. vertexSource = baseName.vertexElement;
  18990. }
  18991. }
  18992. else {
  18993. vertexSource = baseName.vertex || baseName;
  18994. }
  18995. if (baseName.fragmentElement) {
  18996. fragmentSource = document.getElementById(baseName.fragmentElement);
  18997. if (!fragmentSource) {
  18998. fragmentSource = baseName.fragmentElement;
  18999. }
  19000. }
  19001. else {
  19002. fragmentSource = baseName.fragment || baseName;
  19003. }
  19004. this._loadVertexShader(vertexSource, function (vertexCode) {
  19005. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19006. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19007. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19008. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19009. });
  19010. });
  19011. });
  19012. });
  19013. }
  19014. // Properties
  19015. Effect.prototype.isReady = function () {
  19016. return this._isReady;
  19017. };
  19018. Effect.prototype.getProgram = function () {
  19019. return this._program;
  19020. };
  19021. Effect.prototype.getAttributesNames = function () {
  19022. return this._attributesNames;
  19023. };
  19024. Effect.prototype.getAttributeLocation = function (index) {
  19025. return this._attributes[index];
  19026. };
  19027. Effect.prototype.getAttributeLocationByName = function (name) {
  19028. var index = this._attributesNames.indexOf(name);
  19029. return this._attributes[index];
  19030. };
  19031. Effect.prototype.getAttributesCount = function () {
  19032. return this._attributes.length;
  19033. };
  19034. Effect.prototype.getUniformIndex = function (uniformName) {
  19035. return this._uniformsNames.indexOf(uniformName);
  19036. };
  19037. Effect.prototype.getUniform = function (uniformName) {
  19038. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19039. };
  19040. Effect.prototype.getSamplers = function () {
  19041. return this._samplers;
  19042. };
  19043. Effect.prototype.getCompilationError = function () {
  19044. return this._compilationError;
  19045. };
  19046. // Methods
  19047. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19048. // DOM element ?
  19049. if (vertex instanceof HTMLElement) {
  19050. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19051. callback(vertexCode);
  19052. return;
  19053. }
  19054. // Is in local store ?
  19055. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19056. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19057. return;
  19058. }
  19059. var vertexShaderUrl;
  19060. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19061. vertexShaderUrl = vertex;
  19062. }
  19063. else {
  19064. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19065. }
  19066. // Vertex shader
  19067. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19068. };
  19069. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19070. // DOM element ?
  19071. if (fragment instanceof HTMLElement) {
  19072. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19073. callback(fragmentCode);
  19074. return;
  19075. }
  19076. // Is in local store ?
  19077. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19078. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19079. return;
  19080. }
  19081. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19082. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19083. return;
  19084. }
  19085. var fragmentShaderUrl;
  19086. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19087. fragmentShaderUrl = fragment;
  19088. }
  19089. else {
  19090. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19091. }
  19092. // Fragment shader
  19093. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19094. };
  19095. Effect.prototype._dumpShadersName = function () {
  19096. if (this.name.vertexElement) {
  19097. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19098. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19099. }
  19100. else if (this.name.vertex) {
  19101. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19102. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19103. }
  19104. else {
  19105. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19106. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19107. }
  19108. };
  19109. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19110. var _this = this;
  19111. var regex = /#include<(.+)>(\((.*)\))*/g;
  19112. var match = regex.exec(sourceCode);
  19113. var returnValue = new String(sourceCode);
  19114. while (match != null) {
  19115. var includeFile = match[1];
  19116. if (Effect.IncludesShadersStore[includeFile]) {
  19117. // Substitution
  19118. var includeContent = Effect.IncludesShadersStore[includeFile];
  19119. if (match[2]) {
  19120. var splits = match[2].substr(1, match[2].length - 2).split(",");
  19121. for (var index = 0; index < splits.length; index += 2) {
  19122. var source = new RegExp(splits[index], "g");
  19123. var dest = splits[index + 1];
  19124. includeContent = includeContent.replace(source, dest);
  19125. }
  19126. }
  19127. // Replace
  19128. returnValue = returnValue.replace(match[0], includeContent);
  19129. }
  19130. else {
  19131. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19132. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19133. Effect.IncludesShadersStore[includeFile] = fileContent;
  19134. _this._processIncludes(returnValue, callback);
  19135. });
  19136. return;
  19137. }
  19138. match = regex.exec(sourceCode);
  19139. }
  19140. callback(returnValue);
  19141. };
  19142. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19143. try {
  19144. var engine = this._engine;
  19145. // Precision
  19146. if (!engine.getCaps().highPrecisionShaderSupported) {
  19147. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19148. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19149. }
  19150. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19151. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19152. this._attributes = engine.getAttributes(this._program, attributesNames);
  19153. for (var index = 0; index < this._samplers.length; index++) {
  19154. var sampler = this.getUniform(this._samplers[index]);
  19155. if (sampler == null) {
  19156. this._samplers.splice(index, 1);
  19157. index--;
  19158. }
  19159. }
  19160. engine.bindSamplers(this);
  19161. this._isReady = true;
  19162. if (this.onCompiled) {
  19163. this.onCompiled(this);
  19164. }
  19165. }
  19166. catch (e) {
  19167. // Is it a problem with precision?
  19168. if (e.message.indexOf("highp") !== -1) {
  19169. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19170. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19171. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19172. return;
  19173. }
  19174. // Let's go through fallbacks then
  19175. if (fallbacks && fallbacks.isMoreFallbacks) {
  19176. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19177. this._dumpShadersName();
  19178. defines = fallbacks.reduce(defines);
  19179. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19180. }
  19181. else {
  19182. BABYLON.Tools.Error("Unable to compile effect: ");
  19183. this._dumpShadersName();
  19184. BABYLON.Tools.Error("Defines: " + defines);
  19185. BABYLON.Tools.Error("Error: " + e.message);
  19186. this._compilationError = e.message;
  19187. if (this.onError) {
  19188. this.onError(this, this._compilationError);
  19189. }
  19190. }
  19191. }
  19192. };
  19193. Object.defineProperty(Effect.prototype, "isSupported", {
  19194. get: function () {
  19195. return this._compilationError === "";
  19196. },
  19197. enumerable: true,
  19198. configurable: true
  19199. });
  19200. Effect.prototype._bindTexture = function (channel, texture) {
  19201. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19202. };
  19203. Effect.prototype.setTexture = function (channel, texture) {
  19204. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19205. };
  19206. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19207. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19208. };
  19209. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19210. if (!this._valueCache[uniformName]) {
  19211. this._valueCache[uniformName] = new BABYLON.Matrix();
  19212. }
  19213. for (var index = 0; index < 16; index++) {
  19214. this._valueCache[uniformName].m[index] = matrix.m[index];
  19215. }
  19216. };
  19217. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19218. if (!this._valueCache[uniformName]) {
  19219. this._valueCache[uniformName] = [x, y];
  19220. return;
  19221. }
  19222. this._valueCache[uniformName][0] = x;
  19223. this._valueCache[uniformName][1] = y;
  19224. };
  19225. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19226. if (!this._valueCache[uniformName]) {
  19227. this._valueCache[uniformName] = [x, y, z];
  19228. return;
  19229. }
  19230. this._valueCache[uniformName][0] = x;
  19231. this._valueCache[uniformName][1] = y;
  19232. this._valueCache[uniformName][2] = z;
  19233. };
  19234. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19235. if (!this._valueCache[uniformName]) {
  19236. this._valueCache[uniformName] = [x, y, z, w];
  19237. return;
  19238. }
  19239. this._valueCache[uniformName][0] = x;
  19240. this._valueCache[uniformName][1] = y;
  19241. this._valueCache[uniformName][2] = z;
  19242. this._valueCache[uniformName][3] = w;
  19243. };
  19244. Effect.prototype.setArray = function (uniformName, array) {
  19245. this._engine.setArray(this.getUniform(uniformName), array);
  19246. return this;
  19247. };
  19248. Effect.prototype.setArray2 = function (uniformName, array) {
  19249. this._engine.setArray2(this.getUniform(uniformName), array);
  19250. return this;
  19251. };
  19252. Effect.prototype.setArray3 = function (uniformName, array) {
  19253. this._engine.setArray3(this.getUniform(uniformName), array);
  19254. return this;
  19255. };
  19256. Effect.prototype.setArray4 = function (uniformName, array) {
  19257. this._engine.setArray4(this.getUniform(uniformName), array);
  19258. return this;
  19259. };
  19260. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19261. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19262. return this;
  19263. };
  19264. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19265. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19266. // return this;
  19267. // this._cacheMatrix(uniformName, matrix);
  19268. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19269. return this;
  19270. };
  19271. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19272. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19273. return this;
  19274. };
  19275. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19276. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19277. return this;
  19278. };
  19279. Effect.prototype.setFloat = function (uniformName, value) {
  19280. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19281. return this;
  19282. this._valueCache[uniformName] = value;
  19283. this._engine.setFloat(this.getUniform(uniformName), value);
  19284. return this;
  19285. };
  19286. Effect.prototype.setBool = function (uniformName, bool) {
  19287. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19288. return this;
  19289. this._valueCache[uniformName] = bool;
  19290. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19291. return this;
  19292. };
  19293. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19294. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19295. return this;
  19296. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19297. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19298. return this;
  19299. };
  19300. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19301. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19302. return this;
  19303. this._cacheFloat2(uniformName, x, y);
  19304. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19305. return this;
  19306. };
  19307. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19308. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19309. return this;
  19310. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19311. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19312. return this;
  19313. };
  19314. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19315. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19316. return this;
  19317. this._cacheFloat3(uniformName, x, y, z);
  19318. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19319. return this;
  19320. };
  19321. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19322. 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)
  19323. return this;
  19324. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19325. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19326. return this;
  19327. };
  19328. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19329. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19330. return this;
  19331. this._cacheFloat4(uniformName, x, y, z, w);
  19332. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19333. return this;
  19334. };
  19335. Effect.prototype.setColor3 = function (uniformName, color3) {
  19336. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19337. return this;
  19338. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19339. this._engine.setColor3(this.getUniform(uniformName), color3);
  19340. return this;
  19341. };
  19342. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19343. 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)
  19344. return this;
  19345. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19346. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19347. return this;
  19348. };
  19349. // Statics
  19350. Effect.ShadersStore = {};
  19351. Effect.IncludesShadersStore = {};
  19352. return Effect;
  19353. })();
  19354. BABYLON.Effect = Effect;
  19355. })(BABYLON || (BABYLON = {}));
  19356. var BABYLON;
  19357. (function (BABYLON) {
  19358. var maxSimultaneousLights = 4;
  19359. var MaterialHelper = (function () {
  19360. function MaterialHelper() {
  19361. }
  19362. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19363. var lightIndex = 0;
  19364. var needNormals = false;
  19365. for (var index = 0; index < scene.lights.length; index++) {
  19366. var light = scene.lights[index];
  19367. if (!light.isEnabled()) {
  19368. continue;
  19369. }
  19370. // Excluded check
  19371. if (light._excludedMeshesIds.length > 0) {
  19372. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19373. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19374. if (excludedMesh) {
  19375. light.excludedMeshes.push(excludedMesh);
  19376. }
  19377. }
  19378. light._excludedMeshesIds = [];
  19379. }
  19380. // Included check
  19381. if (light._includedOnlyMeshesIds.length > 0) {
  19382. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19383. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19384. if (includedOnlyMesh) {
  19385. light.includedOnlyMeshes.push(includedOnlyMesh);
  19386. }
  19387. }
  19388. light._includedOnlyMeshesIds = [];
  19389. }
  19390. if (!light.canAffectMesh(mesh)) {
  19391. continue;
  19392. }
  19393. needNormals = true;
  19394. defines["LIGHT" + lightIndex] = true;
  19395. var type;
  19396. if (light instanceof BABYLON.SpotLight) {
  19397. type = "SPOTLIGHT" + lightIndex;
  19398. }
  19399. else if (light instanceof BABYLON.HemisphericLight) {
  19400. type = "HEMILIGHT" + lightIndex;
  19401. }
  19402. else if (light instanceof BABYLON.PointLight) {
  19403. type = "POINTLIGHT" + lightIndex;
  19404. }
  19405. else {
  19406. type = "DIRLIGHT" + lightIndex;
  19407. }
  19408. defines[type] = true;
  19409. // Specular
  19410. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19411. defines["SPECULARTERM"] = true;
  19412. }
  19413. // Shadows
  19414. if (scene.shadowsEnabled) {
  19415. var shadowGenerator = light.getShadowGenerator();
  19416. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19417. defines["SHADOW" + lightIndex] = true;
  19418. defines["SHADOWS"] = true;
  19419. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19420. defines["SHADOWVSM" + lightIndex] = true;
  19421. }
  19422. if (shadowGenerator.usePoissonSampling) {
  19423. defines["SHADOWPCF" + lightIndex] = true;
  19424. }
  19425. }
  19426. }
  19427. lightIndex++;
  19428. if (lightIndex === maxSimultaneousLights)
  19429. break;
  19430. }
  19431. return needNormals;
  19432. };
  19433. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19434. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19435. if (!defines["LIGHT" + lightIndex]) {
  19436. continue;
  19437. }
  19438. if (lightIndex > 0) {
  19439. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19440. }
  19441. if (defines["SHADOW" + lightIndex]) {
  19442. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19443. }
  19444. if (defines["SHADOWPCF" + lightIndex]) {
  19445. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19446. }
  19447. if (defines["SHADOWVSM" + lightIndex]) {
  19448. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19449. }
  19450. }
  19451. };
  19452. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19453. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19454. fallbacks.addCPUSkinningFallback(0, mesh);
  19455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19457. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19458. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19459. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19460. }
  19461. }
  19462. };
  19463. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19464. if (defines["INSTANCES"]) {
  19465. attribs.push("world0");
  19466. attribs.push("world1");
  19467. attribs.push("world2");
  19468. attribs.push("world3");
  19469. }
  19470. };
  19471. // Bindings
  19472. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19473. var shadowGenerator = light.getShadowGenerator();
  19474. if (mesh.receiveShadows && shadowGenerator) {
  19475. if (!light.needCube()) {
  19476. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19477. }
  19478. else {
  19479. if (!depthValuesAlreadySet) {
  19480. depthValuesAlreadySet = true;
  19481. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19482. }
  19483. }
  19484. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19485. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19486. }
  19487. return depthValuesAlreadySet;
  19488. };
  19489. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19490. if (light instanceof BABYLON.PointLight) {
  19491. // Point Light
  19492. light.transferToEffect(effect, "vLightData" + lightIndex);
  19493. }
  19494. else if (light instanceof BABYLON.DirectionalLight) {
  19495. // Directional Light
  19496. light.transferToEffect(effect, "vLightData" + lightIndex);
  19497. }
  19498. else if (light instanceof BABYLON.SpotLight) {
  19499. // Spot Light
  19500. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19501. }
  19502. else if (light instanceof BABYLON.HemisphericLight) {
  19503. // Hemispheric Light
  19504. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19505. }
  19506. };
  19507. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19508. var lightIndex = 0;
  19509. var depthValuesAlreadySet = false;
  19510. for (var index = 0; index < scene.lights.length; index++) {
  19511. var light = scene.lights[index];
  19512. if (!light.isEnabled()) {
  19513. continue;
  19514. }
  19515. if (!light.canAffectMesh(mesh)) {
  19516. continue;
  19517. }
  19518. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19519. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19520. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19521. if (defines["SPECULARTERM"]) {
  19522. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19523. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19524. }
  19525. // Shadows
  19526. if (scene.shadowsEnabled) {
  19527. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19528. }
  19529. lightIndex++;
  19530. if (lightIndex === maxSimultaneousLights)
  19531. break;
  19532. }
  19533. };
  19534. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19535. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19536. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19537. effect.setColor3("vFogColor", scene.fogColor);
  19538. }
  19539. };
  19540. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19541. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19542. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19543. }
  19544. };
  19545. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19546. if (defines["LOGARITHMICDEPTH"]) {
  19547. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19548. }
  19549. };
  19550. MaterialHelper.BindClipPlane = function (effect, scene) {
  19551. if (scene.clipPlane) {
  19552. var clipPlane = scene.clipPlane;
  19553. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19554. }
  19555. };
  19556. return MaterialHelper;
  19557. })();
  19558. BABYLON.MaterialHelper = MaterialHelper;
  19559. })(BABYLON || (BABYLON = {}));
  19560. var BABYLON;
  19561. (function (BABYLON) {
  19562. var FresnelParameters = (function () {
  19563. function FresnelParameters() {
  19564. this.isEnabled = true;
  19565. this.leftColor = BABYLON.Color3.White();
  19566. this.rightColor = BABYLON.Color3.Black();
  19567. this.bias = 0;
  19568. this.power = 1;
  19569. }
  19570. FresnelParameters.prototype.clone = function () {
  19571. var newFresnelParameters = new FresnelParameters();
  19572. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19573. return new FresnelParameters;
  19574. };
  19575. FresnelParameters.prototype.serialize = function () {
  19576. var serializationObject = {};
  19577. serializationObject.isEnabled = this.isEnabled;
  19578. serializationObject.leftColor = this.leftColor;
  19579. serializationObject.rightColor = this.rightColor;
  19580. serializationObject.bias = this.bias;
  19581. serializationObject.power = this.power;
  19582. return serializationObject;
  19583. };
  19584. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19585. var fresnelParameters = new FresnelParameters();
  19586. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19587. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19588. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19589. fresnelParameters.bias = parsedFresnelParameters.bias;
  19590. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19591. return fresnelParameters;
  19592. };
  19593. return FresnelParameters;
  19594. })();
  19595. BABYLON.FresnelParameters = FresnelParameters;
  19596. })(BABYLON || (BABYLON = {}));
  19597. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19598. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19599. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19600. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19601. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19602. };
  19603. var BABYLON;
  19604. (function (BABYLON) {
  19605. var MaterialDefines = (function () {
  19606. function MaterialDefines() {
  19607. }
  19608. MaterialDefines.prototype.isEqual = function (other) {
  19609. for (var index = 0; index < this._keys.length; index++) {
  19610. var prop = this._keys[index];
  19611. if (this[prop] !== other[prop]) {
  19612. return false;
  19613. }
  19614. }
  19615. return true;
  19616. };
  19617. MaterialDefines.prototype.cloneTo = function (other) {
  19618. for (var index = 0; index < this._keys.length; index++) {
  19619. var prop = this._keys[index];
  19620. other[prop] = this[prop];
  19621. }
  19622. };
  19623. MaterialDefines.prototype.reset = function () {
  19624. for (var index = 0; index < this._keys.length; index++) {
  19625. var prop = this._keys[index];
  19626. if (typeof (this[prop]) === "number") {
  19627. this[prop] = 0;
  19628. }
  19629. else {
  19630. this[prop] = false;
  19631. }
  19632. }
  19633. };
  19634. MaterialDefines.prototype.toString = function () {
  19635. var result = "";
  19636. for (var index = 0; index < this._keys.length; index++) {
  19637. var prop = this._keys[index];
  19638. if (typeof (this[prop]) === "number") {
  19639. result += "#define " + prop + " " + this[prop] + "\n";
  19640. }
  19641. else if (this[prop]) {
  19642. result += "#define " + prop + "\n";
  19643. }
  19644. }
  19645. return result;
  19646. };
  19647. return MaterialDefines;
  19648. })();
  19649. BABYLON.MaterialDefines = MaterialDefines;
  19650. var Material = (function () {
  19651. function Material(name, scene, doNotAdd) {
  19652. this.name = name;
  19653. this.checkReadyOnEveryCall = false;
  19654. this.checkReadyOnlyOnce = false;
  19655. this.state = "";
  19656. this.alpha = 1.0;
  19657. this.backFaceCulling = true;
  19658. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19659. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19660. this.disableDepthWrite = false;
  19661. this.fogEnabled = true;
  19662. this.pointSize = 1.0;
  19663. this.zOffset = 0;
  19664. this._wasPreviouslyReady = false;
  19665. this._fillMode = Material.TriangleFillMode;
  19666. this.id = name;
  19667. this._scene = scene;
  19668. if (!doNotAdd) {
  19669. scene.materials.push(this);
  19670. }
  19671. }
  19672. Object.defineProperty(Material, "TriangleFillMode", {
  19673. get: function () {
  19674. return Material._TriangleFillMode;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Material, "WireFrameFillMode", {
  19680. get: function () {
  19681. return Material._WireFrameFillMode;
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(Material, "PointFillMode", {
  19687. get: function () {
  19688. return Material._PointFillMode;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19694. get: function () {
  19695. return Material._ClockWiseSideOrientation;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19701. get: function () {
  19702. return Material._CounterClockWiseSideOrientation;
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(Material.prototype, "wireframe", {
  19708. get: function () {
  19709. return this._fillMode === Material.WireFrameFillMode;
  19710. },
  19711. set: function (value) {
  19712. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(Material.prototype, "pointsCloud", {
  19718. get: function () {
  19719. return this._fillMode === Material.PointFillMode;
  19720. },
  19721. set: function (value) {
  19722. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(Material.prototype, "fillMode", {
  19728. get: function () {
  19729. return this._fillMode;
  19730. },
  19731. set: function (value) {
  19732. this._fillMode = value;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(Material.prototype, "isFrozen", {
  19738. get: function () {
  19739. return this.checkReadyOnlyOnce;
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Material.prototype.freeze = function () {
  19745. this.checkReadyOnlyOnce = true;
  19746. };
  19747. Material.prototype.unfreeze = function () {
  19748. this.checkReadyOnlyOnce = false;
  19749. };
  19750. Material.prototype.isReady = function (mesh, useInstances) {
  19751. return true;
  19752. };
  19753. Material.prototype.getEffect = function () {
  19754. return this._effect;
  19755. };
  19756. Material.prototype.getScene = function () {
  19757. return this._scene;
  19758. };
  19759. Material.prototype.needAlphaBlending = function () {
  19760. return (this.alpha < 1.0);
  19761. };
  19762. Material.prototype.needAlphaTesting = function () {
  19763. return false;
  19764. };
  19765. Material.prototype.getAlphaTestTexture = function () {
  19766. return null;
  19767. };
  19768. Material.prototype.trackCreation = function (onCompiled, onError) {
  19769. };
  19770. Material.prototype.markDirty = function () {
  19771. this._wasPreviouslyReady = false;
  19772. };
  19773. Material.prototype._preBind = function () {
  19774. var engine = this._scene.getEngine();
  19775. engine.enableEffect(this._effect);
  19776. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19777. };
  19778. Material.prototype.bind = function (world, mesh) {
  19779. this._scene._cachedMaterial = this;
  19780. if (this.onBind) {
  19781. this.onBind(this, mesh);
  19782. }
  19783. if (this.disableDepthWrite) {
  19784. var engine = this._scene.getEngine();
  19785. this._cachedDepthWriteState = engine.getDepthWrite();
  19786. engine.setDepthWrite(false);
  19787. }
  19788. };
  19789. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19790. };
  19791. Material.prototype.unbind = function () {
  19792. if (this.disableDepthWrite) {
  19793. var engine = this._scene.getEngine();
  19794. engine.setDepthWrite(this._cachedDepthWriteState);
  19795. }
  19796. };
  19797. Material.prototype.clone = function (name) {
  19798. return null;
  19799. };
  19800. Material.prototype.getBindedMeshes = function () {
  19801. var result = new Array();
  19802. for (var index = 0; index < this._scene.meshes.length; index++) {
  19803. var mesh = this._scene.meshes[index];
  19804. if (mesh.material === this) {
  19805. result.push(mesh);
  19806. }
  19807. }
  19808. return result;
  19809. };
  19810. Material.prototype.dispose = function (forceDisposeEffect) {
  19811. // Animations
  19812. this.getScene().stopAnimation(this);
  19813. // Remove from scene
  19814. var index = this._scene.materials.indexOf(this);
  19815. if (index >= 0) {
  19816. this._scene.materials.splice(index, 1);
  19817. }
  19818. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19819. if (forceDisposeEffect && this._effect) {
  19820. this._scene.getEngine()._releaseEffect(this._effect);
  19821. this._effect = null;
  19822. }
  19823. // Remove from meshes
  19824. for (index = 0; index < this._scene.meshes.length; index++) {
  19825. var mesh = this._scene.meshes[index];
  19826. if (mesh.material === this) {
  19827. mesh.material = null;
  19828. }
  19829. }
  19830. // Callback
  19831. if (this.onDispose) {
  19832. this.onDispose();
  19833. }
  19834. };
  19835. Material.prototype.serialize = function () {
  19836. return BABYLON.SerializationHelper.Serialize(this);
  19837. };
  19838. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19839. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19840. multiMaterial.id = parsedMultiMaterial.id;
  19841. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19842. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19843. var subMatId = parsedMultiMaterial.materials[matIndex];
  19844. if (subMatId) {
  19845. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19846. }
  19847. else {
  19848. multiMaterial.subMaterials.push(null);
  19849. }
  19850. }
  19851. return multiMaterial;
  19852. };
  19853. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19854. if (!parsedMaterial.customType) {
  19855. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19856. }
  19857. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19858. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19859. ;
  19860. };
  19861. Material._TriangleFillMode = 0;
  19862. Material._WireFrameFillMode = 1;
  19863. Material._PointFillMode = 2;
  19864. Material._ClockWiseSideOrientation = 0;
  19865. Material._CounterClockWiseSideOrientation = 1;
  19866. __decorate([
  19867. BABYLON.serialize()
  19868. ], Material.prototype, "id", void 0);
  19869. __decorate([
  19870. BABYLON.serialize()
  19871. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19872. __decorate([
  19873. BABYLON.serialize()
  19874. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19875. __decorate([
  19876. BABYLON.serialize()
  19877. ], Material.prototype, "state", void 0);
  19878. __decorate([
  19879. BABYLON.serialize()
  19880. ], Material.prototype, "alpha", void 0);
  19881. __decorate([
  19882. BABYLON.serialize()
  19883. ], Material.prototype, "backFaceCulling", void 0);
  19884. __decorate([
  19885. BABYLON.serialize()
  19886. ], Material.prototype, "sideOrientation", void 0);
  19887. __decorate([
  19888. BABYLON.serialize()
  19889. ], Material.prototype, "alphaMode", void 0);
  19890. __decorate([
  19891. BABYLON.serialize()
  19892. ], Material.prototype, "disableDepthWrite", void 0);
  19893. __decorate([
  19894. BABYLON.serialize()
  19895. ], Material.prototype, "fogEnabled", void 0);
  19896. __decorate([
  19897. BABYLON.serialize()
  19898. ], Material.prototype, "pointSize", void 0);
  19899. __decorate([
  19900. BABYLON.serialize()
  19901. ], Material.prototype, "zOffset", void 0);
  19902. __decorate([
  19903. BABYLON.serialize()
  19904. ], Material.prototype, "wireframe", null);
  19905. __decorate([
  19906. BABYLON.serialize()
  19907. ], Material.prototype, "pointsCloud", null);
  19908. __decorate([
  19909. BABYLON.serialize()
  19910. ], Material.prototype, "fillMode", null);
  19911. return Material;
  19912. })();
  19913. BABYLON.Material = Material;
  19914. })(BABYLON || (BABYLON = {}));
  19915. var BABYLON;
  19916. (function (BABYLON) {
  19917. var StandardMaterialDefines = (function (_super) {
  19918. __extends(StandardMaterialDefines, _super);
  19919. function StandardMaterialDefines() {
  19920. _super.call(this);
  19921. this.DIFFUSE = false;
  19922. this.AMBIENT = false;
  19923. this.OPACITY = false;
  19924. this.OPACITYRGB = false;
  19925. this.REFLECTION = false;
  19926. this.EMISSIVE = false;
  19927. this.SPECULAR = false;
  19928. this.BUMP = false;
  19929. this.SPECULAROVERALPHA = false;
  19930. this.CLIPPLANE = false;
  19931. this.ALPHATEST = false;
  19932. this.ALPHAFROMDIFFUSE = false;
  19933. this.POINTSIZE = false;
  19934. this.FOG = false;
  19935. this.LIGHT0 = false;
  19936. this.LIGHT1 = false;
  19937. this.LIGHT2 = false;
  19938. this.LIGHT3 = false;
  19939. this.SPOTLIGHT0 = false;
  19940. this.SPOTLIGHT1 = false;
  19941. this.SPOTLIGHT2 = false;
  19942. this.SPOTLIGHT3 = false;
  19943. this.HEMILIGHT0 = false;
  19944. this.HEMILIGHT1 = false;
  19945. this.HEMILIGHT2 = false;
  19946. this.HEMILIGHT3 = false;
  19947. this.POINTLIGHT0 = false;
  19948. this.POINTLIGHT1 = false;
  19949. this.POINTLIGHT2 = false;
  19950. this.POINTLIGHT3 = false;
  19951. this.DIRLIGHT0 = false;
  19952. this.DIRLIGHT1 = false;
  19953. this.DIRLIGHT2 = false;
  19954. this.DIRLIGHT3 = false;
  19955. this.SPECULARTERM = false;
  19956. this.SHADOW0 = false;
  19957. this.SHADOW1 = false;
  19958. this.SHADOW2 = false;
  19959. this.SHADOW3 = false;
  19960. this.SHADOWS = false;
  19961. this.SHADOWVSM0 = false;
  19962. this.SHADOWVSM1 = false;
  19963. this.SHADOWVSM2 = false;
  19964. this.SHADOWVSM3 = false;
  19965. this.SHADOWPCF0 = false;
  19966. this.SHADOWPCF1 = false;
  19967. this.SHADOWPCF2 = false;
  19968. this.SHADOWPCF3 = false;
  19969. this.DIFFUSEFRESNEL = false;
  19970. this.OPACITYFRESNEL = false;
  19971. this.REFLECTIONFRESNEL = false;
  19972. this.REFRACTIONFRESNEL = false;
  19973. this.EMISSIVEFRESNEL = false;
  19974. this.FRESNEL = false;
  19975. this.NORMAL = false;
  19976. this.UV1 = false;
  19977. this.UV2 = false;
  19978. this.VERTEXCOLOR = false;
  19979. this.VERTEXALPHA = false;
  19980. this.NUM_BONE_INFLUENCERS = 0;
  19981. this.BonesPerMesh = 0;
  19982. this.INSTANCES = false;
  19983. this.GLOSSINESS = false;
  19984. this.ROUGHNESS = false;
  19985. this.EMISSIVEASILLUMINATION = false;
  19986. this.LINKEMISSIVEWITHDIFFUSE = false;
  19987. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19988. this.LIGHTMAP = false;
  19989. this.USELIGHTMAPASSHADOWMAP = false;
  19990. this.REFLECTIONMAP_3D = false;
  19991. this.REFLECTIONMAP_SPHERICAL = false;
  19992. this.REFLECTIONMAP_PLANAR = false;
  19993. this.REFLECTIONMAP_CUBIC = false;
  19994. this.REFLECTIONMAP_PROJECTION = false;
  19995. this.REFLECTIONMAP_SKYBOX = false;
  19996. this.REFLECTIONMAP_EXPLICIT = false;
  19997. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19998. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19999. this.INVERTCUBICMAP = false;
  20000. this.LOGARITHMICDEPTH = false;
  20001. this.REFRACTION = false;
  20002. this.REFRACTIONMAP_3D = false;
  20003. this.REFLECTIONOVERALPHA = false;
  20004. this._keys = Object.keys(this);
  20005. }
  20006. return StandardMaterialDefines;
  20007. })(BABYLON.MaterialDefines);
  20008. var StandardMaterial = (function (_super) {
  20009. __extends(StandardMaterial, _super);
  20010. function StandardMaterial(name, scene) {
  20011. var _this = this;
  20012. _super.call(this, name, scene);
  20013. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20014. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20015. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20016. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20017. this.specularPower = 64;
  20018. this.useAlphaFromDiffuseTexture = false;
  20019. this.useEmissiveAsIllumination = false;
  20020. this.linkEmissiveWithDiffuse = false;
  20021. this.useReflectionFresnelFromSpecular = false;
  20022. this.useSpecularOverAlpha = false;
  20023. this.useReflectionOverAlpha = false;
  20024. this.disableLighting = false;
  20025. this.roughness = 0;
  20026. this.indexOfRefraction = 0.98;
  20027. this.invertRefractionY = true;
  20028. this.useLightmapAsShadowmap = false;
  20029. this.useGlossinessFromSpecularMapAlpha = false;
  20030. this._renderTargets = new BABYLON.SmartArray(16);
  20031. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20032. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20033. this._defines = new StandardMaterialDefines();
  20034. this._cachedDefines = new StandardMaterialDefines();
  20035. this._cachedDefines.BonesPerMesh = -1;
  20036. this.getRenderTargetTextures = function () {
  20037. _this._renderTargets.reset();
  20038. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20039. _this._renderTargets.push(_this.reflectionTexture);
  20040. }
  20041. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20042. _this._renderTargets.push(_this.refractionTexture);
  20043. }
  20044. return _this._renderTargets;
  20045. };
  20046. }
  20047. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20048. get: function () {
  20049. return this._useLogarithmicDepth;
  20050. },
  20051. set: function (value) {
  20052. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. StandardMaterial.prototype.needAlphaBlending = function () {
  20058. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20059. };
  20060. StandardMaterial.prototype.needAlphaTesting = function () {
  20061. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20062. };
  20063. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20064. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20065. };
  20066. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20067. return this.diffuseTexture;
  20068. };
  20069. // Methods
  20070. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20071. if (!mesh) {
  20072. return true;
  20073. }
  20074. if (this._defines.INSTANCES !== useInstances) {
  20075. return false;
  20076. }
  20077. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20078. return true;
  20079. }
  20080. return false;
  20081. };
  20082. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20083. if (this.isFrozen) {
  20084. if (this._wasPreviouslyReady) {
  20085. return true;
  20086. }
  20087. }
  20088. var scene = this.getScene();
  20089. if (!this.checkReadyOnEveryCall) {
  20090. if (this._renderId === scene.getRenderId()) {
  20091. if (this._checkCache(scene, mesh, useInstances)) {
  20092. return true;
  20093. }
  20094. }
  20095. }
  20096. var engine = scene.getEngine();
  20097. var needNormals = false;
  20098. var needUVs = false;
  20099. this._defines.reset();
  20100. // Textures
  20101. if (scene.texturesEnabled) {
  20102. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20103. if (!this.diffuseTexture.isReady()) {
  20104. return false;
  20105. }
  20106. else {
  20107. needUVs = true;
  20108. this._defines.DIFFUSE = true;
  20109. }
  20110. }
  20111. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20112. if (!this.ambientTexture.isReady()) {
  20113. return false;
  20114. }
  20115. else {
  20116. needUVs = true;
  20117. this._defines.AMBIENT = true;
  20118. }
  20119. }
  20120. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20121. if (!this.opacityTexture.isReady()) {
  20122. return false;
  20123. }
  20124. else {
  20125. needUVs = true;
  20126. this._defines.OPACITY = true;
  20127. if (this.opacityTexture.getAlphaFromRGB) {
  20128. this._defines.OPACITYRGB = true;
  20129. }
  20130. }
  20131. }
  20132. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20133. if (!this.reflectionTexture.isReady()) {
  20134. return false;
  20135. }
  20136. else {
  20137. needNormals = true;
  20138. this._defines.REFLECTION = true;
  20139. if (this.roughness > 0) {
  20140. this._defines.ROUGHNESS = true;
  20141. }
  20142. if (this.useReflectionOverAlpha) {
  20143. this._defines.REFLECTIONOVERALPHA = true;
  20144. }
  20145. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20146. this._defines.INVERTCUBICMAP = true;
  20147. }
  20148. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20149. switch (this.reflectionTexture.coordinatesMode) {
  20150. case BABYLON.Texture.CUBIC_MODE:
  20151. case BABYLON.Texture.INVCUBIC_MODE:
  20152. this._defines.REFLECTIONMAP_CUBIC = true;
  20153. break;
  20154. case BABYLON.Texture.EXPLICIT_MODE:
  20155. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20156. break;
  20157. case BABYLON.Texture.PLANAR_MODE:
  20158. this._defines.REFLECTIONMAP_PLANAR = true;
  20159. break;
  20160. case BABYLON.Texture.PROJECTION_MODE:
  20161. this._defines.REFLECTIONMAP_PROJECTION = true;
  20162. break;
  20163. case BABYLON.Texture.SKYBOX_MODE:
  20164. this._defines.REFLECTIONMAP_SKYBOX = true;
  20165. break;
  20166. case BABYLON.Texture.SPHERICAL_MODE:
  20167. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20168. break;
  20169. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20170. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20171. break;
  20172. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20173. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20174. break;
  20175. }
  20176. }
  20177. }
  20178. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20179. if (!this.emissiveTexture.isReady()) {
  20180. return false;
  20181. }
  20182. else {
  20183. needUVs = true;
  20184. this._defines.EMISSIVE = true;
  20185. }
  20186. }
  20187. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20188. if (!this.lightmapTexture.isReady()) {
  20189. return false;
  20190. }
  20191. else {
  20192. needUVs = true;
  20193. this._defines.LIGHTMAP = true;
  20194. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20195. }
  20196. }
  20197. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20198. if (!this.specularTexture.isReady()) {
  20199. return false;
  20200. }
  20201. else {
  20202. needUVs = true;
  20203. this._defines.SPECULAR = true;
  20204. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20205. }
  20206. }
  20207. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20208. if (!this.bumpTexture.isReady()) {
  20209. return false;
  20210. }
  20211. else {
  20212. needUVs = true;
  20213. this._defines.BUMP = true;
  20214. }
  20215. }
  20216. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20217. if (!this.refractionTexture.isReady()) {
  20218. return false;
  20219. }
  20220. else {
  20221. needUVs = true;
  20222. this._defines.REFRACTION = true;
  20223. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20224. }
  20225. }
  20226. }
  20227. // Effect
  20228. if (scene.clipPlane) {
  20229. this._defines.CLIPPLANE = true;
  20230. }
  20231. if (engine.getAlphaTesting()) {
  20232. this._defines.ALPHATEST = true;
  20233. }
  20234. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20235. this._defines.ALPHAFROMDIFFUSE = true;
  20236. }
  20237. if (this.useEmissiveAsIllumination) {
  20238. this._defines.EMISSIVEASILLUMINATION = true;
  20239. }
  20240. if (this.linkEmissiveWithDiffuse) {
  20241. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20242. }
  20243. if (this.useLogarithmicDepth) {
  20244. this._defines.LOGARITHMICDEPTH = true;
  20245. }
  20246. // Point size
  20247. if (this.pointsCloud || scene.forcePointsCloud) {
  20248. this._defines.POINTSIZE = true;
  20249. }
  20250. // Fog
  20251. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20252. this._defines.FOG = true;
  20253. }
  20254. if (scene.lightsEnabled && !this.disableLighting) {
  20255. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20256. }
  20257. if (StandardMaterial.FresnelEnabled) {
  20258. // Fresnel
  20259. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20260. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20261. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20262. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20263. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20264. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20265. this._defines.DIFFUSEFRESNEL = true;
  20266. }
  20267. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20268. this._defines.OPACITYFRESNEL = true;
  20269. }
  20270. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20271. this._defines.REFLECTIONFRESNEL = true;
  20272. if (this.useReflectionFresnelFromSpecular) {
  20273. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20274. }
  20275. }
  20276. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20277. this._defines.REFRACTIONFRESNEL = true;
  20278. }
  20279. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20280. this._defines.EMISSIVEFRESNEL = true;
  20281. }
  20282. needNormals = true;
  20283. this._defines.FRESNEL = true;
  20284. }
  20285. }
  20286. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20287. this._defines.SPECULAROVERALPHA = true;
  20288. }
  20289. // Attribs
  20290. if (mesh) {
  20291. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20292. this._defines.NORMAL = true;
  20293. }
  20294. if (needUVs) {
  20295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20296. this._defines.UV1 = true;
  20297. }
  20298. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20299. this._defines.UV2 = true;
  20300. }
  20301. }
  20302. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20303. this._defines.VERTEXCOLOR = true;
  20304. if (mesh.hasVertexAlpha) {
  20305. this._defines.VERTEXALPHA = true;
  20306. }
  20307. }
  20308. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20309. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20310. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20311. }
  20312. // Instances
  20313. if (useInstances) {
  20314. this._defines.INSTANCES = true;
  20315. }
  20316. }
  20317. // Get correct effect
  20318. if (!this._defines.isEqual(this._cachedDefines)) {
  20319. this._defines.cloneTo(this._cachedDefines);
  20320. scene.resetCachedMaterial();
  20321. // Fallbacks
  20322. var fallbacks = new BABYLON.EffectFallbacks();
  20323. if (this._defines.REFLECTION) {
  20324. fallbacks.addFallback(0, "REFLECTION");
  20325. }
  20326. if (this._defines.SPECULAR) {
  20327. fallbacks.addFallback(0, "SPECULAR");
  20328. }
  20329. if (this._defines.BUMP) {
  20330. fallbacks.addFallback(0, "BUMP");
  20331. }
  20332. if (this._defines.SPECULAROVERALPHA) {
  20333. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20334. }
  20335. if (this._defines.FOG) {
  20336. fallbacks.addFallback(1, "FOG");
  20337. }
  20338. if (this._defines.POINTSIZE) {
  20339. fallbacks.addFallback(0, "POINTSIZE");
  20340. }
  20341. if (this._defines.LOGARITHMICDEPTH) {
  20342. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20343. }
  20344. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20345. if (this._defines.SPECULARTERM) {
  20346. fallbacks.addFallback(0, "SPECULARTERM");
  20347. }
  20348. if (this._defines.DIFFUSEFRESNEL) {
  20349. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20350. }
  20351. if (this._defines.OPACITYFRESNEL) {
  20352. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20353. }
  20354. if (this._defines.REFLECTIONFRESNEL) {
  20355. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20356. }
  20357. if (this._defines.EMISSIVEFRESNEL) {
  20358. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20359. }
  20360. if (this._defines.FRESNEL) {
  20361. fallbacks.addFallback(4, "FRESNEL");
  20362. }
  20363. //Attributes
  20364. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20365. if (this._defines.NORMAL) {
  20366. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20367. }
  20368. if (this._defines.UV1) {
  20369. attribs.push(BABYLON.VertexBuffer.UVKind);
  20370. }
  20371. if (this._defines.UV2) {
  20372. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20373. }
  20374. if (this._defines.VERTEXCOLOR) {
  20375. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20376. }
  20377. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20378. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20379. // Legacy browser patch
  20380. var shaderName = "default";
  20381. if (!scene.getEngine().getCaps().standardDerivatives) {
  20382. shaderName = "legacydefault";
  20383. }
  20384. var join = this._defines.toString();
  20385. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20386. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20387. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20388. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20389. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20390. "vFogInfos", "vFogColor", "pointSize",
  20391. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20392. "mBones",
  20393. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20394. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20395. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20396. "logarithmicDepthConstant"
  20397. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20398. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20399. ], join, fallbacks, this.onCompiled, this.onError);
  20400. }
  20401. if (!this._effect.isReady()) {
  20402. return false;
  20403. }
  20404. this._renderId = scene.getRenderId();
  20405. this._wasPreviouslyReady = true;
  20406. if (mesh) {
  20407. if (!mesh._materialDefines) {
  20408. mesh._materialDefines = new StandardMaterialDefines();
  20409. }
  20410. this._defines.cloneTo(mesh._materialDefines);
  20411. }
  20412. return true;
  20413. };
  20414. StandardMaterial.prototype.unbind = function () {
  20415. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20416. this._effect.setTexture("reflection2DSampler", null);
  20417. }
  20418. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20419. this._effect.setTexture("refraction2DSampler", null);
  20420. }
  20421. _super.prototype.unbind.call(this);
  20422. };
  20423. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20424. this._effect.setMatrix("world", world);
  20425. };
  20426. StandardMaterial.prototype.bind = function (world, mesh) {
  20427. var scene = this.getScene();
  20428. // Matrices
  20429. this.bindOnlyWorldMatrix(world);
  20430. // Bones
  20431. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20432. if (scene.getCachedMaterial() !== this) {
  20433. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20434. if (StandardMaterial.FresnelEnabled) {
  20435. // Fresnel
  20436. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20437. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20438. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20439. }
  20440. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20441. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20442. }
  20443. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20444. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20445. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20446. }
  20447. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20448. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20449. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20450. }
  20451. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20452. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20453. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20454. }
  20455. }
  20456. // Textures
  20457. if (scene.texturesEnabled) {
  20458. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20459. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20460. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20461. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20462. }
  20463. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20464. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20465. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20466. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20467. }
  20468. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20469. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20470. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20471. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20472. }
  20473. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20474. if (this.reflectionTexture.isCube) {
  20475. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20476. }
  20477. else {
  20478. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20479. }
  20480. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20481. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20482. }
  20483. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20484. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20485. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20486. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20487. }
  20488. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20489. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20490. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20491. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20492. }
  20493. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20494. this._effect.setTexture("specularSampler", this.specularTexture);
  20495. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20496. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20497. }
  20498. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20499. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20500. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20501. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20502. }
  20503. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20504. var depth = 1.0;
  20505. if (this.refractionTexture.isCube) {
  20506. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20507. }
  20508. else {
  20509. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20510. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20511. if (this.refractionTexture.depth) {
  20512. depth = this.refractionTexture.depth;
  20513. }
  20514. }
  20515. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20516. }
  20517. }
  20518. // Clip plane
  20519. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20520. // Point size
  20521. if (this.pointsCloud) {
  20522. this._effect.setFloat("pointSize", this.pointSize);
  20523. }
  20524. // Colors
  20525. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20526. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20527. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20528. if (this._defines.SPECULARTERM) {
  20529. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20530. }
  20531. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20532. }
  20533. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20534. // Diffuse
  20535. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20536. // Lights
  20537. if (scene.lightsEnabled && !this.disableLighting) {
  20538. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20539. }
  20540. // View
  20541. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20542. this._effect.setMatrix("view", scene.getViewMatrix());
  20543. }
  20544. // Fog
  20545. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20546. // Log. depth
  20547. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20548. }
  20549. _super.prototype.bind.call(this, world, mesh);
  20550. };
  20551. StandardMaterial.prototype.getAnimatables = function () {
  20552. var results = [];
  20553. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20554. results.push(this.diffuseTexture);
  20555. }
  20556. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20557. results.push(this.ambientTexture);
  20558. }
  20559. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20560. results.push(this.opacityTexture);
  20561. }
  20562. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20563. results.push(this.reflectionTexture);
  20564. }
  20565. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20566. results.push(this.emissiveTexture);
  20567. }
  20568. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20569. results.push(this.specularTexture);
  20570. }
  20571. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20572. results.push(this.bumpTexture);
  20573. }
  20574. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20575. results.push(this.lightmapTexture);
  20576. }
  20577. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20578. results.push(this.refractionTexture);
  20579. }
  20580. return results;
  20581. };
  20582. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20583. if (this.diffuseTexture) {
  20584. this.diffuseTexture.dispose();
  20585. }
  20586. if (this.ambientTexture) {
  20587. this.ambientTexture.dispose();
  20588. }
  20589. if (this.opacityTexture) {
  20590. this.opacityTexture.dispose();
  20591. }
  20592. if (this.reflectionTexture) {
  20593. this.reflectionTexture.dispose();
  20594. }
  20595. if (this.emissiveTexture) {
  20596. this.emissiveTexture.dispose();
  20597. }
  20598. if (this.specularTexture) {
  20599. this.specularTexture.dispose();
  20600. }
  20601. if (this.bumpTexture) {
  20602. this.bumpTexture.dispose();
  20603. }
  20604. if (this.lightmapTexture) {
  20605. this.lightmapTexture.dispose();
  20606. }
  20607. if (this.refractionTexture) {
  20608. this.refractionTexture.dispose();
  20609. }
  20610. _super.prototype.dispose.call(this, forceDisposeEffect);
  20611. };
  20612. StandardMaterial.prototype.clone = function (name) {
  20613. var _this = this;
  20614. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20615. };
  20616. StandardMaterial.prototype.serialize = function () {
  20617. return BABYLON.SerializationHelper.Serialize(this);
  20618. };
  20619. // Statics
  20620. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20621. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20622. };
  20623. // Flags used to enable or disable a type of texture for all Standard Materials
  20624. StandardMaterial.DiffuseTextureEnabled = true;
  20625. StandardMaterial.AmbientTextureEnabled = true;
  20626. StandardMaterial.OpacityTextureEnabled = true;
  20627. StandardMaterial.ReflectionTextureEnabled = true;
  20628. StandardMaterial.EmissiveTextureEnabled = true;
  20629. StandardMaterial.SpecularTextureEnabled = true;
  20630. StandardMaterial.BumpTextureEnabled = true;
  20631. StandardMaterial.FresnelEnabled = true;
  20632. StandardMaterial.LightmapTextureEnabled = true;
  20633. StandardMaterial.RefractionTextureEnabled = true;
  20634. __decorate([
  20635. BABYLON.serializeAsTexture()
  20636. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20637. __decorate([
  20638. BABYLON.serializeAsTexture()
  20639. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20640. __decorate([
  20641. BABYLON.serializeAsTexture()
  20642. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20643. __decorate([
  20644. BABYLON.serializeAsTexture()
  20645. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20646. __decorate([
  20647. BABYLON.serializeAsTexture()
  20648. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20649. __decorate([
  20650. BABYLON.serializeAsTexture()
  20651. ], StandardMaterial.prototype, "specularTexture", void 0);
  20652. __decorate([
  20653. BABYLON.serializeAsTexture()
  20654. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20655. __decorate([
  20656. BABYLON.serializeAsTexture()
  20657. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20658. __decorate([
  20659. BABYLON.serializeAsTexture()
  20660. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20661. __decorate([
  20662. BABYLON.serializeAsColor3("ambient")
  20663. ], StandardMaterial.prototype, "ambientColor", void 0);
  20664. __decorate([
  20665. BABYLON.serializeAsColor3("diffuse")
  20666. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20667. __decorate([
  20668. BABYLON.serializeAsColor3("specular")
  20669. ], StandardMaterial.prototype, "specularColor", void 0);
  20670. __decorate([
  20671. BABYLON.serializeAsColor3("emissive")
  20672. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20673. __decorate([
  20674. BABYLON.serialize()
  20675. ], StandardMaterial.prototype, "specularPower", void 0);
  20676. __decorate([
  20677. BABYLON.serialize()
  20678. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20679. __decorate([
  20680. BABYLON.serialize()
  20681. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20682. __decorate([
  20683. BABYLON.serialize()
  20684. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20685. __decorate([
  20686. BABYLON.serialize()
  20687. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20688. __decorate([
  20689. BABYLON.serialize()
  20690. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20691. __decorate([
  20692. BABYLON.serialize()
  20693. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20694. __decorate([
  20695. BABYLON.serialize()
  20696. ], StandardMaterial.prototype, "disableLighting", void 0);
  20697. __decorate([
  20698. BABYLON.serialize()
  20699. ], StandardMaterial.prototype, "roughness", void 0);
  20700. __decorate([
  20701. BABYLON.serialize()
  20702. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20703. __decorate([
  20704. BABYLON.serialize()
  20705. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20706. __decorate([
  20707. BABYLON.serialize()
  20708. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20709. __decorate([
  20710. BABYLON.serializeAsFresnelParameters()
  20711. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20712. __decorate([
  20713. BABYLON.serializeAsFresnelParameters()
  20714. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20715. __decorate([
  20716. BABYLON.serializeAsFresnelParameters()
  20717. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20718. __decorate([
  20719. BABYLON.serializeAsFresnelParameters()
  20720. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20721. __decorate([
  20722. BABYLON.serializeAsFresnelParameters()
  20723. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20724. __decorate([
  20725. BABYLON.serialize()
  20726. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20727. __decorate([
  20728. BABYLON.serialize()
  20729. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20730. return StandardMaterial;
  20731. })(BABYLON.Material);
  20732. BABYLON.StandardMaterial = StandardMaterial;
  20733. })(BABYLON || (BABYLON = {}));
  20734. var BABYLON;
  20735. (function (BABYLON) {
  20736. var MultiMaterial = (function (_super) {
  20737. __extends(MultiMaterial, _super);
  20738. function MultiMaterial(name, scene) {
  20739. _super.call(this, name, scene, true);
  20740. this.subMaterials = new Array();
  20741. scene.multiMaterials.push(this);
  20742. }
  20743. // Properties
  20744. MultiMaterial.prototype.getSubMaterial = function (index) {
  20745. if (index < 0 || index >= this.subMaterials.length) {
  20746. return this.getScene().defaultMaterial;
  20747. }
  20748. return this.subMaterials[index];
  20749. };
  20750. // Methods
  20751. MultiMaterial.prototype.isReady = function (mesh) {
  20752. for (var index = 0; index < this.subMaterials.length; index++) {
  20753. var subMaterial = this.subMaterials[index];
  20754. if (subMaterial) {
  20755. if (!this.subMaterials[index].isReady(mesh)) {
  20756. return false;
  20757. }
  20758. }
  20759. }
  20760. return true;
  20761. };
  20762. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20763. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20764. for (var index = 0; index < this.subMaterials.length; index++) {
  20765. var subMaterial = null;
  20766. if (cloneChildren) {
  20767. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20768. }
  20769. else {
  20770. subMaterial = this.subMaterials[index];
  20771. }
  20772. newMultiMaterial.subMaterials.push(subMaterial);
  20773. }
  20774. return newMultiMaterial;
  20775. };
  20776. MultiMaterial.prototype.serialize = function () {
  20777. var serializationObject = {};
  20778. serializationObject.name = this.name;
  20779. serializationObject.id = this.id;
  20780. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20781. serializationObject.materials = [];
  20782. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20783. var subMat = this.subMaterials[matIndex];
  20784. if (subMat) {
  20785. serializationObject.materials.push(subMat.id);
  20786. }
  20787. else {
  20788. serializationObject.materials.push(null);
  20789. }
  20790. }
  20791. return serializationObject;
  20792. };
  20793. return MultiMaterial;
  20794. })(BABYLON.Material);
  20795. BABYLON.MultiMaterial = MultiMaterial;
  20796. })(BABYLON || (BABYLON = {}));
  20797. var BABYLON;
  20798. (function (BABYLON) {
  20799. var SceneLoader = (function () {
  20800. function SceneLoader() {
  20801. }
  20802. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20803. get: function () {
  20804. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20805. },
  20806. set: function (value) {
  20807. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20808. },
  20809. enumerable: true,
  20810. configurable: true
  20811. });
  20812. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20813. get: function () {
  20814. return SceneLoader._ShowLoadingScreen;
  20815. },
  20816. set: function (value) {
  20817. SceneLoader._ShowLoadingScreen = value;
  20818. },
  20819. enumerable: true,
  20820. configurable: true
  20821. });
  20822. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20823. var dotPosition = sceneFilename.lastIndexOf(".");
  20824. var queryStringPosition = sceneFilename.indexOf("?");
  20825. if (queryStringPosition === -1) {
  20826. queryStringPosition = sceneFilename.length;
  20827. }
  20828. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20829. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20830. var plugin = this._registeredPlugins[index];
  20831. if (plugin.extensions.indexOf(extension) !== -1) {
  20832. return plugin;
  20833. }
  20834. }
  20835. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20836. };
  20837. // Public functions
  20838. SceneLoader.GetPluginForExtension = function (extension) {
  20839. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20840. var plugin = this._registeredPlugins[index];
  20841. if (plugin.extensions.indexOf(extension) !== -1) {
  20842. return plugin;
  20843. }
  20844. }
  20845. return null;
  20846. };
  20847. SceneLoader.RegisterPlugin = function (plugin) {
  20848. plugin.extensions = plugin.extensions.toLowerCase();
  20849. SceneLoader._registeredPlugins.push(plugin);
  20850. };
  20851. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20852. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20853. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20854. return;
  20855. }
  20856. var loadingToken = {};
  20857. scene._addPendingData(loadingToken);
  20858. var manifestChecked = function (success) {
  20859. scene.database = database;
  20860. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20861. var importMeshFromData = function (data) {
  20862. var meshes = [];
  20863. var particleSystems = [];
  20864. var skeletons = [];
  20865. try {
  20866. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20867. if (onerror) {
  20868. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20869. }
  20870. scene._removePendingData(loadingToken);
  20871. return;
  20872. }
  20873. }
  20874. catch (e) {
  20875. if (onerror) {
  20876. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20877. }
  20878. scene._removePendingData(loadingToken);
  20879. return;
  20880. }
  20881. if (onsuccess) {
  20882. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20883. onsuccess(meshes, particleSystems, skeletons);
  20884. scene._removePendingData(loadingToken);
  20885. }
  20886. };
  20887. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20888. // Direct load
  20889. importMeshFromData(sceneFilename.substr(5));
  20890. return;
  20891. }
  20892. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20893. importMeshFromData(data);
  20894. }, progressCallBack, database);
  20895. };
  20896. if (scene.getEngine().enableOfflineSupport) {
  20897. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20898. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20899. }
  20900. else {
  20901. manifestChecked(true);
  20902. }
  20903. };
  20904. /**
  20905. * Load a scene
  20906. * @param rootUrl a string that defines the root url for scene and resources
  20907. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20908. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20909. */
  20910. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20911. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20912. };
  20913. /**
  20914. * Append a scene
  20915. * @param rootUrl a string that defines the root url for scene and resources
  20916. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20917. * @param scene is the instance of BABYLON.Scene to append to
  20918. */
  20919. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20920. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20921. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20922. return;
  20923. }
  20924. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20925. var database;
  20926. var loadingToken = {};
  20927. scene._addPendingData(loadingToken);
  20928. if (SceneLoader.ShowLoadingScreen) {
  20929. scene.getEngine().displayLoadingUI();
  20930. }
  20931. var loadSceneFromData = function (data) {
  20932. scene.database = database;
  20933. if (!plugin.load(scene, data, rootUrl)) {
  20934. if (onerror) {
  20935. onerror(scene);
  20936. }
  20937. scene._removePendingData(loadingToken);
  20938. scene.getEngine().hideLoadingUI();
  20939. return;
  20940. }
  20941. if (onsuccess) {
  20942. onsuccess(scene);
  20943. }
  20944. scene._removePendingData(loadingToken);
  20945. if (SceneLoader.ShowLoadingScreen) {
  20946. scene.executeWhenReady(function () {
  20947. scene.getEngine().hideLoadingUI();
  20948. });
  20949. }
  20950. };
  20951. var manifestChecked = function (success) {
  20952. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20953. };
  20954. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20955. // Direct load
  20956. loadSceneFromData(sceneFilename.substr(5));
  20957. return;
  20958. }
  20959. if (rootUrl.indexOf("file:") === -1) {
  20960. if (scene.getEngine().enableOfflineSupport) {
  20961. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20962. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20963. }
  20964. else {
  20965. manifestChecked(true);
  20966. }
  20967. }
  20968. else {
  20969. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20970. }
  20971. };
  20972. // Flags
  20973. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20974. SceneLoader._ShowLoadingScreen = true;
  20975. // Members
  20976. SceneLoader._registeredPlugins = new Array();
  20977. return SceneLoader;
  20978. })();
  20979. BABYLON.SceneLoader = SceneLoader;
  20980. ;
  20981. })(BABYLON || (BABYLON = {}));
  20982. var BABYLON;
  20983. (function (BABYLON) {
  20984. var Internals;
  20985. (function (Internals) {
  20986. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20987. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20988. var parsedMaterial = parsedData.materials[index];
  20989. if (parsedMaterial.id === id) {
  20990. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20991. }
  20992. }
  20993. return null;
  20994. };
  20995. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20996. names = (names instanceof Array) ? names : [names];
  20997. for (var i in names) {
  20998. if (mesh.name === names[i]) {
  20999. hierarchyIds.push(mesh.id);
  21000. return true;
  21001. }
  21002. }
  21003. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21004. hierarchyIds.push(mesh.id);
  21005. return true;
  21006. }
  21007. return false;
  21008. };
  21009. BABYLON.SceneLoader.RegisterPlugin({
  21010. extensions: ".babylon",
  21011. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21012. var parsedData = JSON.parse(data);
  21013. var loadedSkeletonsIds = [];
  21014. var loadedMaterialsIds = [];
  21015. var hierarchyIds = [];
  21016. var index;
  21017. var cache;
  21018. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21019. var parsedMesh = parsedData.meshes[index];
  21020. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21021. if (meshesNames instanceof Array) {
  21022. // Remove found mesh name from list.
  21023. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21024. }
  21025. //Geometry?
  21026. if (parsedMesh.geometryId) {
  21027. //does the file contain geometries?
  21028. if (parsedData.geometries) {
  21029. //find the correct geometry and add it to the scene
  21030. var found = false;
  21031. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21032. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21033. return;
  21034. }
  21035. else {
  21036. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21037. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21038. switch (geometryType) {
  21039. case "boxes":
  21040. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21041. break;
  21042. case "spheres":
  21043. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21044. break;
  21045. case "cylinders":
  21046. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21047. break;
  21048. case "toruses":
  21049. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21050. break;
  21051. case "grounds":
  21052. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21053. break;
  21054. case "planes":
  21055. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21056. break;
  21057. case "torusKnots":
  21058. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21059. break;
  21060. case "vertexData":
  21061. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21062. break;
  21063. }
  21064. found = true;
  21065. }
  21066. });
  21067. }
  21068. });
  21069. if (!found) {
  21070. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21071. }
  21072. }
  21073. }
  21074. // Material ?
  21075. if (parsedMesh.materialId) {
  21076. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21077. if (!materialFound && parsedData.multiMaterials) {
  21078. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21079. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21080. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21081. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21082. var subMatId = parsedMultiMaterial.materials[matIndex];
  21083. loadedMaterialsIds.push(subMatId);
  21084. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21085. }
  21086. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21087. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21088. materialFound = true;
  21089. break;
  21090. }
  21091. }
  21092. }
  21093. if (!materialFound) {
  21094. loadedMaterialsIds.push(parsedMesh.materialId);
  21095. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21096. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21097. }
  21098. }
  21099. }
  21100. // Skeleton ?
  21101. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21102. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21103. if (!skeletonAlreadyLoaded) {
  21104. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21105. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21106. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21107. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21108. loadedSkeletonsIds.push(parsedSkeleton.id);
  21109. }
  21110. }
  21111. }
  21112. }
  21113. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21114. meshes.push(mesh);
  21115. }
  21116. }
  21117. // Connecting parents
  21118. var currentMesh;
  21119. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21120. currentMesh = scene.meshes[index];
  21121. if (currentMesh._waitingParentId) {
  21122. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21123. currentMesh._waitingParentId = undefined;
  21124. }
  21125. }
  21126. // freeze and compute world matrix application
  21127. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21128. currentMesh = scene.meshes[index];
  21129. if (currentMesh._waitingFreezeWorldMatrix) {
  21130. currentMesh.freezeWorldMatrix();
  21131. currentMesh._waitingFreezeWorldMatrix = undefined;
  21132. }
  21133. else {
  21134. currentMesh.computeWorldMatrix(true);
  21135. }
  21136. }
  21137. // Particles
  21138. if (parsedData.particleSystems) {
  21139. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21140. var parsedParticleSystem = parsedData.particleSystems[index];
  21141. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21142. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21143. }
  21144. }
  21145. }
  21146. return true;
  21147. },
  21148. load: function (scene, data, rootUrl) {
  21149. var parsedData = JSON.parse(data);
  21150. // Scene
  21151. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21152. scene.autoClear = parsedData.autoClear;
  21153. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21154. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21155. if (parsedData.gravity) {
  21156. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21157. }
  21158. // Fog
  21159. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21160. scene.fogMode = parsedData.fogMode;
  21161. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21162. scene.fogStart = parsedData.fogStart;
  21163. scene.fogEnd = parsedData.fogEnd;
  21164. scene.fogDensity = parsedData.fogDensity;
  21165. }
  21166. //Physics
  21167. if (parsedData.physicsEnabled) {
  21168. var physicsPlugin;
  21169. if (parsedData.physicsEngine === "cannon") {
  21170. physicsPlugin = new BABYLON.CannonJSPlugin();
  21171. }
  21172. else if (parsedData.physicsEngine === "oimo") {
  21173. physicsPlugin = new BABYLON.OimoJSPlugin();
  21174. }
  21175. //else - default engine, which is currently oimo
  21176. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21177. scene.enablePhysics(physicsGravity, physicsPlugin);
  21178. }
  21179. //collisions, if defined. otherwise, default is true
  21180. if (parsedData.collisionsEnabled != undefined) {
  21181. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21182. }
  21183. scene.workerCollisions = !!parsedData.workerCollisions;
  21184. var index;
  21185. var cache;
  21186. // Lights
  21187. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21188. var parsedLight = parsedData.lights[index];
  21189. BABYLON.Light.Parse(parsedLight, scene);
  21190. }
  21191. // Animations
  21192. if (parsedData.animations) {
  21193. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21194. var parsedAnimation = parsedData.animations[index];
  21195. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21196. }
  21197. }
  21198. // Materials
  21199. if (parsedData.materials) {
  21200. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21201. var parsedMaterial = parsedData.materials[index];
  21202. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21203. }
  21204. }
  21205. if (parsedData.multiMaterials) {
  21206. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21207. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21208. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21209. }
  21210. }
  21211. // Skeletons
  21212. if (parsedData.skeletons) {
  21213. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21214. var parsedSkeleton = parsedData.skeletons[index];
  21215. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21216. }
  21217. }
  21218. // Geometries
  21219. var geometries = parsedData.geometries;
  21220. if (geometries) {
  21221. // Boxes
  21222. var boxes = geometries.boxes;
  21223. if (boxes) {
  21224. for (index = 0, cache = boxes.length; index < cache; index++) {
  21225. var parsedBox = boxes[index];
  21226. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21227. }
  21228. }
  21229. // Spheres
  21230. var spheres = geometries.spheres;
  21231. if (spheres) {
  21232. for (index = 0, cache = spheres.length; index < cache; index++) {
  21233. var parsedSphere = spheres[index];
  21234. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21235. }
  21236. }
  21237. // Cylinders
  21238. var cylinders = geometries.cylinders;
  21239. if (cylinders) {
  21240. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21241. var parsedCylinder = cylinders[index];
  21242. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21243. }
  21244. }
  21245. // Toruses
  21246. var toruses = geometries.toruses;
  21247. if (toruses) {
  21248. for (index = 0, cache = toruses.length; index < cache; index++) {
  21249. var parsedTorus = toruses[index];
  21250. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21251. }
  21252. }
  21253. // Grounds
  21254. var grounds = geometries.grounds;
  21255. if (grounds) {
  21256. for (index = 0, cache = grounds.length; index < cache; index++) {
  21257. var parsedGround = grounds[index];
  21258. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21259. }
  21260. }
  21261. // Planes
  21262. var planes = geometries.planes;
  21263. if (planes) {
  21264. for (index = 0, cache = planes.length; index < cache; index++) {
  21265. var parsedPlane = planes[index];
  21266. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21267. }
  21268. }
  21269. // TorusKnots
  21270. var torusKnots = geometries.torusKnots;
  21271. if (torusKnots) {
  21272. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21273. var parsedTorusKnot = torusKnots[index];
  21274. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21275. }
  21276. }
  21277. // VertexData
  21278. var vertexData = geometries.vertexData;
  21279. if (vertexData) {
  21280. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21281. var parsedVertexData = vertexData[index];
  21282. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21283. }
  21284. }
  21285. }
  21286. // Meshes
  21287. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21288. var parsedMesh = parsedData.meshes[index];
  21289. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21290. }
  21291. // Cameras
  21292. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21293. var parsedCamera = parsedData.cameras[index];
  21294. BABYLON.Camera.Parse(parsedCamera, scene);
  21295. }
  21296. if (parsedData.activeCameraID) {
  21297. scene.setActiveCameraByID(parsedData.activeCameraID);
  21298. }
  21299. // Browsing all the graph to connect the dots
  21300. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21301. var camera = scene.cameras[index];
  21302. if (camera._waitingParentId) {
  21303. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21304. camera._waitingParentId = undefined;
  21305. }
  21306. }
  21307. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21308. var light = scene.lights[index];
  21309. if (light._waitingParentId) {
  21310. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21311. light._waitingParentId = undefined;
  21312. }
  21313. }
  21314. // Sounds
  21315. var loadedSounds = [];
  21316. var loadedSound;
  21317. if (BABYLON.AudioEngine && parsedData.sounds) {
  21318. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21319. var parsedSound = parsedData.sounds[index];
  21320. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21321. if (!parsedSound.url)
  21322. parsedSound.url = parsedSound.name;
  21323. if (!loadedSounds[parsedSound.url]) {
  21324. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21325. loadedSounds[parsedSound.url] = loadedSound;
  21326. }
  21327. else {
  21328. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21329. }
  21330. }
  21331. else {
  21332. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21333. }
  21334. }
  21335. }
  21336. loadedSounds = [];
  21337. // Connect parents & children and parse actions
  21338. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21339. var mesh = scene.meshes[index];
  21340. if (mesh._waitingParentId) {
  21341. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21342. mesh._waitingParentId = undefined;
  21343. }
  21344. if (mesh._waitingActions) {
  21345. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21346. mesh._waitingActions = undefined;
  21347. }
  21348. }
  21349. // freeze world matrix application
  21350. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21351. var currentMesh = scene.meshes[index];
  21352. if (currentMesh._waitingFreezeWorldMatrix) {
  21353. currentMesh.freezeWorldMatrix();
  21354. currentMesh._waitingFreezeWorldMatrix = undefined;
  21355. }
  21356. else {
  21357. currentMesh.computeWorldMatrix(true);
  21358. }
  21359. }
  21360. // Particles Systems
  21361. if (parsedData.particleSystems) {
  21362. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21363. var parsedParticleSystem = parsedData.particleSystems[index];
  21364. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21365. }
  21366. }
  21367. // Lens flares
  21368. if (parsedData.lensFlareSystems) {
  21369. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21370. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21371. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21372. }
  21373. }
  21374. // Shadows
  21375. if (parsedData.shadowGenerators) {
  21376. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21377. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21378. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21379. }
  21380. }
  21381. // Actions (scene)
  21382. if (parsedData.actions) {
  21383. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21384. }
  21385. // Finish
  21386. return true;
  21387. }
  21388. });
  21389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21390. })(BABYLON || (BABYLON = {}));
  21391. var BABYLON;
  21392. (function (BABYLON) {
  21393. var SpriteManager = (function () {
  21394. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21396. this.name = name;
  21397. this.cellSize = cellSize;
  21398. this.sprites = new Array();
  21399. this.renderingGroupId = 0;
  21400. this.layerMask = 0x0FFFFFFF;
  21401. this.fogEnabled = true;
  21402. this.isPickable = false;
  21403. this._vertexDeclaration = [4, 4, 4, 4];
  21404. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21405. this._capacity = capacity;
  21406. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21407. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21408. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21409. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21410. this._scene = scene;
  21411. this._scene.spriteManagers.push(this);
  21412. // VBO
  21413. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21414. var indices = [];
  21415. var index = 0;
  21416. for (var count = 0; count < capacity; count++) {
  21417. indices.push(index);
  21418. indices.push(index + 1);
  21419. indices.push(index + 2);
  21420. indices.push(index);
  21421. indices.push(index + 2);
  21422. indices.push(index + 3);
  21423. index += 4;
  21424. }
  21425. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21426. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21427. // Effects
  21428. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21429. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21430. }
  21431. Object.defineProperty(SpriteManager.prototype, "texture", {
  21432. get: function () {
  21433. return this._spriteTexture;
  21434. },
  21435. set: function (value) {
  21436. this._spriteTexture = value;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21442. var arrayOffset = index * 16;
  21443. if (offsetX === 0)
  21444. offsetX = this._epsilon;
  21445. else if (offsetX === 1)
  21446. offsetX = 1 - this._epsilon;
  21447. if (offsetY === 0)
  21448. offsetY = this._epsilon;
  21449. else if (offsetY === 1)
  21450. offsetY = 1 - this._epsilon;
  21451. this._vertices[arrayOffset] = sprite.position.x;
  21452. this._vertices[arrayOffset + 1] = sprite.position.y;
  21453. this._vertices[arrayOffset + 2] = sprite.position.z;
  21454. this._vertices[arrayOffset + 3] = sprite.angle;
  21455. this._vertices[arrayOffset + 4] = sprite.width;
  21456. this._vertices[arrayOffset + 5] = sprite.height;
  21457. this._vertices[arrayOffset + 6] = offsetX;
  21458. this._vertices[arrayOffset + 7] = offsetY;
  21459. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21460. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21461. var offset = (sprite.cellIndex / rowSize) >> 0;
  21462. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21463. this._vertices[arrayOffset + 11] = offset;
  21464. // Color
  21465. this._vertices[arrayOffset + 12] = sprite.color.r;
  21466. this._vertices[arrayOffset + 13] = sprite.color.g;
  21467. this._vertices[arrayOffset + 14] = sprite.color.b;
  21468. this._vertices[arrayOffset + 15] = sprite.color.a;
  21469. };
  21470. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21471. var count = Math.min(this._capacity, this.sprites.length);
  21472. var min = BABYLON.Vector3.Zero();
  21473. var max = BABYLON.Vector3.Zero();
  21474. var distance = Number.MAX_VALUE;
  21475. var currentSprite;
  21476. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21477. var cameraView = camera.getViewMatrix();
  21478. for (var index = 0; index < count; index++) {
  21479. var sprite = this.sprites[index];
  21480. if (!sprite) {
  21481. continue;
  21482. }
  21483. if (predicate) {
  21484. if (!predicate(sprite)) {
  21485. continue;
  21486. }
  21487. }
  21488. else if (!sprite.isPickable) {
  21489. continue;
  21490. }
  21491. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21492. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21493. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21494. if (ray.intersectsBoxMinMax(min, max)) {
  21495. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21496. if (distance > currentDistance) {
  21497. distance = currentDistance;
  21498. currentSprite = sprite;
  21499. if (fastCheck) {
  21500. break;
  21501. }
  21502. }
  21503. }
  21504. }
  21505. if (currentSprite) {
  21506. var result = new BABYLON.PickingInfo();
  21507. result.hit = true;
  21508. result.pickedSprite = currentSprite;
  21509. result.distance = distance;
  21510. return result;
  21511. }
  21512. return null;
  21513. };
  21514. SpriteManager.prototype.render = function () {
  21515. // Check
  21516. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21517. return;
  21518. var engine = this._scene.getEngine();
  21519. var baseSize = this._spriteTexture.getBaseSize();
  21520. // Sprites
  21521. var deltaTime = engine.getDeltaTime();
  21522. var max = Math.min(this._capacity, this.sprites.length);
  21523. var rowSize = baseSize.width / this.cellSize;
  21524. var offset = 0;
  21525. for (var index = 0; index < max; index++) {
  21526. var sprite = this.sprites[index];
  21527. if (!sprite) {
  21528. continue;
  21529. }
  21530. sprite._animate(deltaTime);
  21531. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21532. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21533. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21534. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21535. }
  21536. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21537. // Render
  21538. var effect = this._effectBase;
  21539. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21540. effect = this._effectFog;
  21541. }
  21542. engine.enableEffect(effect);
  21543. var viewMatrix = this._scene.getViewMatrix();
  21544. effect.setTexture("diffuseSampler", this._spriteTexture);
  21545. effect.setMatrix("view", viewMatrix);
  21546. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21547. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21548. // Fog
  21549. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21550. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21551. effect.setColor3("vFogColor", this._scene.fogColor);
  21552. }
  21553. // VBOs
  21554. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21555. // Draw order
  21556. engine.setDepthFunctionToLessOrEqual();
  21557. effect.setBool("alphaTest", true);
  21558. engine.setColorWrite(false);
  21559. engine.draw(true, 0, max * 6);
  21560. engine.setColorWrite(true);
  21561. effect.setBool("alphaTest", false);
  21562. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21563. engine.draw(true, 0, max * 6);
  21564. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21565. };
  21566. SpriteManager.prototype.dispose = function () {
  21567. if (this._vertexBuffer) {
  21568. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21569. this._vertexBuffer = null;
  21570. }
  21571. if (this._indexBuffer) {
  21572. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21573. this._indexBuffer = null;
  21574. }
  21575. if (this._spriteTexture) {
  21576. this._spriteTexture.dispose();
  21577. this._spriteTexture = null;
  21578. }
  21579. // Remove from scene
  21580. var index = this._scene.spriteManagers.indexOf(this);
  21581. this._scene.spriteManagers.splice(index, 1);
  21582. // Callback
  21583. if (this.onDispose) {
  21584. this.onDispose();
  21585. }
  21586. };
  21587. return SpriteManager;
  21588. })();
  21589. BABYLON.SpriteManager = SpriteManager;
  21590. })(BABYLON || (BABYLON = {}));
  21591. var BABYLON;
  21592. (function (BABYLON) {
  21593. var Sprite = (function () {
  21594. function Sprite(name, manager) {
  21595. this.name = name;
  21596. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21597. this.width = 1.0;
  21598. this.height = 1.0;
  21599. this.angle = 0;
  21600. this.cellIndex = 0;
  21601. this.invertU = 0;
  21602. this.invertV = 0;
  21603. this.animations = new Array();
  21604. this.isPickable = false;
  21605. this._animationStarted = false;
  21606. this._loopAnimation = false;
  21607. this._fromIndex = 0;
  21608. this._toIndex = 0;
  21609. this._delay = 0;
  21610. this._direction = 1;
  21611. this._frameCount = 0;
  21612. this._time = 0;
  21613. this._manager = manager;
  21614. this._manager.sprites.push(this);
  21615. this.position = BABYLON.Vector3.Zero();
  21616. }
  21617. Object.defineProperty(Sprite.prototype, "size", {
  21618. get: function () {
  21619. return this.width;
  21620. },
  21621. set: function (value) {
  21622. this.width = value;
  21623. this.height = value;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21629. this._fromIndex = from;
  21630. this._toIndex = to;
  21631. this._loopAnimation = loop;
  21632. this._delay = delay;
  21633. this._animationStarted = true;
  21634. this._direction = from < to ? 1 : -1;
  21635. this.cellIndex = from;
  21636. this._time = 0;
  21637. };
  21638. Sprite.prototype.stopAnimation = function () {
  21639. this._animationStarted = false;
  21640. };
  21641. Sprite.prototype._animate = function (deltaTime) {
  21642. if (!this._animationStarted)
  21643. return;
  21644. this._time += deltaTime;
  21645. if (this._time > this._delay) {
  21646. this._time = this._time % this._delay;
  21647. this.cellIndex += this._direction;
  21648. if (this.cellIndex == this._toIndex) {
  21649. if (this._loopAnimation) {
  21650. this.cellIndex = this._fromIndex;
  21651. }
  21652. else {
  21653. this._animationStarted = false;
  21654. if (this.disposeWhenFinishedAnimating) {
  21655. this.dispose();
  21656. }
  21657. }
  21658. }
  21659. }
  21660. };
  21661. Sprite.prototype.dispose = function () {
  21662. for (var i = 0; i < this._manager.sprites.length; i++) {
  21663. if (this._manager.sprites[i] == this) {
  21664. this._manager.sprites.splice(i, 1);
  21665. }
  21666. }
  21667. };
  21668. return Sprite;
  21669. })();
  21670. BABYLON.Sprite = Sprite;
  21671. })(BABYLON || (BABYLON = {}));
  21672. var BABYLON;
  21673. (function (BABYLON) {
  21674. var Layer = (function () {
  21675. function Layer(name, imgUrl, scene, isBackground, color) {
  21676. this.name = name;
  21677. this.scale = new BABYLON.Vector2(1, 1);
  21678. this.offset = new BABYLON.Vector2(0, 0);
  21679. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21680. this._vertexDeclaration = [2];
  21681. this._vertexStrideSize = 2 * 4;
  21682. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21683. this.isBackground = isBackground === undefined ? true : isBackground;
  21684. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21685. this._scene = scene;
  21686. this._scene.layers.push(this);
  21687. // VBO
  21688. var vertices = [];
  21689. vertices.push(1, 1);
  21690. vertices.push(-1, 1);
  21691. vertices.push(-1, -1);
  21692. vertices.push(1, -1);
  21693. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21694. // Indices
  21695. var indices = [];
  21696. indices.push(0);
  21697. indices.push(1);
  21698. indices.push(2);
  21699. indices.push(0);
  21700. indices.push(2);
  21701. indices.push(3);
  21702. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21703. // Effects
  21704. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21705. }
  21706. Layer.prototype.render = function () {
  21707. // Check
  21708. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21709. return;
  21710. var engine = this._scene.getEngine();
  21711. // Render
  21712. engine.enableEffect(this._effect);
  21713. engine.setState(false);
  21714. // Texture
  21715. this._effect.setTexture("textureSampler", this.texture);
  21716. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21717. // Color
  21718. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21719. // Scale / offset
  21720. this._effect.setVector2("offset", this.offset);
  21721. this._effect.setVector2("scale", this.scale);
  21722. // VBOs
  21723. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21724. // Draw order
  21725. engine.setAlphaMode(this.alphaBlendingMode);
  21726. engine.draw(true, 0, 6);
  21727. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21728. };
  21729. Layer.prototype.dispose = function () {
  21730. if (this._vertexBuffer) {
  21731. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21732. this._vertexBuffer = null;
  21733. }
  21734. if (this._indexBuffer) {
  21735. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21736. this._indexBuffer = null;
  21737. }
  21738. if (this.texture) {
  21739. this.texture.dispose();
  21740. this.texture = null;
  21741. }
  21742. // Remove from scene
  21743. var index = this._scene.layers.indexOf(this);
  21744. this._scene.layers.splice(index, 1);
  21745. // Callback
  21746. if (this.onDispose) {
  21747. this.onDispose();
  21748. }
  21749. };
  21750. return Layer;
  21751. })();
  21752. BABYLON.Layer = Layer;
  21753. })(BABYLON || (BABYLON = {}));
  21754. var BABYLON;
  21755. (function (BABYLON) {
  21756. var Particle = (function () {
  21757. function Particle() {
  21758. this.position = BABYLON.Vector3.Zero();
  21759. this.direction = BABYLON.Vector3.Zero();
  21760. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21761. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21762. this.lifeTime = 1.0;
  21763. this.age = 0;
  21764. this.size = 0;
  21765. this.angle = 0;
  21766. this.angularSpeed = 0;
  21767. }
  21768. Particle.prototype.copyTo = function (other) {
  21769. other.position.copyFrom(this.position);
  21770. other.direction.copyFrom(this.direction);
  21771. other.color.copyFrom(this.color);
  21772. other.colorStep.copyFrom(this.colorStep);
  21773. other.lifeTime = this.lifeTime;
  21774. other.age = this.age;
  21775. other.size = this.size;
  21776. other.angle = this.angle;
  21777. other.angularSpeed = this.angularSpeed;
  21778. };
  21779. return Particle;
  21780. })();
  21781. BABYLON.Particle = Particle;
  21782. })(BABYLON || (BABYLON = {}));
  21783. var BABYLON;
  21784. (function (BABYLON) {
  21785. var randomNumber = function (min, max) {
  21786. if (min === max) {
  21787. return (min);
  21788. }
  21789. var random = Math.random();
  21790. return ((random * (max - min)) + min);
  21791. };
  21792. var ParticleSystem = (function () {
  21793. function ParticleSystem(name, capacity, scene, customEffect) {
  21794. var _this = this;
  21795. this.name = name;
  21796. // Members
  21797. this.animations = [];
  21798. this.renderingGroupId = 0;
  21799. this.emitter = null;
  21800. this.emitRate = 10;
  21801. this.manualEmitCount = -1;
  21802. this.updateSpeed = 0.01;
  21803. this.targetStopDuration = 0;
  21804. this.disposeOnStop = false;
  21805. this.minEmitPower = 1;
  21806. this.maxEmitPower = 1;
  21807. this.minLifeTime = 1;
  21808. this.maxLifeTime = 1;
  21809. this.minSize = 1;
  21810. this.maxSize = 1;
  21811. this.minAngularSpeed = 0;
  21812. this.maxAngularSpeed = 0;
  21813. this.layerMask = 0x0FFFFFFF;
  21814. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21815. this.forceDepthWrite = false;
  21816. this.gravity = BABYLON.Vector3.Zero();
  21817. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21818. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21819. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21820. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21821. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21822. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21823. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21824. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21825. this.particles = new Array();
  21826. this._vertexDeclaration = [3, 4, 4];
  21827. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21828. this._stockParticles = new Array();
  21829. this._newPartsExcess = 0;
  21830. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21831. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21832. this._scaledDirection = BABYLON.Vector3.Zero();
  21833. this._scaledGravity = BABYLON.Vector3.Zero();
  21834. this._currentRenderId = -1;
  21835. this._started = false;
  21836. this._stopped = false;
  21837. this._actualFrame = 0;
  21838. this.id = name;
  21839. this._capacity = capacity;
  21840. this._scene = scene;
  21841. this._customEffect = customEffect;
  21842. scene.particleSystems.push(this);
  21843. // VBO
  21844. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21845. var indices = [];
  21846. var index = 0;
  21847. for (var count = 0; count < capacity; count++) {
  21848. indices.push(index);
  21849. indices.push(index + 1);
  21850. indices.push(index + 2);
  21851. indices.push(index);
  21852. indices.push(index + 2);
  21853. indices.push(index + 3);
  21854. index += 4;
  21855. }
  21856. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21857. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21858. // Default behaviors
  21859. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21860. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21861. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21862. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21863. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21864. };
  21865. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21866. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21867. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21868. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21869. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21870. };
  21871. this.updateFunction = function (particles) {
  21872. for (var index = 0; index < particles.length; index++) {
  21873. var particle = particles[index];
  21874. particle.age += _this._scaledUpdateSpeed;
  21875. if (particle.age >= particle.lifeTime) {
  21876. _this.recycleParticle(particle);
  21877. index--;
  21878. continue;
  21879. }
  21880. else {
  21881. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21882. particle.color.addInPlace(_this._scaledColorStep);
  21883. if (particle.color.a < 0)
  21884. particle.color.a = 0;
  21885. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21886. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21887. particle.position.addInPlace(_this._scaledDirection);
  21888. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21889. particle.direction.addInPlace(_this._scaledGravity);
  21890. }
  21891. }
  21892. };
  21893. }
  21894. ParticleSystem.prototype.recycleParticle = function (particle) {
  21895. var lastParticle = this.particles.pop();
  21896. if (lastParticle !== particle) {
  21897. lastParticle.copyTo(particle);
  21898. this._stockParticles.push(lastParticle);
  21899. }
  21900. };
  21901. ParticleSystem.prototype.getCapacity = function () {
  21902. return this._capacity;
  21903. };
  21904. ParticleSystem.prototype.isAlive = function () {
  21905. return this._alive;
  21906. };
  21907. ParticleSystem.prototype.isStarted = function () {
  21908. return this._started;
  21909. };
  21910. ParticleSystem.prototype.start = function () {
  21911. this._started = true;
  21912. this._stopped = false;
  21913. this._actualFrame = 0;
  21914. };
  21915. ParticleSystem.prototype.stop = function () {
  21916. this._stopped = true;
  21917. };
  21918. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21919. var offset = index * 11;
  21920. this._vertices[offset] = particle.position.x;
  21921. this._vertices[offset + 1] = particle.position.y;
  21922. this._vertices[offset + 2] = particle.position.z;
  21923. this._vertices[offset + 3] = particle.color.r;
  21924. this._vertices[offset + 4] = particle.color.g;
  21925. this._vertices[offset + 5] = particle.color.b;
  21926. this._vertices[offset + 6] = particle.color.a;
  21927. this._vertices[offset + 7] = particle.angle;
  21928. this._vertices[offset + 8] = particle.size;
  21929. this._vertices[offset + 9] = offsetX;
  21930. this._vertices[offset + 10] = offsetY;
  21931. };
  21932. ParticleSystem.prototype._update = function (newParticles) {
  21933. // Update current
  21934. this._alive = this.particles.length > 0;
  21935. this.updateFunction(this.particles);
  21936. // Add new ones
  21937. var worldMatrix;
  21938. if (this.emitter.position) {
  21939. worldMatrix = this.emitter.getWorldMatrix();
  21940. }
  21941. else {
  21942. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21943. }
  21944. var particle;
  21945. for (var index = 0; index < newParticles; index++) {
  21946. if (this.particles.length === this._capacity) {
  21947. break;
  21948. }
  21949. if (this._stockParticles.length !== 0) {
  21950. particle = this._stockParticles.pop();
  21951. particle.age = 0;
  21952. }
  21953. else {
  21954. particle = new BABYLON.Particle();
  21955. }
  21956. this.particles.push(particle);
  21957. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21958. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21959. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21960. particle.size = randomNumber(this.minSize, this.maxSize);
  21961. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21962. this.startPositionFunction(worldMatrix, particle.position, particle);
  21963. var step = randomNumber(0, 1.0);
  21964. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21965. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21966. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21967. }
  21968. };
  21969. ParticleSystem.prototype._getEffect = function () {
  21970. if (this._customEffect) {
  21971. return this._customEffect;
  21972. }
  21973. ;
  21974. var defines = [];
  21975. if (this._scene.clipPlane) {
  21976. defines.push("#define CLIPPLANE");
  21977. }
  21978. // Effect
  21979. var join = defines.join("\n");
  21980. if (this._cachedDefines !== join) {
  21981. this._cachedDefines = join;
  21982. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21983. }
  21984. return this._effect;
  21985. };
  21986. ParticleSystem.prototype.animate = function () {
  21987. if (!this._started)
  21988. return;
  21989. var effect = this._getEffect();
  21990. // Check
  21991. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21992. return;
  21993. if (this._currentRenderId === this._scene.getRenderId()) {
  21994. return;
  21995. }
  21996. this._currentRenderId = this._scene.getRenderId();
  21997. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21998. // determine the number of particles we need to create
  21999. var newParticles;
  22000. if (this.manualEmitCount > -1) {
  22001. newParticles = this.manualEmitCount;
  22002. this._newPartsExcess = 0;
  22003. this.manualEmitCount = 0;
  22004. }
  22005. else {
  22006. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22007. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22008. }
  22009. if (this._newPartsExcess > 1.0) {
  22010. newParticles += this._newPartsExcess >> 0;
  22011. this._newPartsExcess -= this._newPartsExcess >> 0;
  22012. }
  22013. this._alive = false;
  22014. if (!this._stopped) {
  22015. this._actualFrame += this._scaledUpdateSpeed;
  22016. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22017. this.stop();
  22018. }
  22019. else {
  22020. newParticles = 0;
  22021. }
  22022. this._update(newParticles);
  22023. // Stopped?
  22024. if (this._stopped) {
  22025. if (!this._alive) {
  22026. this._started = false;
  22027. if (this.disposeOnStop) {
  22028. this._scene._toBeDisposed.push(this);
  22029. }
  22030. }
  22031. }
  22032. // Update VBO
  22033. var offset = 0;
  22034. for (var index = 0; index < this.particles.length; index++) {
  22035. var particle = this.particles[index];
  22036. this._appendParticleVertex(offset++, particle, 0, 0);
  22037. this._appendParticleVertex(offset++, particle, 1, 0);
  22038. this._appendParticleVertex(offset++, particle, 1, 1);
  22039. this._appendParticleVertex(offset++, particle, 0, 1);
  22040. }
  22041. var engine = this._scene.getEngine();
  22042. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22043. };
  22044. ParticleSystem.prototype.render = function () {
  22045. var effect = this._getEffect();
  22046. // Check
  22047. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22048. return 0;
  22049. var engine = this._scene.getEngine();
  22050. // Render
  22051. engine.enableEffect(effect);
  22052. engine.setState(false);
  22053. var viewMatrix = this._scene.getViewMatrix();
  22054. effect.setTexture("diffuseSampler", this.particleTexture);
  22055. effect.setMatrix("view", viewMatrix);
  22056. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22057. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22058. if (this._scene.clipPlane) {
  22059. var clipPlane = this._scene.clipPlane;
  22060. var invView = viewMatrix.clone();
  22061. invView.invert();
  22062. effect.setMatrix("invView", invView);
  22063. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22064. }
  22065. // VBOs
  22066. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22067. // Draw order
  22068. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22069. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22070. }
  22071. else {
  22072. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22073. }
  22074. if (this.forceDepthWrite) {
  22075. engine.setDepthWrite(true);
  22076. }
  22077. engine.draw(true, 0, this.particles.length * 6);
  22078. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22079. return this.particles.length;
  22080. };
  22081. ParticleSystem.prototype.dispose = function () {
  22082. if (this._vertexBuffer) {
  22083. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22084. this._vertexBuffer = null;
  22085. }
  22086. if (this._indexBuffer) {
  22087. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22088. this._indexBuffer = null;
  22089. }
  22090. if (this.particleTexture) {
  22091. this.particleTexture.dispose();
  22092. this.particleTexture = null;
  22093. }
  22094. // Remove from scene
  22095. var index = this._scene.particleSystems.indexOf(this);
  22096. this._scene.particleSystems.splice(index, 1);
  22097. // Callback
  22098. if (this.onDispose) {
  22099. this.onDispose();
  22100. }
  22101. };
  22102. // Clone
  22103. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22104. var result = new ParticleSystem(name, this._capacity, this._scene);
  22105. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22106. if (newEmitter === undefined) {
  22107. newEmitter = this.emitter;
  22108. }
  22109. result.emitter = newEmitter;
  22110. if (this.particleTexture) {
  22111. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22112. }
  22113. result.start();
  22114. return result;
  22115. };
  22116. ParticleSystem.prototype.serialize = function () {
  22117. var serializationObject = {};
  22118. serializationObject.name = this.name;
  22119. serializationObject.id = this.id;
  22120. // Emitter
  22121. if (this.emitter.position) {
  22122. serializationObject.emitterId = this.emitter.id;
  22123. }
  22124. else {
  22125. serializationObject.emitter = this.emitter.asArray();
  22126. }
  22127. serializationObject.capacity = this.getCapacity();
  22128. if (this.particleTexture) {
  22129. serializationObject.textureName = this.particleTexture.name;
  22130. }
  22131. // Animations
  22132. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22133. // Particle system
  22134. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22135. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22136. serializationObject.minSize = this.minSize;
  22137. serializationObject.maxSize = this.maxSize;
  22138. serializationObject.minEmitPower = this.minEmitPower;
  22139. serializationObject.maxEmitPower = this.maxEmitPower;
  22140. serializationObject.minLifeTime = this.minLifeTime;
  22141. serializationObject.maxLifeTime = this.maxLifeTime;
  22142. serializationObject.emitRate = this.emitRate;
  22143. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22144. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22145. serializationObject.gravity = this.gravity.asArray();
  22146. serializationObject.direction1 = this.direction1.asArray();
  22147. serializationObject.direction2 = this.direction2.asArray();
  22148. serializationObject.color1 = this.color1.asArray();
  22149. serializationObject.color2 = this.color2.asArray();
  22150. serializationObject.colorDead = this.colorDead.asArray();
  22151. serializationObject.updateSpeed = this.updateSpeed;
  22152. serializationObject.targetStopDuration = this.targetStopDuration;
  22153. serializationObject.textureMask = this.textureMask.asArray();
  22154. serializationObject.blendMode = this.blendMode;
  22155. return serializationObject;
  22156. };
  22157. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22158. var name = parsedParticleSystem.name;
  22159. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22160. if (parsedParticleSystem.id) {
  22161. particleSystem.id = parsedParticleSystem.id;
  22162. }
  22163. // Texture
  22164. if (parsedParticleSystem.textureName) {
  22165. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22166. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22167. }
  22168. // Emitter
  22169. if (parsedParticleSystem.emitterId) {
  22170. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22171. }
  22172. else {
  22173. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22174. }
  22175. // Animations
  22176. if (parsedParticleSystem.animations) {
  22177. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22178. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22179. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22180. }
  22181. }
  22182. // Particle system
  22183. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22184. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22185. particleSystem.minSize = parsedParticleSystem.minSize;
  22186. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22187. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22188. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22189. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22190. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22191. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22192. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22193. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22194. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22195. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22196. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22197. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22198. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22199. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22200. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22201. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22202. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22203. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22204. particleSystem.start();
  22205. return particleSystem;
  22206. };
  22207. // Statics
  22208. ParticleSystem.BLENDMODE_ONEONE = 0;
  22209. ParticleSystem.BLENDMODE_STANDARD = 1;
  22210. return ParticleSystem;
  22211. })();
  22212. BABYLON.ParticleSystem = ParticleSystem;
  22213. })(BABYLON || (BABYLON = {}));
  22214. var BABYLON;
  22215. (function (BABYLON) {
  22216. var AnimationRange = (function () {
  22217. function AnimationRange(name, from, to) {
  22218. this.name = name;
  22219. this.from = from;
  22220. this.to = to;
  22221. }
  22222. return AnimationRange;
  22223. })();
  22224. BABYLON.AnimationRange = AnimationRange;
  22225. /**
  22226. * Composed of a frame, and an action function
  22227. */
  22228. var AnimationEvent = (function () {
  22229. function AnimationEvent(frame, action, onlyOnce) {
  22230. this.frame = frame;
  22231. this.action = action;
  22232. this.onlyOnce = onlyOnce;
  22233. this.isDone = false;
  22234. }
  22235. return AnimationEvent;
  22236. })();
  22237. BABYLON.AnimationEvent = AnimationEvent;
  22238. var Animation = (function () {
  22239. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22240. this.name = name;
  22241. this.targetProperty = targetProperty;
  22242. this.framePerSecond = framePerSecond;
  22243. this.dataType = dataType;
  22244. this.loopMode = loopMode;
  22245. this._offsetsCache = {};
  22246. this._highLimitsCache = {};
  22247. this._stopped = false;
  22248. // The set of event that will be linked to this animation
  22249. this._events = new Array();
  22250. this.allowMatricesInterpolation = false;
  22251. this._ranges = {};
  22252. this.targetPropertyPath = targetProperty.split(".");
  22253. this.dataType = dataType;
  22254. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22255. }
  22256. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22257. var dataType = undefined;
  22258. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22259. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22260. }
  22261. else if (from instanceof BABYLON.Quaternion) {
  22262. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22263. }
  22264. else if (from instanceof BABYLON.Vector3) {
  22265. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22266. }
  22267. else if (from instanceof BABYLON.Vector2) {
  22268. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22269. }
  22270. else if (from instanceof BABYLON.Color3) {
  22271. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22272. }
  22273. if (dataType == undefined) {
  22274. return null;
  22275. }
  22276. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22277. var keys = [];
  22278. keys.push({ frame: 0, value: from });
  22279. keys.push({ frame: totalFrame, value: to });
  22280. animation.setKeys(keys);
  22281. if (easingFunction !== undefined) {
  22282. animation.setEasingFunction(easingFunction);
  22283. }
  22284. return animation;
  22285. };
  22286. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22287. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22288. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22289. };
  22290. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22291. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22292. node.animations.push(animation);
  22293. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22294. };
  22295. // Methods
  22296. /**
  22297. * Add an event to this animation.
  22298. */
  22299. Animation.prototype.addEvent = function (event) {
  22300. this._events.push(event);
  22301. };
  22302. /**
  22303. * Remove all events found at the given frame
  22304. * @param frame
  22305. */
  22306. Animation.prototype.removeEvents = function (frame) {
  22307. for (var index = 0; index < this._events.length; index++) {
  22308. if (this._events[index].frame === frame) {
  22309. this._events.splice(index, 1);
  22310. index--;
  22311. }
  22312. }
  22313. };
  22314. Animation.prototype.createRange = function (name, from, to) {
  22315. // check name not already in use; could happen for bones after serialized
  22316. if (!this._ranges[name]) {
  22317. this._ranges[name] = new AnimationRange(name, from, to);
  22318. }
  22319. };
  22320. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22321. if (deleteFrames === void 0) { deleteFrames = true; }
  22322. if (this._ranges[name]) {
  22323. if (deleteFrames) {
  22324. var from = this._ranges[name].from;
  22325. var to = this._ranges[name].to;
  22326. // this loop MUST go high to low for multiple splices to work
  22327. for (var key = this._keys.length - 1; key >= 0; key--) {
  22328. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22329. this._keys.splice(key, 1);
  22330. }
  22331. }
  22332. }
  22333. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22334. }
  22335. };
  22336. Animation.prototype.getRange = function (name) {
  22337. return this._ranges[name];
  22338. };
  22339. Animation.prototype.reset = function () {
  22340. this._offsetsCache = {};
  22341. this._highLimitsCache = {};
  22342. this.currentFrame = 0;
  22343. };
  22344. Animation.prototype.isStopped = function () {
  22345. return this._stopped;
  22346. };
  22347. Animation.prototype.getKeys = function () {
  22348. return this._keys;
  22349. };
  22350. Animation.prototype.getHighestFrame = function () {
  22351. var ret = 0;
  22352. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22353. if (ret < this._keys[key].frame) {
  22354. ret = this._keys[key].frame;
  22355. }
  22356. }
  22357. return ret;
  22358. };
  22359. Animation.prototype.getEasingFunction = function () {
  22360. return this._easingFunction;
  22361. };
  22362. Animation.prototype.setEasingFunction = function (easingFunction) {
  22363. this._easingFunction = easingFunction;
  22364. };
  22365. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22366. return startValue + (endValue - startValue) * gradient;
  22367. };
  22368. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22369. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22370. };
  22371. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22372. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22373. };
  22374. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22375. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22376. };
  22377. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22378. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22379. };
  22380. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22381. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22382. };
  22383. Animation.prototype.clone = function () {
  22384. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22385. if (this._keys) {
  22386. clone.setKeys(this._keys);
  22387. }
  22388. return clone;
  22389. };
  22390. Animation.prototype.setKeys = function (values) {
  22391. this._keys = values.slice(0);
  22392. this._offsetsCache = {};
  22393. this._highLimitsCache = {};
  22394. };
  22395. Animation.prototype._getKeyValue = function (value) {
  22396. if (typeof value === "function") {
  22397. return value();
  22398. }
  22399. return value;
  22400. };
  22401. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22402. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22403. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22404. }
  22405. this.currentFrame = currentFrame;
  22406. // Try to get a hash to find the right key
  22407. 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));
  22408. if (this._keys[startKey].frame >= currentFrame) {
  22409. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22410. startKey--;
  22411. }
  22412. }
  22413. for (var key = startKey; key < this._keys.length; key++) {
  22414. if (this._keys[key + 1].frame >= currentFrame) {
  22415. var startValue = this._getKeyValue(this._keys[key].value);
  22416. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22417. // gradient : percent of currentFrame between the frame inf and the frame sup
  22418. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22419. // check for easingFunction and correction of gradient
  22420. if (this._easingFunction != null) {
  22421. gradient = this._easingFunction.ease(gradient);
  22422. }
  22423. switch (this.dataType) {
  22424. // Float
  22425. case Animation.ANIMATIONTYPE_FLOAT:
  22426. switch (loopMode) {
  22427. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22428. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22429. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22430. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22431. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22432. }
  22433. break;
  22434. // Quaternion
  22435. case Animation.ANIMATIONTYPE_QUATERNION:
  22436. var quaternion = null;
  22437. switch (loopMode) {
  22438. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22439. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22440. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22441. break;
  22442. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22443. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22444. break;
  22445. }
  22446. return quaternion;
  22447. // Vector3
  22448. case Animation.ANIMATIONTYPE_VECTOR3:
  22449. switch (loopMode) {
  22450. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22451. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22452. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22453. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22454. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22455. }
  22456. // Vector2
  22457. case Animation.ANIMATIONTYPE_VECTOR2:
  22458. switch (loopMode) {
  22459. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22460. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22461. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22462. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22463. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22464. }
  22465. // Color3
  22466. case Animation.ANIMATIONTYPE_COLOR3:
  22467. switch (loopMode) {
  22468. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22469. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22470. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22471. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22472. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22473. }
  22474. // Matrix
  22475. case Animation.ANIMATIONTYPE_MATRIX:
  22476. switch (loopMode) {
  22477. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22478. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22479. if (this.allowMatricesInterpolation) {
  22480. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22481. }
  22482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22483. return startValue;
  22484. }
  22485. default:
  22486. break;
  22487. }
  22488. break;
  22489. }
  22490. }
  22491. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22492. };
  22493. Animation.prototype.setValue = function (currentValue) {
  22494. // Set value
  22495. if (this.targetPropertyPath.length > 1) {
  22496. var property = this._target[this.targetPropertyPath[0]];
  22497. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22498. property = property[this.targetPropertyPath[index]];
  22499. }
  22500. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22501. }
  22502. else {
  22503. this._target[this.targetPropertyPath[0]] = currentValue;
  22504. }
  22505. if (this._target.markAsDirty) {
  22506. this._target.markAsDirty(this.targetProperty);
  22507. }
  22508. };
  22509. Animation.prototype.goToFrame = function (frame) {
  22510. if (frame < this._keys[0].frame) {
  22511. frame = this._keys[0].frame;
  22512. }
  22513. else if (frame > this._keys[this._keys.length - 1].frame) {
  22514. frame = this._keys[this._keys.length - 1].frame;
  22515. }
  22516. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22517. this.setValue(currentValue);
  22518. };
  22519. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22520. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22521. this._stopped = true;
  22522. return false;
  22523. }
  22524. var returnValue = true;
  22525. // Adding a start key at frame 0 if missing
  22526. if (this._keys[0].frame !== 0) {
  22527. var newKey = { frame: 0, value: this._keys[0].value };
  22528. this._keys.splice(0, 0, newKey);
  22529. }
  22530. // Check limits
  22531. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22532. from = this._keys[0].frame;
  22533. }
  22534. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22535. to = this._keys[this._keys.length - 1].frame;
  22536. }
  22537. // Compute ratio
  22538. var range = to - from;
  22539. var offsetValue;
  22540. // ratio represents the frame delta between from and to
  22541. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22542. var highLimitValue = 0;
  22543. if (ratio > range && !loop) {
  22544. returnValue = false;
  22545. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22546. }
  22547. else {
  22548. // Get max value if required
  22549. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22550. var keyOffset = to.toString() + from.toString();
  22551. if (!this._offsetsCache[keyOffset]) {
  22552. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22553. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22554. switch (this.dataType) {
  22555. // Float
  22556. case Animation.ANIMATIONTYPE_FLOAT:
  22557. this._offsetsCache[keyOffset] = toValue - fromValue;
  22558. break;
  22559. // Quaternion
  22560. case Animation.ANIMATIONTYPE_QUATERNION:
  22561. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22562. break;
  22563. // Vector3
  22564. case Animation.ANIMATIONTYPE_VECTOR3:
  22565. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22566. // Vector2
  22567. case Animation.ANIMATIONTYPE_VECTOR2:
  22568. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22569. // Color3
  22570. case Animation.ANIMATIONTYPE_COLOR3:
  22571. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22572. default:
  22573. break;
  22574. }
  22575. this._highLimitsCache[keyOffset] = toValue;
  22576. }
  22577. highLimitValue = this._highLimitsCache[keyOffset];
  22578. offsetValue = this._offsetsCache[keyOffset];
  22579. }
  22580. }
  22581. if (offsetValue === undefined) {
  22582. switch (this.dataType) {
  22583. // Float
  22584. case Animation.ANIMATIONTYPE_FLOAT:
  22585. offsetValue = 0;
  22586. break;
  22587. // Quaternion
  22588. case Animation.ANIMATIONTYPE_QUATERNION:
  22589. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22590. break;
  22591. // Vector3
  22592. case Animation.ANIMATIONTYPE_VECTOR3:
  22593. offsetValue = BABYLON.Vector3.Zero();
  22594. break;
  22595. // Vector2
  22596. case Animation.ANIMATIONTYPE_VECTOR2:
  22597. offsetValue = BABYLON.Vector2.Zero();
  22598. break;
  22599. // Color3
  22600. case Animation.ANIMATIONTYPE_COLOR3:
  22601. offsetValue = BABYLON.Color3.Black();
  22602. }
  22603. }
  22604. // Compute value
  22605. var repeatCount = (ratio / range) >> 0;
  22606. var currentFrame = returnValue ? from + ratio % range : to;
  22607. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22608. // Set value
  22609. this.setValue(currentValue);
  22610. // Check events
  22611. for (var index = 0; index < this._events.length; index++) {
  22612. if (currentFrame >= this._events[index].frame) {
  22613. var event = this._events[index];
  22614. if (!event.isDone) {
  22615. // If event should be done only once, remove it.
  22616. if (event.onlyOnce) {
  22617. this._events.splice(index, 1);
  22618. index--;
  22619. }
  22620. event.isDone = true;
  22621. event.action();
  22622. } // Don't do anything if the event has already be done.
  22623. }
  22624. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22625. // reset event, the animation is looping
  22626. this._events[index].isDone = false;
  22627. }
  22628. }
  22629. if (!returnValue) {
  22630. this._stopped = true;
  22631. }
  22632. return returnValue;
  22633. };
  22634. Animation.prototype.serialize = function () {
  22635. var serializationObject = {};
  22636. serializationObject.name = this.name;
  22637. serializationObject.property = this.targetProperty;
  22638. serializationObject.framePerSecond = this.framePerSecond;
  22639. serializationObject.dataType = this.dataType;
  22640. serializationObject.loopBehavior = this.loopMode;
  22641. var dataType = this.dataType;
  22642. serializationObject.keys = [];
  22643. var keys = this.getKeys();
  22644. for (var index = 0; index < keys.length; index++) {
  22645. var animationKey = keys[index];
  22646. var key = {};
  22647. key.frame = animationKey.frame;
  22648. switch (dataType) {
  22649. case Animation.ANIMATIONTYPE_FLOAT:
  22650. key.values = [animationKey.value];
  22651. break;
  22652. case Animation.ANIMATIONTYPE_QUATERNION:
  22653. case Animation.ANIMATIONTYPE_MATRIX:
  22654. case Animation.ANIMATIONTYPE_VECTOR3:
  22655. case Animation.ANIMATIONTYPE_COLOR3:
  22656. key.values = animationKey.value.asArray();
  22657. break;
  22658. }
  22659. serializationObject.keys.push(key);
  22660. }
  22661. serializationObject.ranges = [];
  22662. for (var name in this._ranges) {
  22663. var range = {};
  22664. range.name = name;
  22665. range.from = this._ranges[name].from;
  22666. range.to = this._ranges[name].to;
  22667. serializationObject.ranges.push(range);
  22668. }
  22669. return serializationObject;
  22670. };
  22671. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22672. get: function () {
  22673. return Animation._ANIMATIONTYPE_FLOAT;
  22674. },
  22675. enumerable: true,
  22676. configurable: true
  22677. });
  22678. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22679. get: function () {
  22680. return Animation._ANIMATIONTYPE_VECTOR3;
  22681. },
  22682. enumerable: true,
  22683. configurable: true
  22684. });
  22685. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22686. get: function () {
  22687. return Animation._ANIMATIONTYPE_VECTOR2;
  22688. },
  22689. enumerable: true,
  22690. configurable: true
  22691. });
  22692. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22693. get: function () {
  22694. return Animation._ANIMATIONTYPE_QUATERNION;
  22695. },
  22696. enumerable: true,
  22697. configurable: true
  22698. });
  22699. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22700. get: function () {
  22701. return Animation._ANIMATIONTYPE_MATRIX;
  22702. },
  22703. enumerable: true,
  22704. configurable: true
  22705. });
  22706. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22707. get: function () {
  22708. return Animation._ANIMATIONTYPE_COLOR3;
  22709. },
  22710. enumerable: true,
  22711. configurable: true
  22712. });
  22713. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22714. get: function () {
  22715. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22716. },
  22717. enumerable: true,
  22718. configurable: true
  22719. });
  22720. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22721. get: function () {
  22722. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22728. get: function () {
  22729. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22730. },
  22731. enumerable: true,
  22732. configurable: true
  22733. });
  22734. Animation.Parse = function (parsedAnimation) {
  22735. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22736. var dataType = parsedAnimation.dataType;
  22737. var keys = [];
  22738. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22739. var key = parsedAnimation.keys[index];
  22740. var data;
  22741. switch (dataType) {
  22742. case Animation.ANIMATIONTYPE_FLOAT:
  22743. data = key.values[0];
  22744. break;
  22745. case Animation.ANIMATIONTYPE_QUATERNION:
  22746. data = BABYLON.Quaternion.FromArray(key.values);
  22747. break;
  22748. case Animation.ANIMATIONTYPE_MATRIX:
  22749. data = BABYLON.Matrix.FromArray(key.values);
  22750. break;
  22751. case Animation.ANIMATIONTYPE_COLOR3:
  22752. data = BABYLON.Color3.FromArray(key.values);
  22753. break;
  22754. case Animation.ANIMATIONTYPE_VECTOR3:
  22755. default:
  22756. data = BABYLON.Vector3.FromArray(key.values);
  22757. break;
  22758. }
  22759. keys.push({
  22760. frame: key.frame,
  22761. value: data
  22762. });
  22763. }
  22764. animation.setKeys(keys);
  22765. if (parsedAnimation.ranges) {
  22766. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22767. data = parsedAnimation.ranges[index];
  22768. animation.createRange(data.name, data.from, data.to);
  22769. }
  22770. }
  22771. return animation;
  22772. };
  22773. Animation.AppendSerializedAnimations = function (source, destination) {
  22774. if (source.animations) {
  22775. destination.animations = [];
  22776. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22777. var animation = source.animations[animationIndex];
  22778. destination.animations.push(animation.serialize());
  22779. }
  22780. }
  22781. };
  22782. // Statics
  22783. Animation._ANIMATIONTYPE_FLOAT = 0;
  22784. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22785. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22786. Animation._ANIMATIONTYPE_MATRIX = 3;
  22787. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22788. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22789. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22790. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22791. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22792. return Animation;
  22793. })();
  22794. BABYLON.Animation = Animation;
  22795. })(BABYLON || (BABYLON = {}));
  22796. var BABYLON;
  22797. (function (BABYLON) {
  22798. var Animatable = (function () {
  22799. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22800. if (fromFrame === void 0) { fromFrame = 0; }
  22801. if (toFrame === void 0) { toFrame = 100; }
  22802. if (loopAnimation === void 0) { loopAnimation = false; }
  22803. if (speedRatio === void 0) { speedRatio = 1.0; }
  22804. this.target = target;
  22805. this.fromFrame = fromFrame;
  22806. this.toFrame = toFrame;
  22807. this.loopAnimation = loopAnimation;
  22808. this.speedRatio = speedRatio;
  22809. this.onAnimationEnd = onAnimationEnd;
  22810. this._animations = new Array();
  22811. this._paused = false;
  22812. this.animationStarted = false;
  22813. if (animations) {
  22814. this.appendAnimations(target, animations);
  22815. }
  22816. this._scene = scene;
  22817. scene._activeAnimatables.push(this);
  22818. }
  22819. // Methods
  22820. Animatable.prototype.getAnimations = function () {
  22821. return this._animations;
  22822. };
  22823. Animatable.prototype.appendAnimations = function (target, animations) {
  22824. for (var index = 0; index < animations.length; index++) {
  22825. var animation = animations[index];
  22826. animation._target = target;
  22827. this._animations.push(animation);
  22828. }
  22829. };
  22830. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22831. var animations = this._animations;
  22832. for (var index = 0; index < animations.length; index++) {
  22833. if (animations[index].targetProperty === property) {
  22834. return animations[index];
  22835. }
  22836. }
  22837. return null;
  22838. };
  22839. Animatable.prototype.reset = function () {
  22840. var animations = this._animations;
  22841. for (var index = 0; index < animations.length; index++) {
  22842. animations[index].reset();
  22843. }
  22844. this._localDelayOffset = null;
  22845. this._pausedDelay = null;
  22846. };
  22847. Animatable.prototype.goToFrame = function (frame) {
  22848. var animations = this._animations;
  22849. for (var index = 0; index < animations.length; index++) {
  22850. animations[index].goToFrame(frame);
  22851. }
  22852. };
  22853. Animatable.prototype.pause = function () {
  22854. if (this._paused) {
  22855. return;
  22856. }
  22857. this._paused = true;
  22858. };
  22859. Animatable.prototype.restart = function () {
  22860. this._paused = false;
  22861. };
  22862. Animatable.prototype.stop = function () {
  22863. var index = this._scene._activeAnimatables.indexOf(this);
  22864. if (index > -1) {
  22865. this._scene._activeAnimatables.splice(index, 1);
  22866. }
  22867. if (this.onAnimationEnd) {
  22868. this.onAnimationEnd();
  22869. }
  22870. };
  22871. Animatable.prototype._animate = function (delay) {
  22872. if (this._paused) {
  22873. this.animationStarted = false;
  22874. if (!this._pausedDelay) {
  22875. this._pausedDelay = delay;
  22876. }
  22877. return true;
  22878. }
  22879. if (!this._localDelayOffset) {
  22880. this._localDelayOffset = delay;
  22881. }
  22882. else if (this._pausedDelay) {
  22883. this._localDelayOffset += delay - this._pausedDelay;
  22884. this._pausedDelay = null;
  22885. }
  22886. // Animating
  22887. var running = false;
  22888. var animations = this._animations;
  22889. var index;
  22890. for (index = 0; index < animations.length; index++) {
  22891. var animation = animations[index];
  22892. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22893. running = running || isRunning;
  22894. }
  22895. this.animationStarted = running;
  22896. if (!running) {
  22897. // Remove from active animatables
  22898. index = this._scene._activeAnimatables.indexOf(this);
  22899. this._scene._activeAnimatables.splice(index, 1);
  22900. }
  22901. if (!running && this.onAnimationEnd) {
  22902. this.onAnimationEnd();
  22903. }
  22904. return running;
  22905. };
  22906. return Animatable;
  22907. })();
  22908. BABYLON.Animatable = Animatable;
  22909. })(BABYLON || (BABYLON = {}));
  22910. var BABYLON;
  22911. (function (BABYLON) {
  22912. var EasingFunction = (function () {
  22913. function EasingFunction() {
  22914. // Properties
  22915. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22916. }
  22917. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22918. get: function () {
  22919. return EasingFunction._EASINGMODE_EASEIN;
  22920. },
  22921. enumerable: true,
  22922. configurable: true
  22923. });
  22924. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22925. get: function () {
  22926. return EasingFunction._EASINGMODE_EASEOUT;
  22927. },
  22928. enumerable: true,
  22929. configurable: true
  22930. });
  22931. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22932. get: function () {
  22933. return EasingFunction._EASINGMODE_EASEINOUT;
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22939. var n = Math.min(Math.max(easingMode, 0), 2);
  22940. this._easingMode = n;
  22941. };
  22942. EasingFunction.prototype.getEasingMode = function () {
  22943. return this._easingMode;
  22944. };
  22945. EasingFunction.prototype.easeInCore = function (gradient) {
  22946. throw new Error('You must implement this method');
  22947. };
  22948. EasingFunction.prototype.ease = function (gradient) {
  22949. switch (this._easingMode) {
  22950. case EasingFunction.EASINGMODE_EASEIN:
  22951. return this.easeInCore(gradient);
  22952. case EasingFunction.EASINGMODE_EASEOUT:
  22953. return (1 - this.easeInCore(1 - gradient));
  22954. }
  22955. if (gradient >= 0.5) {
  22956. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22957. }
  22958. return (this.easeInCore(gradient * 2) * 0.5);
  22959. };
  22960. //Statics
  22961. EasingFunction._EASINGMODE_EASEIN = 0;
  22962. EasingFunction._EASINGMODE_EASEOUT = 1;
  22963. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22964. return EasingFunction;
  22965. })();
  22966. BABYLON.EasingFunction = EasingFunction;
  22967. var CircleEase = (function (_super) {
  22968. __extends(CircleEase, _super);
  22969. function CircleEase() {
  22970. _super.apply(this, arguments);
  22971. }
  22972. CircleEase.prototype.easeInCore = function (gradient) {
  22973. gradient = Math.max(0, Math.min(1, gradient));
  22974. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22975. };
  22976. return CircleEase;
  22977. })(EasingFunction);
  22978. BABYLON.CircleEase = CircleEase;
  22979. var BackEase = (function (_super) {
  22980. __extends(BackEase, _super);
  22981. function BackEase(amplitude) {
  22982. if (amplitude === void 0) { amplitude = 1; }
  22983. _super.call(this);
  22984. this.amplitude = amplitude;
  22985. }
  22986. BackEase.prototype.easeInCore = function (gradient) {
  22987. var num = Math.max(0, this.amplitude);
  22988. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22989. };
  22990. return BackEase;
  22991. })(EasingFunction);
  22992. BABYLON.BackEase = BackEase;
  22993. var BounceEase = (function (_super) {
  22994. __extends(BounceEase, _super);
  22995. function BounceEase(bounces, bounciness) {
  22996. if (bounces === void 0) { bounces = 3; }
  22997. if (bounciness === void 0) { bounciness = 2; }
  22998. _super.call(this);
  22999. this.bounces = bounces;
  23000. this.bounciness = bounciness;
  23001. }
  23002. BounceEase.prototype.easeInCore = function (gradient) {
  23003. var y = Math.max(0.0, this.bounces);
  23004. var bounciness = this.bounciness;
  23005. if (bounciness <= 1.0) {
  23006. bounciness = 1.001;
  23007. }
  23008. var num9 = Math.pow(bounciness, y);
  23009. var num5 = 1.0 - bounciness;
  23010. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23011. var num15 = gradient * num4;
  23012. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23013. var num3 = Math.floor(num65);
  23014. var num13 = num3 + 1.0;
  23015. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23016. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23017. var num7 = (num8 + num12) * 0.5;
  23018. var num6 = gradient - num7;
  23019. var num2 = num7 - num8;
  23020. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23021. };
  23022. return BounceEase;
  23023. })(EasingFunction);
  23024. BABYLON.BounceEase = BounceEase;
  23025. var CubicEase = (function (_super) {
  23026. __extends(CubicEase, _super);
  23027. function CubicEase() {
  23028. _super.apply(this, arguments);
  23029. }
  23030. CubicEase.prototype.easeInCore = function (gradient) {
  23031. return (gradient * gradient * gradient);
  23032. };
  23033. return CubicEase;
  23034. })(EasingFunction);
  23035. BABYLON.CubicEase = CubicEase;
  23036. var ElasticEase = (function (_super) {
  23037. __extends(ElasticEase, _super);
  23038. function ElasticEase(oscillations, springiness) {
  23039. if (oscillations === void 0) { oscillations = 3; }
  23040. if (springiness === void 0) { springiness = 3; }
  23041. _super.call(this);
  23042. this.oscillations = oscillations;
  23043. this.springiness = springiness;
  23044. }
  23045. ElasticEase.prototype.easeInCore = function (gradient) {
  23046. var num2;
  23047. var num3 = Math.max(0.0, this.oscillations);
  23048. var num = Math.max(0.0, this.springiness);
  23049. if (num == 0) {
  23050. num2 = gradient;
  23051. }
  23052. else {
  23053. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23054. }
  23055. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23056. };
  23057. return ElasticEase;
  23058. })(EasingFunction);
  23059. BABYLON.ElasticEase = ElasticEase;
  23060. var ExponentialEase = (function (_super) {
  23061. __extends(ExponentialEase, _super);
  23062. function ExponentialEase(exponent) {
  23063. if (exponent === void 0) { exponent = 2; }
  23064. _super.call(this);
  23065. this.exponent = exponent;
  23066. }
  23067. ExponentialEase.prototype.easeInCore = function (gradient) {
  23068. if (this.exponent <= 0) {
  23069. return gradient;
  23070. }
  23071. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23072. };
  23073. return ExponentialEase;
  23074. })(EasingFunction);
  23075. BABYLON.ExponentialEase = ExponentialEase;
  23076. var PowerEase = (function (_super) {
  23077. __extends(PowerEase, _super);
  23078. function PowerEase(power) {
  23079. if (power === void 0) { power = 2; }
  23080. _super.call(this);
  23081. this.power = power;
  23082. }
  23083. PowerEase.prototype.easeInCore = function (gradient) {
  23084. var y = Math.max(0.0, this.power);
  23085. return Math.pow(gradient, y);
  23086. };
  23087. return PowerEase;
  23088. })(EasingFunction);
  23089. BABYLON.PowerEase = PowerEase;
  23090. var QuadraticEase = (function (_super) {
  23091. __extends(QuadraticEase, _super);
  23092. function QuadraticEase() {
  23093. _super.apply(this, arguments);
  23094. }
  23095. QuadraticEase.prototype.easeInCore = function (gradient) {
  23096. return (gradient * gradient);
  23097. };
  23098. return QuadraticEase;
  23099. })(EasingFunction);
  23100. BABYLON.QuadraticEase = QuadraticEase;
  23101. var QuarticEase = (function (_super) {
  23102. __extends(QuarticEase, _super);
  23103. function QuarticEase() {
  23104. _super.apply(this, arguments);
  23105. }
  23106. QuarticEase.prototype.easeInCore = function (gradient) {
  23107. return (gradient * gradient * gradient * gradient);
  23108. };
  23109. return QuarticEase;
  23110. })(EasingFunction);
  23111. BABYLON.QuarticEase = QuarticEase;
  23112. var QuinticEase = (function (_super) {
  23113. __extends(QuinticEase, _super);
  23114. function QuinticEase() {
  23115. _super.apply(this, arguments);
  23116. }
  23117. QuinticEase.prototype.easeInCore = function (gradient) {
  23118. return (gradient * gradient * gradient * gradient * gradient);
  23119. };
  23120. return QuinticEase;
  23121. })(EasingFunction);
  23122. BABYLON.QuinticEase = QuinticEase;
  23123. var SineEase = (function (_super) {
  23124. __extends(SineEase, _super);
  23125. function SineEase() {
  23126. _super.apply(this, arguments);
  23127. }
  23128. SineEase.prototype.easeInCore = function (gradient) {
  23129. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23130. };
  23131. return SineEase;
  23132. })(EasingFunction);
  23133. BABYLON.SineEase = SineEase;
  23134. var BezierCurveEase = (function (_super) {
  23135. __extends(BezierCurveEase, _super);
  23136. function BezierCurveEase(x1, y1, x2, y2) {
  23137. if (x1 === void 0) { x1 = 0; }
  23138. if (y1 === void 0) { y1 = 0; }
  23139. if (x2 === void 0) { x2 = 1; }
  23140. if (y2 === void 0) { y2 = 1; }
  23141. _super.call(this);
  23142. this.x1 = x1;
  23143. this.y1 = y1;
  23144. this.x2 = x2;
  23145. this.y2 = y2;
  23146. }
  23147. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23148. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23149. };
  23150. return BezierCurveEase;
  23151. })(EasingFunction);
  23152. BABYLON.BezierCurveEase = BezierCurveEase;
  23153. })(BABYLON || (BABYLON = {}));
  23154. var BABYLON;
  23155. (function (BABYLON) {
  23156. var Bone = (function (_super) {
  23157. __extends(Bone, _super);
  23158. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23159. _super.call(this, name, skeleton.getScene());
  23160. this.name = name;
  23161. this.children = new Array();
  23162. this.animations = new Array();
  23163. this._worldTransform = new BABYLON.Matrix();
  23164. this._absoluteTransform = new BABYLON.Matrix();
  23165. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23166. this._skeleton = skeleton;
  23167. this._matrix = matrix;
  23168. this._baseMatrix = matrix;
  23169. this._restPose = restPose ? restPose : matrix.clone();
  23170. skeleton.bones.push(this);
  23171. if (parentBone) {
  23172. this._parent = parentBone;
  23173. parentBone.children.push(this);
  23174. }
  23175. else {
  23176. this._parent = null;
  23177. }
  23178. this._updateDifferenceMatrix();
  23179. }
  23180. // Members
  23181. Bone.prototype.getParent = function () {
  23182. return this._parent;
  23183. };
  23184. Bone.prototype.getLocalMatrix = function () {
  23185. return this._matrix;
  23186. };
  23187. Bone.prototype.getBaseMatrix = function () {
  23188. return this._baseMatrix;
  23189. };
  23190. Bone.prototype.getRestPose = function () {
  23191. return this._restPose;
  23192. };
  23193. Bone.prototype.returnToRest = function () {
  23194. this.updateMatrix(this._restPose.clone());
  23195. };
  23196. Bone.prototype.getWorldMatrix = function () {
  23197. return this._worldTransform;
  23198. };
  23199. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23200. return this._invertedAbsoluteTransform;
  23201. };
  23202. Bone.prototype.getAbsoluteTransform = function () {
  23203. return this._absoluteTransform;
  23204. };
  23205. // Methods
  23206. Bone.prototype.updateMatrix = function (matrix) {
  23207. this._baseMatrix = matrix.clone();
  23208. this._matrix = matrix.clone();
  23209. this._skeleton._markAsDirty();
  23210. this._updateDifferenceMatrix();
  23211. };
  23212. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23213. if (!rootMatrix) {
  23214. rootMatrix = this._baseMatrix;
  23215. }
  23216. if (this._parent) {
  23217. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23218. }
  23219. else {
  23220. this._absoluteTransform.copyFrom(rootMatrix);
  23221. }
  23222. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23223. for (var index = 0; index < this.children.length; index++) {
  23224. this.children[index]._updateDifferenceMatrix();
  23225. }
  23226. };
  23227. Bone.prototype.markAsDirty = function () {
  23228. this._currentRenderId++;
  23229. this._skeleton._markAsDirty();
  23230. };
  23231. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23232. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23233. // all animation may be coming from a library skeleton, so may need to create animation
  23234. if (this.animations.length === 0) {
  23235. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23236. }
  23237. // get animation info / verify there is such a range from the source bone
  23238. var sourceRange = source.animations[0].getRange(rangeName);
  23239. if (!sourceRange) {
  23240. return false;
  23241. }
  23242. var from = sourceRange.from;
  23243. var to = sourceRange.to;
  23244. var sourceKeys = source.animations[0].getKeys();
  23245. // rescaling prep
  23246. var sourceBoneLength = source.length;
  23247. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23248. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23249. var destKeys = this.animations[0].getKeys();
  23250. // loop vars declaration / initialization
  23251. var orig;
  23252. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23253. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23254. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23255. var mat;
  23256. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23257. orig = sourceKeys[key];
  23258. if (orig.frame >= from && orig.frame <= to) {
  23259. if (scalingReqd) {
  23260. orig.value.decompose(origScale, origRotation, origTranslation);
  23261. origTranslation.scaleInPlace(ratio);
  23262. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23263. }
  23264. else {
  23265. mat = orig.value;
  23266. }
  23267. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23268. }
  23269. }
  23270. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23271. return true;
  23272. };
  23273. return Bone;
  23274. })(BABYLON.Node);
  23275. BABYLON.Bone = Bone;
  23276. })(BABYLON || (BABYLON = {}));
  23277. var BABYLON;
  23278. (function (BABYLON) {
  23279. var Skeleton = (function () {
  23280. function Skeleton(name, id, scene) {
  23281. this.name = name;
  23282. this.id = id;
  23283. this.bones = new Array();
  23284. this.needInitialSkinMatrix = false;
  23285. this._isDirty = true;
  23286. this._meshesWithPoseMatrix = new Array();
  23287. this._identity = BABYLON.Matrix.Identity();
  23288. this._ranges = {};
  23289. this.bones = [];
  23290. this._scene = scene;
  23291. scene.skeletons.push(this);
  23292. this.prepare();
  23293. //make sure it will recalculate the matrix next time prepare is called.
  23294. this._isDirty = true;
  23295. }
  23296. // Members
  23297. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23298. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23299. return mesh._bonesTransformMatrices;
  23300. }
  23301. return this._transformMatrices;
  23302. };
  23303. Skeleton.prototype.getScene = function () {
  23304. return this._scene;
  23305. };
  23306. // Methods
  23307. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23308. // check name not already in use
  23309. if (!this._ranges[name]) {
  23310. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23311. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23312. if (this.bones[i].animations[0]) {
  23313. this.bones[i].animations[0].createRange(name, from, to);
  23314. }
  23315. }
  23316. }
  23317. };
  23318. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23319. if (deleteFrames === void 0) { deleteFrames = true; }
  23320. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23321. if (this.bones[i].animations[0]) {
  23322. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23323. }
  23324. }
  23325. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23326. };
  23327. Skeleton.prototype.getAnimationRange = function (name) {
  23328. return this._ranges[name];
  23329. };
  23330. /**
  23331. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23332. */
  23333. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23334. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23335. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23336. return false;
  23337. }
  23338. var ret = true;
  23339. var frameOffset = this._getHighestAnimationFrame() + 1;
  23340. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23341. var boneDict = {};
  23342. var sourceBones = source.bones;
  23343. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23344. boneDict[sourceBones[i].name] = sourceBones[i];
  23345. }
  23346. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23347. var boneName = this.bones[i].name;
  23348. var sourceBone = boneDict[boneName];
  23349. if (sourceBone) {
  23350. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23351. }
  23352. else {
  23353. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23354. ret = false;
  23355. }
  23356. }
  23357. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23358. var range = source.getAnimationRange(name);
  23359. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23360. return ret;
  23361. };
  23362. Skeleton.prototype.returnToRest = function () {
  23363. for (var index = 0; index < this.bones.length; index++) {
  23364. this.bones[index].returnToRest();
  23365. }
  23366. };
  23367. Skeleton.prototype._getHighestAnimationFrame = function () {
  23368. var ret = 0;
  23369. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23370. if (this.bones[i].animations[0]) {
  23371. var highest = this.bones[i].animations[0].getHighestFrame();
  23372. if (ret < highest) {
  23373. ret = highest;
  23374. }
  23375. }
  23376. }
  23377. return ret;
  23378. };
  23379. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23380. var range = this.getAnimationRange(name);
  23381. if (!range) {
  23382. return null;
  23383. }
  23384. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23385. };
  23386. Skeleton.prototype._markAsDirty = function () {
  23387. this._isDirty = true;
  23388. };
  23389. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23390. this._meshesWithPoseMatrix.push(mesh);
  23391. };
  23392. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23393. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23394. if (index > -1) {
  23395. this._meshesWithPoseMatrix.splice(index, 1);
  23396. }
  23397. };
  23398. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23399. for (var index = 0; index < this.bones.length; index++) {
  23400. var bone = this.bones[index];
  23401. var parentBone = bone.getParent();
  23402. if (parentBone) {
  23403. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23404. }
  23405. else {
  23406. if (initialSkinMatrix) {
  23407. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23408. }
  23409. else {
  23410. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23411. }
  23412. }
  23413. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23414. }
  23415. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23416. };
  23417. Skeleton.prototype.prepare = function () {
  23418. if (!this._isDirty) {
  23419. return;
  23420. }
  23421. if (this.needInitialSkinMatrix) {
  23422. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23423. var mesh = this._meshesWithPoseMatrix[index];
  23424. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23425. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23426. }
  23427. var poseMatrix = mesh.getPoseMatrix();
  23428. // Prepare bones
  23429. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23430. var bone = this.bones[boneIndex];
  23431. if (!bone.getParent()) {
  23432. var matrix = bone.getBaseMatrix();
  23433. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23434. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23435. }
  23436. }
  23437. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23438. }
  23439. }
  23440. else {
  23441. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23442. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23443. }
  23444. this._computeTransformMatrices(this._transformMatrices, null);
  23445. }
  23446. this._isDirty = false;
  23447. this._scene._activeBones += this.bones.length;
  23448. };
  23449. Skeleton.prototype.getAnimatables = function () {
  23450. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23451. this._animatables = [];
  23452. for (var index = 0; index < this.bones.length; index++) {
  23453. this._animatables.push(this.bones[index]);
  23454. }
  23455. }
  23456. return this._animatables;
  23457. };
  23458. Skeleton.prototype.clone = function (name, id) {
  23459. var result = new Skeleton(name, id || name, this._scene);
  23460. for (var index = 0; index < this.bones.length; index++) {
  23461. var source = this.bones[index];
  23462. var parentBone = null;
  23463. if (source.getParent()) {
  23464. var parentIndex = this.bones.indexOf(source.getParent());
  23465. parentBone = result.bones[parentIndex];
  23466. }
  23467. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23468. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23469. }
  23470. return result;
  23471. };
  23472. Skeleton.prototype.dispose = function () {
  23473. this._meshesWithPoseMatrix = [];
  23474. // Animations
  23475. this.getScene().stopAnimation(this);
  23476. // Remove from scene
  23477. this.getScene().removeSkeleton(this);
  23478. };
  23479. Skeleton.prototype.serialize = function () {
  23480. var serializationObject = {};
  23481. serializationObject.name = this.name;
  23482. serializationObject.id = this.id;
  23483. serializationObject.bones = [];
  23484. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23485. for (var index = 0; index < this.bones.length; index++) {
  23486. var bone = this.bones[index];
  23487. var serializedBone = {
  23488. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23489. name: bone.name,
  23490. matrix: bone.getLocalMatrix().toArray(),
  23491. rest: bone.getRestPose().toArray()
  23492. };
  23493. serializationObject.bones.push(serializedBone);
  23494. if (bone.length) {
  23495. serializedBone.length = bone.length;
  23496. }
  23497. if (bone.animations && bone.animations.length > 0) {
  23498. serializedBone.animation = bone.animations[0].serialize();
  23499. }
  23500. serializationObject.ranges = [];
  23501. for (var name in this._ranges) {
  23502. var range = {};
  23503. range.name = name;
  23504. range.from = this._ranges[name].from;
  23505. range.to = this._ranges[name].to;
  23506. serializationObject.ranges.push(range);
  23507. }
  23508. }
  23509. return serializationObject;
  23510. };
  23511. Skeleton.Parse = function (parsedSkeleton, scene) {
  23512. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23513. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23514. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23515. var parsedBone = parsedSkeleton.bones[index];
  23516. var parentBone = null;
  23517. if (parsedBone.parentBoneIndex > -1) {
  23518. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23519. }
  23520. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23521. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23522. if (parsedBone.length) {
  23523. bone.length = parsedBone.length;
  23524. }
  23525. if (parsedBone.animation) {
  23526. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23527. }
  23528. }
  23529. // placed after bones, so createAnimationRange can cascade down
  23530. if (parsedSkeleton.ranges) {
  23531. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23532. var data = parsedSkeleton.ranges[index];
  23533. skeleton.createAnimationRange(data.name, data.from, data.to);
  23534. }
  23535. }
  23536. return skeleton;
  23537. };
  23538. return Skeleton;
  23539. })();
  23540. BABYLON.Skeleton = Skeleton;
  23541. })(BABYLON || (BABYLON = {}));
  23542. var BABYLON;
  23543. (function (BABYLON) {
  23544. var PostProcess = (function () {
  23545. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23547. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23548. this.name = name;
  23549. this.width = -1;
  23550. this.height = -1;
  23551. this._reusable = false;
  23552. this._textures = new BABYLON.SmartArray(2);
  23553. this._currentRenderTextureInd = 0;
  23554. if (camera != null) {
  23555. this._camera = camera;
  23556. this._scene = camera.getScene();
  23557. camera.attachPostProcess(this);
  23558. this._engine = this._scene.getEngine();
  23559. }
  23560. else {
  23561. this._engine = engine;
  23562. }
  23563. this._renderRatio = ratio;
  23564. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23565. this._reusable = reusable || false;
  23566. this._textureType = textureType;
  23567. this._samplers = samplers || [];
  23568. this._samplers.push("textureSampler");
  23569. this._fragmentUrl = fragmentUrl;
  23570. this._parameters = parameters || [];
  23571. this.updateEffect(defines);
  23572. }
  23573. PostProcess.prototype.updateEffect = function (defines) {
  23574. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23575. };
  23576. PostProcess.prototype.isReusable = function () {
  23577. return this._reusable;
  23578. };
  23579. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23580. camera = camera || this._camera;
  23581. var scene = camera.getScene();
  23582. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23583. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23584. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23585. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23586. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23587. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23588. if (this._textures.length > 0) {
  23589. for (var i = 0; i < this._textures.length; i++) {
  23590. this._engine._releaseTexture(this._textures.data[i]);
  23591. }
  23592. this._textures.reset();
  23593. }
  23594. this.width = desiredWidth;
  23595. this.height = desiredHeight;
  23596. 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 }));
  23597. if (this._reusable) {
  23598. 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 }));
  23599. }
  23600. if (this.onSizeChanged) {
  23601. this.onSizeChanged();
  23602. }
  23603. }
  23604. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23605. if (this.onActivate) {
  23606. this.onActivate(camera);
  23607. }
  23608. // Clear
  23609. if (this.clearColor) {
  23610. this._engine.clear(this.clearColor, true, true);
  23611. }
  23612. else {
  23613. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23614. }
  23615. if (this._reusable) {
  23616. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23617. }
  23618. };
  23619. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23620. get: function () {
  23621. return this._effect.isSupported;
  23622. },
  23623. enumerable: true,
  23624. configurable: true
  23625. });
  23626. PostProcess.prototype.apply = function () {
  23627. // Check
  23628. if (!this._effect.isReady())
  23629. return null;
  23630. // States
  23631. this._engine.enableEffect(this._effect);
  23632. this._engine.setState(false);
  23633. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23634. this._engine.setDepthBuffer(false);
  23635. this._engine.setDepthWrite(false);
  23636. // Texture
  23637. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23638. // Parameters
  23639. if (this.onApply) {
  23640. this.onApply(this._effect);
  23641. }
  23642. return this._effect;
  23643. };
  23644. PostProcess.prototype.dispose = function (camera) {
  23645. camera = camera || this._camera;
  23646. if (this._textures.length > 0) {
  23647. for (var i = 0; i < this._textures.length; i++) {
  23648. this._engine._releaseTexture(this._textures.data[i]);
  23649. }
  23650. this._textures.reset();
  23651. }
  23652. if (!camera) {
  23653. return;
  23654. }
  23655. camera.detachPostProcess(this);
  23656. var index = camera._postProcesses.indexOf(this);
  23657. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23658. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23659. }
  23660. };
  23661. return PostProcess;
  23662. })();
  23663. BABYLON.PostProcess = PostProcess;
  23664. })(BABYLON || (BABYLON = {}));
  23665. var BABYLON;
  23666. (function (BABYLON) {
  23667. var PostProcessManager = (function () {
  23668. function PostProcessManager(scene) {
  23669. this._vertexDeclaration = [2];
  23670. this._vertexStrideSize = 2 * 4;
  23671. this._scene = scene;
  23672. }
  23673. PostProcessManager.prototype._prepareBuffers = function () {
  23674. if (this._vertexBuffer) {
  23675. return;
  23676. }
  23677. // VBO
  23678. var vertices = [];
  23679. vertices.push(1, 1);
  23680. vertices.push(-1, 1);
  23681. vertices.push(-1, -1);
  23682. vertices.push(1, -1);
  23683. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23684. // Indices
  23685. var indices = [];
  23686. indices.push(0);
  23687. indices.push(1);
  23688. indices.push(2);
  23689. indices.push(0);
  23690. indices.push(2);
  23691. indices.push(3);
  23692. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23693. };
  23694. // Methods
  23695. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23696. var postProcesses = this._scene.activeCamera._postProcesses;
  23697. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23698. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23699. return false;
  23700. }
  23701. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23702. return true;
  23703. };
  23704. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23705. var engine = this._scene.getEngine();
  23706. for (var index = 0; index < postProcesses.length; index++) {
  23707. if (index < postProcesses.length - 1) {
  23708. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23709. }
  23710. else {
  23711. if (targetTexture) {
  23712. engine.bindFramebuffer(targetTexture);
  23713. }
  23714. else {
  23715. engine.restoreDefaultFramebuffer();
  23716. }
  23717. }
  23718. var pp = postProcesses[index];
  23719. var effect = pp.apply();
  23720. if (effect) {
  23721. if (pp.onBeforeRender) {
  23722. pp.onBeforeRender(effect);
  23723. }
  23724. // VBOs
  23725. this._prepareBuffers();
  23726. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23727. // Draw order
  23728. engine.draw(true, 0, 6);
  23729. if (pp.onAfterRender) {
  23730. pp.onAfterRender(effect);
  23731. }
  23732. }
  23733. }
  23734. // Restore depth buffer
  23735. engine.setDepthBuffer(true);
  23736. engine.setDepthWrite(true);
  23737. };
  23738. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23739. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23740. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23741. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23742. return;
  23743. }
  23744. var engine = this._scene.getEngine();
  23745. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23746. if (index < postProcessesTakenIndices.length - 1) {
  23747. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23748. }
  23749. else {
  23750. if (targetTexture) {
  23751. engine.bindFramebuffer(targetTexture, faceIndex);
  23752. }
  23753. else {
  23754. engine.restoreDefaultFramebuffer();
  23755. }
  23756. }
  23757. if (doNotPresent) {
  23758. break;
  23759. }
  23760. var pp = postProcesses[postProcessesTakenIndices[index]];
  23761. var effect = pp.apply();
  23762. if (effect) {
  23763. if (pp.onBeforeRender) {
  23764. pp.onBeforeRender(effect);
  23765. }
  23766. // VBOs
  23767. this._prepareBuffers();
  23768. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23769. // Draw order
  23770. engine.draw(true, 0, 6);
  23771. if (pp.onAfterRender) {
  23772. pp.onAfterRender(effect);
  23773. }
  23774. }
  23775. }
  23776. // Restore depth buffer
  23777. engine.setDepthBuffer(true);
  23778. engine.setDepthWrite(true);
  23779. };
  23780. PostProcessManager.prototype.dispose = function () {
  23781. if (this._vertexBuffer) {
  23782. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23783. this._vertexBuffer = null;
  23784. }
  23785. if (this._indexBuffer) {
  23786. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23787. this._indexBuffer = null;
  23788. }
  23789. };
  23790. return PostProcessManager;
  23791. })();
  23792. BABYLON.PostProcessManager = PostProcessManager;
  23793. })(BABYLON || (BABYLON = {}));
  23794. var BABYLON;
  23795. (function (BABYLON) {
  23796. var PassPostProcess = (function (_super) {
  23797. __extends(PassPostProcess, _super);
  23798. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23799. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23800. }
  23801. return PassPostProcess;
  23802. })(BABYLON.PostProcess);
  23803. BABYLON.PassPostProcess = PassPostProcess;
  23804. })(BABYLON || (BABYLON = {}));
  23805. var BABYLON;
  23806. (function (BABYLON) {
  23807. var PhysicsEngine = (function () {
  23808. function PhysicsEngine(plugin) {
  23809. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23810. }
  23811. PhysicsEngine.prototype._initialize = function (gravity) {
  23812. this._currentPlugin.initialize();
  23813. this._setGravity(gravity);
  23814. };
  23815. PhysicsEngine.prototype._runOneStep = function (delta) {
  23816. if (delta > 0.1) {
  23817. delta = 0.1;
  23818. }
  23819. else if (delta <= 0) {
  23820. delta = 1.0 / 60.0;
  23821. }
  23822. this._currentPlugin.runOneStep(delta);
  23823. };
  23824. PhysicsEngine.prototype._setGravity = function (gravity) {
  23825. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23826. this._currentPlugin.setGravity(this.gravity);
  23827. };
  23828. PhysicsEngine.prototype._getGravity = function () {
  23829. return this._currentPlugin.getGravity();
  23830. };
  23831. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23832. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23833. };
  23834. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23835. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23836. };
  23837. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23838. this._currentPlugin.unregisterMesh(mesh);
  23839. };
  23840. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23841. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23842. };
  23843. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23844. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23845. };
  23846. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23847. this._currentPlugin.updateBodyPosition(mesh);
  23848. };
  23849. PhysicsEngine.prototype.dispose = function () {
  23850. this._currentPlugin.dispose();
  23851. };
  23852. PhysicsEngine.prototype.isSupported = function () {
  23853. return this._currentPlugin.isSupported();
  23854. };
  23855. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23856. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23857. };
  23858. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23859. return this._currentPlugin.name;
  23860. };
  23861. PhysicsEngine.prototype.getWorldObject = function () {
  23862. return this._currentPlugin.getWorldObject();
  23863. };
  23864. // Statics
  23865. PhysicsEngine.NoImpostor = 0;
  23866. PhysicsEngine.SphereImpostor = 1;
  23867. PhysicsEngine.BoxImpostor = 2;
  23868. PhysicsEngine.PlaneImpostor = 3;
  23869. PhysicsEngine.MeshImpostor = 4;
  23870. PhysicsEngine.CapsuleImpostor = 5;
  23871. PhysicsEngine.ConeImpostor = 6;
  23872. PhysicsEngine.CylinderImpostor = 7;
  23873. PhysicsEngine.ConvexHullImpostor = 8;
  23874. PhysicsEngine.HeightmapImpostor = 9;
  23875. PhysicsEngine.Epsilon = 0.001;
  23876. return PhysicsEngine;
  23877. })();
  23878. BABYLON.PhysicsEngine = PhysicsEngine;
  23879. })(BABYLON || (BABYLON = {}));
  23880. var BABYLON;
  23881. (function (BABYLON) {
  23882. var VertexData = (function () {
  23883. function VertexData() {
  23884. }
  23885. VertexData.prototype.set = function (data, kind) {
  23886. switch (kind) {
  23887. case BABYLON.VertexBuffer.PositionKind:
  23888. this.positions = data;
  23889. break;
  23890. case BABYLON.VertexBuffer.NormalKind:
  23891. this.normals = data;
  23892. break;
  23893. case BABYLON.VertexBuffer.UVKind:
  23894. this.uvs = data;
  23895. break;
  23896. case BABYLON.VertexBuffer.UV2Kind:
  23897. this.uvs2 = data;
  23898. break;
  23899. case BABYLON.VertexBuffer.UV3Kind:
  23900. this.uvs3 = data;
  23901. break;
  23902. case BABYLON.VertexBuffer.UV4Kind:
  23903. this.uvs4 = data;
  23904. break;
  23905. case BABYLON.VertexBuffer.UV5Kind:
  23906. this.uvs5 = data;
  23907. break;
  23908. case BABYLON.VertexBuffer.UV6Kind:
  23909. this.uvs6 = data;
  23910. break;
  23911. case BABYLON.VertexBuffer.ColorKind:
  23912. this.colors = data;
  23913. break;
  23914. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23915. this.matricesIndices = data;
  23916. break;
  23917. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23918. this.matricesWeights = data;
  23919. break;
  23920. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23921. this.matricesIndicesExtra = data;
  23922. break;
  23923. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23924. this.matricesWeightsExtra = data;
  23925. break;
  23926. }
  23927. };
  23928. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23929. this._applyTo(mesh, updatable);
  23930. };
  23931. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23932. this._applyTo(geometry, updatable);
  23933. };
  23934. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23935. this._update(mesh);
  23936. };
  23937. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23938. this._update(geometry);
  23939. };
  23940. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23941. if (this.positions) {
  23942. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23943. }
  23944. if (this.normals) {
  23945. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23946. }
  23947. if (this.uvs) {
  23948. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23949. }
  23950. if (this.uvs2) {
  23951. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23952. }
  23953. if (this.uvs3) {
  23954. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23955. }
  23956. if (this.uvs4) {
  23957. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23958. }
  23959. if (this.uvs5) {
  23960. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23961. }
  23962. if (this.uvs6) {
  23963. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23964. }
  23965. if (this.colors) {
  23966. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23967. }
  23968. if (this.matricesIndices) {
  23969. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23970. }
  23971. if (this.matricesWeights) {
  23972. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23973. }
  23974. if (this.matricesIndicesExtra) {
  23975. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23976. }
  23977. if (this.matricesWeightsExtra) {
  23978. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23979. }
  23980. if (this.indices) {
  23981. meshOrGeometry.setIndices(this.indices);
  23982. }
  23983. };
  23984. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23985. if (this.positions) {
  23986. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23987. }
  23988. if (this.normals) {
  23989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23990. }
  23991. if (this.uvs) {
  23992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23993. }
  23994. if (this.uvs2) {
  23995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23996. }
  23997. if (this.uvs3) {
  23998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23999. }
  24000. if (this.uvs4) {
  24001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24002. }
  24003. if (this.uvs5) {
  24004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24005. }
  24006. if (this.uvs6) {
  24007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24008. }
  24009. if (this.colors) {
  24010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24011. }
  24012. if (this.matricesIndices) {
  24013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24014. }
  24015. if (this.matricesWeights) {
  24016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24017. }
  24018. if (this.matricesIndicesExtra) {
  24019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24020. }
  24021. if (this.matricesWeightsExtra) {
  24022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24023. }
  24024. if (this.indices) {
  24025. meshOrGeometry.setIndices(this.indices);
  24026. }
  24027. };
  24028. VertexData.prototype.transform = function (matrix) {
  24029. var transformed = BABYLON.Vector3.Zero();
  24030. var index;
  24031. if (this.positions) {
  24032. var position = BABYLON.Vector3.Zero();
  24033. for (index = 0; index < this.positions.length; index += 3) {
  24034. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24035. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24036. this.positions[index] = transformed.x;
  24037. this.positions[index + 1] = transformed.y;
  24038. this.positions[index + 2] = transformed.z;
  24039. }
  24040. }
  24041. if (this.normals) {
  24042. var normal = BABYLON.Vector3.Zero();
  24043. for (index = 0; index < this.normals.length; index += 3) {
  24044. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24045. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24046. this.normals[index] = transformed.x;
  24047. this.normals[index + 1] = transformed.y;
  24048. this.normals[index + 2] = transformed.z;
  24049. }
  24050. }
  24051. };
  24052. VertexData.prototype.merge = function (other) {
  24053. if (other.indices) {
  24054. if (!this.indices) {
  24055. this.indices = [];
  24056. }
  24057. var offset = this.positions ? this.positions.length / 3 : 0;
  24058. for (var index = 0; index < other.indices.length; index++) {
  24059. //TODO check type - if Int32Array!
  24060. this.indices.push(other.indices[index] + offset);
  24061. }
  24062. }
  24063. this.positions = this._mergeElement(this.positions, other.positions);
  24064. this.normals = this._mergeElement(this.normals, other.normals);
  24065. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24066. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24067. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24068. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24069. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24070. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24071. this.colors = this._mergeElement(this.colors, other.colors);
  24072. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24073. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24074. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24075. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24076. };
  24077. VertexData.prototype._mergeElement = function (source, other) {
  24078. if (!other)
  24079. return source;
  24080. if (!source)
  24081. return other;
  24082. var len = other.length + source.length;
  24083. var isSrcTypedArray = source instanceof Float32Array;
  24084. var isOthTypedArray = other instanceof Float32Array;
  24085. // use non-loop method when the source is Float32Array
  24086. if (isSrcTypedArray) {
  24087. var ret32 = new Float32Array(len);
  24088. ret32.set(source);
  24089. ret32.set(other, source.length);
  24090. return ret32;
  24091. }
  24092. else if (!isOthTypedArray) {
  24093. return source.concat(other);
  24094. }
  24095. else {
  24096. var ret = source.slice(0); // copy source to a separate array
  24097. for (var i = 0, len = other.length; i < len; i++) {
  24098. ret.push(other[i]);
  24099. }
  24100. return ret;
  24101. }
  24102. };
  24103. VertexData.prototype.serialize = function () {
  24104. var serializationObject = this.serialize();
  24105. if (this.positions) {
  24106. serializationObject.positions = this.positions;
  24107. }
  24108. if (this.normals) {
  24109. serializationObject.normals = this.normals;
  24110. }
  24111. if (this.uvs) {
  24112. serializationObject.uvs = this.uvs;
  24113. }
  24114. if (this.uvs2) {
  24115. serializationObject.uvs2 = this.uvs2;
  24116. }
  24117. if (this.uvs3) {
  24118. serializationObject.uvs3 = this.uvs3;
  24119. }
  24120. if (this.uvs4) {
  24121. serializationObject.uvs4 = this.uvs4;
  24122. }
  24123. if (this.uvs5) {
  24124. serializationObject.uvs5 = this.uvs5;
  24125. }
  24126. if (this.uvs6) {
  24127. serializationObject.uvs6 = this.uvs6;
  24128. }
  24129. if (this.colors) {
  24130. serializationObject.colors = this.colors;
  24131. }
  24132. if (this.matricesIndices) {
  24133. serializationObject.matricesIndices = this.matricesIndices;
  24134. serializationObject.matricesIndices._isExpanded = true;
  24135. }
  24136. if (this.matricesWeights) {
  24137. serializationObject.matricesWeights = this.matricesWeights;
  24138. }
  24139. if (this.matricesIndicesExtra) {
  24140. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24141. serializationObject.matricesIndicesExtra._isExpanded = true;
  24142. }
  24143. if (this.matricesWeightsExtra) {
  24144. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24145. }
  24146. serializationObject.indices = this.indices;
  24147. return serializationObject;
  24148. };
  24149. // Statics
  24150. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24151. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24152. };
  24153. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24154. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24155. };
  24156. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24157. var result = new VertexData();
  24158. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24159. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24160. }
  24161. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24162. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24163. }
  24164. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24165. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24166. }
  24167. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24168. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24169. }
  24170. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24171. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24172. }
  24173. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24174. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24175. }
  24176. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24177. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24178. }
  24179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24180. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24181. }
  24182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24183. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24184. }
  24185. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24186. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24187. }
  24188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24189. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24190. }
  24191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24192. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24193. }
  24194. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24195. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24196. }
  24197. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24198. return result;
  24199. };
  24200. VertexData.CreateRibbon = function (options) {
  24201. var pathArray = options.pathArray;
  24202. var closeArray = options.closeArray || false;
  24203. var closePath = options.closePath || false;
  24204. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24205. var offset = options.offset || defaultOffset;
  24206. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24208. var positions = [];
  24209. var indices = [];
  24210. var normals = [];
  24211. var uvs = [];
  24212. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24213. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24214. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24215. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24216. var minlg; // minimal length among all paths from pathArray
  24217. var lg = []; // array of path lengths : nb of vertex per path
  24218. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24219. var p; // path iterator
  24220. var i; // point iterator
  24221. var j; // point iterator
  24222. // if single path in pathArray
  24223. if (pathArray.length < 2) {
  24224. var ar1 = [];
  24225. var ar2 = [];
  24226. for (i = 0; i < pathArray[0].length - offset; i++) {
  24227. ar1.push(pathArray[0][i]);
  24228. ar2.push(pathArray[0][i + offset]);
  24229. }
  24230. pathArray = [ar1, ar2];
  24231. }
  24232. // positions and horizontal distances (u)
  24233. var idc = 0;
  24234. var closePathCorr = (closePath) ? 1 : 0;
  24235. var path;
  24236. var l;
  24237. minlg = pathArray[0].length;
  24238. var vectlg;
  24239. var dist;
  24240. for (p = 0; p < pathArray.length; p++) {
  24241. uTotalDistance[p] = 0;
  24242. us[p] = [0];
  24243. path = pathArray[p];
  24244. l = path.length;
  24245. minlg = (minlg < l) ? minlg : l;
  24246. j = 0;
  24247. while (j < l) {
  24248. positions.push(path[j].x, path[j].y, path[j].z);
  24249. if (j > 0) {
  24250. vectlg = path[j].subtract(path[j - 1]).length();
  24251. dist = vectlg + uTotalDistance[p];
  24252. us[p].push(dist);
  24253. uTotalDistance[p] = dist;
  24254. }
  24255. j++;
  24256. }
  24257. if (closePath) {
  24258. j--;
  24259. positions.push(path[0].x, path[0].y, path[0].z);
  24260. vectlg = path[j].subtract(path[0]).length();
  24261. dist = vectlg + uTotalDistance[p];
  24262. us[p].push(dist);
  24263. uTotalDistance[p] = dist;
  24264. }
  24265. lg[p] = l + closePathCorr;
  24266. idx[p] = idc;
  24267. idc += (l + closePathCorr);
  24268. }
  24269. // vertical distances (v)
  24270. var path1;
  24271. var path2;
  24272. var vertex1;
  24273. var vertex2;
  24274. for (i = 0; i < minlg + closePathCorr; i++) {
  24275. vTotalDistance[i] = 0;
  24276. vs[i] = [0];
  24277. for (p = 0; p < pathArray.length - 1; p++) {
  24278. path1 = pathArray[p];
  24279. path2 = pathArray[p + 1];
  24280. if (i === minlg) {
  24281. vertex1 = path1[0];
  24282. vertex2 = path2[0];
  24283. }
  24284. else {
  24285. vertex1 = path1[i];
  24286. vertex2 = path2[i];
  24287. }
  24288. vectlg = vertex2.subtract(vertex1).length();
  24289. dist = vectlg + vTotalDistance[i];
  24290. vs[i].push(dist);
  24291. vTotalDistance[i] = dist;
  24292. }
  24293. if (closeArray) {
  24294. path1 = pathArray[p];
  24295. path2 = pathArray[0];
  24296. if (i === minlg) {
  24297. vertex2 = path2[0];
  24298. }
  24299. vectlg = vertex2.subtract(vertex1).length();
  24300. dist = vectlg + vTotalDistance[i];
  24301. vTotalDistance[i] = dist;
  24302. }
  24303. }
  24304. // uvs
  24305. var u;
  24306. var v;
  24307. for (p = 0; p < pathArray.length; p++) {
  24308. for (i = 0; i < minlg + closePathCorr; i++) {
  24309. u = us[p][i] / uTotalDistance[p];
  24310. v = vs[i][p] / vTotalDistance[i];
  24311. uvs.push(u, v);
  24312. }
  24313. }
  24314. // indices
  24315. p = 0; // path index
  24316. var pi = 0; // positions array index
  24317. var l1 = lg[p] - 1; // path1 length
  24318. var l2 = lg[p + 1] - 1; // path2 length
  24319. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24320. var shft = idx[1] - idx[0]; // shift
  24321. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24322. while (pi <= min && p < path1nb) {
  24323. // 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
  24324. indices.push(pi, pi + shft, pi + 1);
  24325. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24326. pi += 1;
  24327. if (pi === min) {
  24328. p++;
  24329. if (p === lg.length - 1) {
  24330. shft = idx[0] - idx[p];
  24331. l1 = lg[p] - 1;
  24332. l2 = lg[0] - 1;
  24333. }
  24334. else {
  24335. shft = idx[p + 1] - idx[p];
  24336. l1 = lg[p] - 1;
  24337. l2 = lg[p + 1] - 1;
  24338. }
  24339. pi = idx[p];
  24340. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24341. }
  24342. }
  24343. // normals
  24344. VertexData.ComputeNormals(positions, indices, normals);
  24345. if (closePath) {
  24346. var indexFirst = 0;
  24347. var indexLast = 0;
  24348. for (p = 0; p < pathArray.length; p++) {
  24349. indexFirst = idx[p] * 3;
  24350. if (p + 1 < pathArray.length) {
  24351. indexLast = (idx[p + 1] - 1) * 3;
  24352. }
  24353. else {
  24354. indexLast = normals.length - 3;
  24355. }
  24356. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24357. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24358. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24359. normals[indexLast] = normals[indexFirst];
  24360. normals[indexLast + 1] = normals[indexFirst + 1];
  24361. normals[indexLast + 2] = normals[indexFirst + 2];
  24362. }
  24363. }
  24364. // sides
  24365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24366. // Result
  24367. var vertexData = new VertexData();
  24368. vertexData.indices = indices;
  24369. vertexData.positions = positions;
  24370. vertexData.normals = normals;
  24371. vertexData.uvs = uvs;
  24372. if (closePath) {
  24373. vertexData._idx = idx;
  24374. }
  24375. return vertexData;
  24376. };
  24377. VertexData.CreateBox = function (options) {
  24378. var normalsSource = [
  24379. new BABYLON.Vector3(0, 0, 1),
  24380. new BABYLON.Vector3(0, 0, -1),
  24381. new BABYLON.Vector3(1, 0, 0),
  24382. new BABYLON.Vector3(-1, 0, 0),
  24383. new BABYLON.Vector3(0, 1, 0),
  24384. new BABYLON.Vector3(0, -1, 0)
  24385. ];
  24386. var indices = [];
  24387. var positions = [];
  24388. var normals = [];
  24389. var uvs = [];
  24390. var width = options.width || options.size || 1;
  24391. var height = options.height || options.size || 1;
  24392. var depth = options.depth || options.size || 1;
  24393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24394. var faceUV = options.faceUV || new Array(6);
  24395. var faceColors = options.faceColors;
  24396. var colors = [];
  24397. // default face colors and UV if undefined
  24398. for (var f = 0; f < 6; f++) {
  24399. if (faceUV[f] === undefined) {
  24400. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24401. }
  24402. if (faceColors && faceColors[f] === undefined) {
  24403. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24404. }
  24405. }
  24406. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24407. // Create each face in turn.
  24408. for (var index = 0; index < normalsSource.length; index++) {
  24409. var normal = normalsSource[index];
  24410. // Get two vectors perpendicular to the face normal and to each other.
  24411. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24412. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24413. // Six indices (two triangles) per face.
  24414. var verticesLength = positions.length / 3;
  24415. indices.push(verticesLength);
  24416. indices.push(verticesLength + 1);
  24417. indices.push(verticesLength + 2);
  24418. indices.push(verticesLength);
  24419. indices.push(verticesLength + 2);
  24420. indices.push(verticesLength + 3);
  24421. // Four vertices per face.
  24422. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24423. positions.push(vertex.x, vertex.y, vertex.z);
  24424. normals.push(normal.x, normal.y, normal.z);
  24425. uvs.push(faceUV[index].z, faceUV[index].w);
  24426. if (faceColors) {
  24427. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24428. }
  24429. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24430. positions.push(vertex.x, vertex.y, vertex.z);
  24431. normals.push(normal.x, normal.y, normal.z);
  24432. uvs.push(faceUV[index].x, faceUV[index].w);
  24433. if (faceColors) {
  24434. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24435. }
  24436. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24437. positions.push(vertex.x, vertex.y, vertex.z);
  24438. normals.push(normal.x, normal.y, normal.z);
  24439. uvs.push(faceUV[index].x, faceUV[index].y);
  24440. if (faceColors) {
  24441. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24442. }
  24443. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24444. positions.push(vertex.x, vertex.y, vertex.z);
  24445. normals.push(normal.x, normal.y, normal.z);
  24446. uvs.push(faceUV[index].z, faceUV[index].y);
  24447. if (faceColors) {
  24448. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24449. }
  24450. }
  24451. // sides
  24452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24453. // Result
  24454. var vertexData = new VertexData();
  24455. vertexData.indices = indices;
  24456. vertexData.positions = positions;
  24457. vertexData.normals = normals;
  24458. vertexData.uvs = uvs;
  24459. if (faceColors) {
  24460. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24461. vertexData.colors = totalColors;
  24462. }
  24463. return vertexData;
  24464. };
  24465. VertexData.CreateSphere = function (options) {
  24466. var segments = options.segments || 32;
  24467. var diameterX = options.diameterX || options.diameter || 1;
  24468. var diameterY = options.diameterY || options.diameter || 1;
  24469. var diameterZ = options.diameterZ || options.diameter || 1;
  24470. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24471. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24472. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24473. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24474. var totalZRotationSteps = 2 + segments;
  24475. var totalYRotationSteps = 2 * totalZRotationSteps;
  24476. var indices = [];
  24477. var positions = [];
  24478. var normals = [];
  24479. var uvs = [];
  24480. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24481. var normalizedZ = zRotationStep / totalZRotationSteps;
  24482. var angleZ = normalizedZ * Math.PI * slice;
  24483. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24484. var normalizedY = yRotationStep / totalYRotationSteps;
  24485. var angleY = normalizedY * Math.PI * 2 * arc;
  24486. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24487. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24488. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24489. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24490. var vertex = complete.multiply(radius);
  24491. var normal = complete.divide(radius).normalize();
  24492. positions.push(vertex.x, vertex.y, vertex.z);
  24493. normals.push(normal.x, normal.y, normal.z);
  24494. uvs.push(normalizedY, normalizedZ);
  24495. }
  24496. if (zRotationStep > 0) {
  24497. var verticesCount = positions.length / 3;
  24498. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24499. indices.push((firstIndex));
  24500. indices.push((firstIndex + 1));
  24501. indices.push(firstIndex + totalYRotationSteps + 1);
  24502. indices.push((firstIndex + totalYRotationSteps + 1));
  24503. indices.push((firstIndex + 1));
  24504. indices.push((firstIndex + totalYRotationSteps + 2));
  24505. }
  24506. }
  24507. }
  24508. // Sides
  24509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24510. // Result
  24511. var vertexData = new VertexData();
  24512. vertexData.indices = indices;
  24513. vertexData.positions = positions;
  24514. vertexData.normals = normals;
  24515. vertexData.uvs = uvs;
  24516. return vertexData;
  24517. };
  24518. // Cylinder and cone
  24519. VertexData.CreateCylinder = function (options) {
  24520. var height = options.height || 2;
  24521. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24522. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24523. var tessellation = options.tessellation || 24;
  24524. var subdivisions = options.subdivisions || 1;
  24525. var hasRings = options.hasRings;
  24526. var enclose = options.enclose;
  24527. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24529. var faceUV = options.faceUV || new Array(3);
  24530. var faceColors = options.faceColors;
  24531. // default face colors and UV if undefined
  24532. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24533. var ringNb = (hasRings) ? subdivisions : 1;
  24534. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24535. var f;
  24536. for (f = 0; f < surfaceNb; f++) {
  24537. if (faceColors && faceColors[f] === undefined) {
  24538. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24539. }
  24540. }
  24541. for (f = 0; f < surfaceNb; f++) {
  24542. if (faceUV && faceUV[f] === undefined) {
  24543. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24544. }
  24545. }
  24546. var indices = [];
  24547. var positions = [];
  24548. var normals = [];
  24549. var uvs = [];
  24550. var colors = [];
  24551. var angle_step = Math.PI * 2 * arc / tessellation;
  24552. var angle;
  24553. var h;
  24554. var radius;
  24555. var tan = (diameterBottom - diameterTop) / 2 / height;
  24556. var ringVertex = BABYLON.Vector3.Zero();
  24557. var ringNormal = BABYLON.Vector3.Zero();
  24558. var ringFirstVertex = BABYLON.Vector3.Zero();
  24559. var ringFirstNormal = BABYLON.Vector3.Zero();
  24560. var quadNormal = BABYLON.Vector3.Zero();
  24561. var Y = BABYLON.Axis.Y;
  24562. // positions, normals, uvs
  24563. var i;
  24564. var j;
  24565. var r;
  24566. var ringIdx = 1;
  24567. var s = 1; // surface index
  24568. var cs = 0;
  24569. var v = 0;
  24570. for (i = 0; i <= subdivisions; i++) {
  24571. h = i / subdivisions;
  24572. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24573. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24574. for (r = 0; r < ringIdx; r++) {
  24575. if (hasRings) {
  24576. s += r;
  24577. }
  24578. if (enclose) {
  24579. s += 2 * r;
  24580. }
  24581. for (j = 0; j <= tessellation; j++) {
  24582. angle = j * angle_step;
  24583. // position
  24584. ringVertex.x = Math.cos(-angle) * radius;
  24585. ringVertex.y = -height / 2 + h * height;
  24586. ringVertex.z = Math.sin(-angle) * radius;
  24587. // normal
  24588. if (diameterTop === 0 && i === subdivisions) {
  24589. // if no top cap, reuse former normals
  24590. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24591. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24592. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24593. }
  24594. else {
  24595. ringNormal.x = ringVertex.x;
  24596. ringNormal.z = ringVertex.z;
  24597. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24598. ringNormal.normalize();
  24599. }
  24600. // keep first ring vertex values for enclose
  24601. if (j === 0) {
  24602. ringFirstVertex.copyFrom(ringVertex);
  24603. ringFirstNormal.copyFrom(ringNormal);
  24604. }
  24605. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24606. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24607. if (hasRings) {
  24608. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24609. }
  24610. else {
  24611. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24612. }
  24613. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24614. if (faceColors) {
  24615. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24616. }
  24617. }
  24618. // if enclose, add four vertices and their dedicated normals
  24619. if (arc !== 1 && enclose) {
  24620. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24621. positions.push(0, ringVertex.y, 0);
  24622. positions.push(0, ringVertex.y, 0);
  24623. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24624. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24625. quadNormal.normalize();
  24626. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24627. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24628. quadNormal.normalize();
  24629. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24630. if (hasRings) {
  24631. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24632. }
  24633. else {
  24634. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24635. }
  24636. uvs.push(faceUV[s + 1].x, v);
  24637. uvs.push(faceUV[s + 1].z, v);
  24638. if (hasRings) {
  24639. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24640. }
  24641. else {
  24642. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24643. }
  24644. uvs.push(faceUV[s + 2].x, v);
  24645. uvs.push(faceUV[s + 2].z, v);
  24646. if (faceColors) {
  24647. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24648. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24649. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24650. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24651. }
  24652. }
  24653. if (cs !== s) {
  24654. cs = s;
  24655. }
  24656. }
  24657. }
  24658. // indices
  24659. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24660. var s;
  24661. i = 0;
  24662. for (s = 0; s < subdivisions; s++) {
  24663. for (j = 0; j < tessellation; j++) {
  24664. var i0 = i * (e + 1) + j;
  24665. var i1 = (i + 1) * (e + 1) + j;
  24666. var i2 = i * (e + 1) + (j + 1);
  24667. var i3 = (i + 1) * (e + 1) + (j + 1);
  24668. indices.push(i0, i1, i2);
  24669. indices.push(i3, i2, i1);
  24670. }
  24671. if (arc !== 1 && enclose) {
  24672. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24673. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24674. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24675. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24676. }
  24677. i = (hasRings) ? (i + 2) : (i + 1);
  24678. }
  24679. // Caps
  24680. var createCylinderCap = function (isTop) {
  24681. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24682. if (radius === 0) {
  24683. return;
  24684. }
  24685. // Cap positions, normals & uvs
  24686. var angle;
  24687. var circleVector;
  24688. var i;
  24689. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24690. var c;
  24691. if (faceColors) {
  24692. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24693. }
  24694. // cap center
  24695. var vbase = positions.length / 3;
  24696. var offset = isTop ? height / 2 : -height / 2;
  24697. var center = new BABYLON.Vector3(0, offset, 0);
  24698. positions.push(center.x, center.y, center.z);
  24699. normals.push(0, isTop ? 1 : -1, 0);
  24700. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24701. if (faceColors) {
  24702. colors.push(c.r, c.g, c.b, c.a);
  24703. }
  24704. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24705. for (i = 0; i <= tessellation; i++) {
  24706. angle = Math.PI * 2 * i * arc / tessellation;
  24707. var cos = Math.cos(-angle);
  24708. var sin = Math.sin(-angle);
  24709. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24710. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24711. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24712. normals.push(0, isTop ? 1 : -1, 0);
  24713. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24714. if (faceColors) {
  24715. colors.push(c.r, c.g, c.b, c.a);
  24716. }
  24717. }
  24718. // Cap indices
  24719. for (i = 0; i < tessellation; i++) {
  24720. if (!isTop) {
  24721. indices.push(vbase);
  24722. indices.push(vbase + (i + 1));
  24723. indices.push(vbase + (i + 2));
  24724. }
  24725. else {
  24726. indices.push(vbase);
  24727. indices.push(vbase + (i + 2));
  24728. indices.push(vbase + (i + 1));
  24729. }
  24730. }
  24731. };
  24732. // add caps to geometry
  24733. createCylinderCap(false);
  24734. createCylinderCap(true);
  24735. // Sides
  24736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24737. var vertexData = new VertexData();
  24738. vertexData.indices = indices;
  24739. vertexData.positions = positions;
  24740. vertexData.normals = normals;
  24741. vertexData.uvs = uvs;
  24742. if (faceColors) {
  24743. vertexData.colors = colors;
  24744. }
  24745. return vertexData;
  24746. };
  24747. VertexData.CreateTorus = function (options) {
  24748. var indices = [];
  24749. var positions = [];
  24750. var normals = [];
  24751. var uvs = [];
  24752. var diameter = options.diameter || 1;
  24753. var thickness = options.thickness || 0.5;
  24754. var tessellation = options.tessellation || 16;
  24755. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24756. var stride = tessellation + 1;
  24757. for (var i = 0; i <= tessellation; i++) {
  24758. var u = i / tessellation;
  24759. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24760. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24761. for (var j = 0; j <= tessellation; j++) {
  24762. var v = 1 - j / tessellation;
  24763. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24764. var dx = Math.cos(innerAngle);
  24765. var dy = Math.sin(innerAngle);
  24766. // Create a vertex.
  24767. var normal = new BABYLON.Vector3(dx, dy, 0);
  24768. var position = normal.scale(thickness / 2);
  24769. var textureCoordinate = new BABYLON.Vector2(u, v);
  24770. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24771. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24772. positions.push(position.x, position.y, position.z);
  24773. normals.push(normal.x, normal.y, normal.z);
  24774. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24775. // And create indices for two triangles.
  24776. var nextI = (i + 1) % stride;
  24777. var nextJ = (j + 1) % stride;
  24778. indices.push(i * stride + j);
  24779. indices.push(i * stride + nextJ);
  24780. indices.push(nextI * stride + j);
  24781. indices.push(i * stride + nextJ);
  24782. indices.push(nextI * stride + nextJ);
  24783. indices.push(nextI * stride + j);
  24784. }
  24785. }
  24786. // Sides
  24787. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24788. // Result
  24789. var vertexData = new VertexData();
  24790. vertexData.indices = indices;
  24791. vertexData.positions = positions;
  24792. vertexData.normals = normals;
  24793. vertexData.uvs = uvs;
  24794. return vertexData;
  24795. };
  24796. VertexData.CreateLineSystem = function (options) {
  24797. var indices = [];
  24798. var positions = [];
  24799. var lines = options.lines;
  24800. var idx = 0;
  24801. for (var l = 0; l < lines.length; l++) {
  24802. var points = lines[l];
  24803. for (var index = 0; index < points.length; index++) {
  24804. positions.push(points[index].x, points[index].y, points[index].z);
  24805. if (index > 0) {
  24806. indices.push(idx - 1);
  24807. indices.push(idx);
  24808. }
  24809. idx++;
  24810. }
  24811. }
  24812. var vertexData = new VertexData();
  24813. vertexData.indices = indices;
  24814. vertexData.positions = positions;
  24815. return vertexData;
  24816. };
  24817. VertexData.CreateDashedLines = function (options) {
  24818. var dashSize = options.dashSize || 3;
  24819. var gapSize = options.gapSize || 1;
  24820. var dashNb = options.dashNb || 200;
  24821. var points = options.points;
  24822. var positions = new Array();
  24823. var indices = new Array();
  24824. var curvect = BABYLON.Vector3.Zero();
  24825. var lg = 0;
  24826. var nb = 0;
  24827. var shft = 0;
  24828. var dashshft = 0;
  24829. var curshft = 0;
  24830. var idx = 0;
  24831. var i = 0;
  24832. for (i = 0; i < points.length - 1; i++) {
  24833. points[i + 1].subtractToRef(points[i], curvect);
  24834. lg += curvect.length();
  24835. }
  24836. shft = lg / dashNb;
  24837. dashshft = dashSize * shft / (dashSize + gapSize);
  24838. for (i = 0; i < points.length - 1; i++) {
  24839. points[i + 1].subtractToRef(points[i], curvect);
  24840. nb = Math.floor(curvect.length() / shft);
  24841. curvect.normalize();
  24842. for (var j = 0; j < nb; j++) {
  24843. curshft = shft * j;
  24844. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24845. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24846. indices.push(idx, idx + 1);
  24847. idx += 2;
  24848. }
  24849. }
  24850. // Result
  24851. var vertexData = new VertexData();
  24852. vertexData.positions = positions;
  24853. vertexData.indices = indices;
  24854. return vertexData;
  24855. };
  24856. VertexData.CreateGround = function (options) {
  24857. var indices = [];
  24858. var positions = [];
  24859. var normals = [];
  24860. var uvs = [];
  24861. var row, col;
  24862. var width = options.width || 1;
  24863. var height = options.height || 1;
  24864. var subdivisions = options.subdivisions || 1;
  24865. for (row = 0; row <= subdivisions; row++) {
  24866. for (col = 0; col <= subdivisions; col++) {
  24867. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24868. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24869. positions.push(position.x, position.y, position.z);
  24870. normals.push(normal.x, normal.y, normal.z);
  24871. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24872. }
  24873. }
  24874. for (row = 0; row < subdivisions; row++) {
  24875. for (col = 0; col < subdivisions; col++) {
  24876. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24877. indices.push(col + 1 + row * (subdivisions + 1));
  24878. indices.push(col + row * (subdivisions + 1));
  24879. indices.push(col + (row + 1) * (subdivisions + 1));
  24880. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24881. indices.push(col + row * (subdivisions + 1));
  24882. }
  24883. }
  24884. // Result
  24885. var vertexData = new VertexData();
  24886. vertexData.indices = indices;
  24887. vertexData.positions = positions;
  24888. vertexData.normals = normals;
  24889. vertexData.uvs = uvs;
  24890. return vertexData;
  24891. };
  24892. VertexData.CreateTiledGround = function (options) {
  24893. var xmin = options.xmin;
  24894. var zmin = options.zmin;
  24895. var xmax = options.xmax;
  24896. var zmax = options.zmax;
  24897. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24898. var precision = options.precision || { w: 1, h: 1 };
  24899. var indices = [];
  24900. var positions = [];
  24901. var normals = [];
  24902. var uvs = [];
  24903. var row, col, tileRow, tileCol;
  24904. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24905. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24906. precision.w = (precision.w < 1) ? 1 : precision.w;
  24907. precision.h = (precision.h < 1) ? 1 : precision.h;
  24908. var tileSize = {
  24909. 'w': (xmax - xmin) / subdivisions.w,
  24910. 'h': (zmax - zmin) / subdivisions.h
  24911. };
  24912. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24913. // Indices
  24914. var base = positions.length / 3;
  24915. var rowLength = precision.w + 1;
  24916. for (row = 0; row < precision.h; row++) {
  24917. for (col = 0; col < precision.w; col++) {
  24918. var square = [
  24919. base + col + row * rowLength,
  24920. base + (col + 1) + row * rowLength,
  24921. base + (col + 1) + (row + 1) * rowLength,
  24922. base + col + (row + 1) * rowLength
  24923. ];
  24924. indices.push(square[1]);
  24925. indices.push(square[2]);
  24926. indices.push(square[3]);
  24927. indices.push(square[0]);
  24928. indices.push(square[1]);
  24929. indices.push(square[3]);
  24930. }
  24931. }
  24932. // Position, normals and uvs
  24933. var position = BABYLON.Vector3.Zero();
  24934. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24935. for (row = 0; row <= precision.h; row++) {
  24936. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24937. for (col = 0; col <= precision.w; col++) {
  24938. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24939. position.y = 0;
  24940. positions.push(position.x, position.y, position.z);
  24941. normals.push(normal.x, normal.y, normal.z);
  24942. uvs.push(col / precision.w, row / precision.h);
  24943. }
  24944. }
  24945. }
  24946. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24947. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24948. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24949. }
  24950. }
  24951. // Result
  24952. var vertexData = new VertexData();
  24953. vertexData.indices = indices;
  24954. vertexData.positions = positions;
  24955. vertexData.normals = normals;
  24956. vertexData.uvs = uvs;
  24957. return vertexData;
  24958. };
  24959. VertexData.CreateGroundFromHeightMap = function (options) {
  24960. var indices = [];
  24961. var positions = [];
  24962. var normals = [];
  24963. var uvs = [];
  24964. var row, col;
  24965. // Vertices
  24966. for (row = 0; row <= options.subdivisions; row++) {
  24967. for (col = 0; col <= options.subdivisions; col++) {
  24968. 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));
  24969. // Compute height
  24970. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24971. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24972. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24973. var r = options.buffer[pos] / 255.0;
  24974. var g = options.buffer[pos + 1] / 255.0;
  24975. var b = options.buffer[pos + 2] / 255.0;
  24976. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24977. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24978. // Add vertex
  24979. positions.push(position.x, position.y, position.z);
  24980. normals.push(0, 0, 0);
  24981. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24982. }
  24983. }
  24984. // Indices
  24985. for (row = 0; row < options.subdivisions; row++) {
  24986. for (col = 0; col < options.subdivisions; col++) {
  24987. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24988. indices.push(col + 1 + row * (options.subdivisions + 1));
  24989. indices.push(col + row * (options.subdivisions + 1));
  24990. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24991. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24992. indices.push(col + row * (options.subdivisions + 1));
  24993. }
  24994. }
  24995. // Normals
  24996. VertexData.ComputeNormals(positions, indices, normals);
  24997. // Result
  24998. var vertexData = new VertexData();
  24999. vertexData.indices = indices;
  25000. vertexData.positions = positions;
  25001. vertexData.normals = normals;
  25002. vertexData.uvs = uvs;
  25003. return vertexData;
  25004. };
  25005. VertexData.CreatePlane = function (options) {
  25006. var indices = [];
  25007. var positions = [];
  25008. var normals = [];
  25009. var uvs = [];
  25010. var width = options.width || options.size || 1;
  25011. var height = options.height || options.size || 1;
  25012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25013. // Vertices
  25014. var halfWidth = width / 2.0;
  25015. var halfHeight = height / 2.0;
  25016. positions.push(-halfWidth, -halfHeight, 0);
  25017. normals.push(0, 0, -1.0);
  25018. uvs.push(0.0, 0.0);
  25019. positions.push(halfWidth, -halfHeight, 0);
  25020. normals.push(0, 0, -1.0);
  25021. uvs.push(1.0, 0.0);
  25022. positions.push(halfWidth, halfHeight, 0);
  25023. normals.push(0, 0, -1.0);
  25024. uvs.push(1.0, 1.0);
  25025. positions.push(-halfWidth, halfHeight, 0);
  25026. normals.push(0, 0, -1.0);
  25027. uvs.push(0.0, 1.0);
  25028. // Indices
  25029. indices.push(0);
  25030. indices.push(1);
  25031. indices.push(2);
  25032. indices.push(0);
  25033. indices.push(2);
  25034. indices.push(3);
  25035. // Sides
  25036. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25037. // Result
  25038. var vertexData = new VertexData();
  25039. vertexData.indices = indices;
  25040. vertexData.positions = positions;
  25041. vertexData.normals = normals;
  25042. vertexData.uvs = uvs;
  25043. return vertexData;
  25044. };
  25045. VertexData.CreateDisc = function (options) {
  25046. var positions = [];
  25047. var indices = [];
  25048. var normals = [];
  25049. var uvs = [];
  25050. var radius = options.radius || 0.5;
  25051. var tessellation = options.tessellation || 64;
  25052. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25054. // positions and uvs
  25055. positions.push(0, 0, 0); // disc center first
  25056. uvs.push(0.5, 0.5);
  25057. var theta = Math.PI * 2 * arc;
  25058. var step = theta / tessellation;
  25059. for (var a = 0; a < theta; a += step) {
  25060. var x = Math.cos(a);
  25061. var y = Math.sin(a);
  25062. var u = (x + 1) / 2;
  25063. var v = (1 - y) / 2;
  25064. positions.push(radius * x, radius * y, 0);
  25065. uvs.push(u, v);
  25066. }
  25067. if (arc === 1) {
  25068. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25069. uvs.push(uvs[2], uvs[3]);
  25070. }
  25071. //indices
  25072. var vertexNb = positions.length / 3;
  25073. for (var i = 1; i < vertexNb - 1; i++) {
  25074. indices.push(i + 1, 0, i);
  25075. }
  25076. // result
  25077. VertexData.ComputeNormals(positions, indices, normals);
  25078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25079. var vertexData = new VertexData();
  25080. vertexData.indices = indices;
  25081. vertexData.positions = positions;
  25082. vertexData.normals = normals;
  25083. vertexData.uvs = uvs;
  25084. return vertexData;
  25085. };
  25086. VertexData.CreateIcoSphere = function (options) {
  25087. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25088. var radius = options.radius || 1;
  25089. var flat = (options.flat === undefined) ? true : options.flat;
  25090. var subdivisions = options.subdivisions || 4;
  25091. var radiusX = options.radiusX || radius;
  25092. var radiusY = options.radiusY || radius;
  25093. var radiusZ = options.radiusZ || radius;
  25094. var t = (1 + Math.sqrt(5)) / 2;
  25095. // 12 vertex x,y,z
  25096. var ico_vertices = [
  25097. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25098. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25099. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25100. ];
  25101. // index of 3 vertex makes a face of icopshere
  25102. var ico_indices = [
  25103. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25104. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25105. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25106. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25107. ];
  25108. // vertex for uv have aliased position, not for UV
  25109. var vertices_unalias_id = [
  25110. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25111. // vertex alias
  25112. 0,
  25113. 2,
  25114. 3,
  25115. 3,
  25116. 3,
  25117. 4,
  25118. 7,
  25119. 8,
  25120. 9,
  25121. 9,
  25122. 10,
  25123. 11 // 23: B + 12
  25124. ];
  25125. // uv as integer step (not pixels !)
  25126. var ico_vertexuv = [
  25127. 5, 1, 3, 1, 6, 4, 0, 0,
  25128. 5, 3, 4, 2, 2, 2, 4, 0,
  25129. 2, 0, 1, 1, 6, 0, 6, 2,
  25130. // vertex alias (for same vertex on different faces)
  25131. 0, 4,
  25132. 3, 3,
  25133. 4, 4,
  25134. 3, 1,
  25135. 4, 2,
  25136. 4, 4,
  25137. 0, 2,
  25138. 1, 1,
  25139. 2, 2,
  25140. 3, 3,
  25141. 1, 3,
  25142. 2, 4 // 23: B + 12
  25143. ];
  25144. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25145. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25146. // First island of uv mapping
  25147. // v = 4h 3+ 2
  25148. // v = 3h 9+ 4
  25149. // v = 2h 9+ 5 B
  25150. // v = 1h 9 1 0
  25151. // v = 0h 3 8 7 A
  25152. // u = 0 1 2 3 4 5 6 *a
  25153. // Second island of uv mapping
  25154. // v = 4h 0+ B+ 4+
  25155. // v = 3h A+ 2+
  25156. // v = 2h 7+ 6 3+
  25157. // v = 1h 8+ 3+
  25158. // v = 0h
  25159. // u = 0 1 2 3 4 5 6 *a
  25160. // Face layout on texture UV mapping
  25161. // ============
  25162. // \ 4 /\ 16 / ======
  25163. // \ / \ / /\ 11 /
  25164. // \/ 7 \/ / \ /
  25165. // ======= / 10 \/
  25166. // /\ 17 /\ =======
  25167. // / \ / \ \ 15 /\
  25168. // / 8 \/ 12 \ \ / \
  25169. // ============ \/ 6 \
  25170. // \ 18 /\ ============
  25171. // \ / \ \ 5 /\ 0 /
  25172. // \/ 13 \ \ / \ /
  25173. // ======= \/ 1 \/
  25174. // =============
  25175. // /\ 19 /\ 2 /\
  25176. // / \ / \ / \
  25177. // / 14 \/ 9 \/ 3 \
  25178. // ===================
  25179. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25180. var ustep = 138 / 1024;
  25181. var vstep = 239 / 1024;
  25182. var uoffset = 60 / 1024;
  25183. var voffset = 26 / 1024;
  25184. // Second island should have margin, not to touch the first island
  25185. // avoid any borderline artefact in pixel rounding
  25186. var island_u_offset = -40 / 1024;
  25187. var island_v_offset = +20 / 1024;
  25188. // face is either island 0 or 1 :
  25189. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25190. var island = [
  25191. 0, 0, 0, 0, 1,
  25192. 0, 0, 1, 1, 0,
  25193. 0, 0, 1, 1, 0,
  25194. 0, 1, 1, 1, 0 // 15 - 19
  25195. ];
  25196. var indices = [];
  25197. var positions = [];
  25198. var normals = [];
  25199. var uvs = [];
  25200. var current_indice = 0;
  25201. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25202. var face_vertex_pos = new Array(3);
  25203. var face_vertex_uv = new Array(3);
  25204. var v012;
  25205. for (v012 = 0; v012 < 3; v012++) {
  25206. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25207. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25208. }
  25209. // create all with normals
  25210. for (var face = 0; face < 20; face++) {
  25211. // 3 vertex per face
  25212. for (v012 = 0; v012 < 3; v012++) {
  25213. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25214. var v_id = ico_indices[3 * face + v012];
  25215. // vertex have 3D position (x,y,z)
  25216. 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]);
  25217. // Normalize to get normal, then scale to radius
  25218. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25219. // uv Coordinates from vertex ID
  25220. 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);
  25221. }
  25222. // Subdivide the face (interpolate pos, norm, uv)
  25223. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25224. // - norm is linear interpolation of vertex corner normal
  25225. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25226. // - uv is linear interpolation
  25227. //
  25228. // Topology is as below for sub-divide by 2
  25229. // vertex shown as v0,v1,v2
  25230. // interp index is i1 to progress in range [v0,v1[
  25231. // interp index is i2 to progress in range [v0,v2[
  25232. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25233. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25234. //
  25235. //
  25236. // i2 v2
  25237. // ^ ^
  25238. // / / \
  25239. // / / \
  25240. // / / \
  25241. // / / (0,1) \
  25242. // / #---------\
  25243. // / / \ (0,0)'/ \
  25244. // / / \ / \
  25245. // / / \ / \
  25246. // / / (0,0) \ / (1,0) \
  25247. // / #---------#---------\
  25248. // v0 v1
  25249. //
  25250. // --------------------> i1
  25251. //
  25252. // interp of (i1,i2):
  25253. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25254. // along i1 : lerp(x0,x1, i1/(S-i2))
  25255. //
  25256. // centroid of triangle is needed to get help normal computation
  25257. // (c1,c2) are used for centroid location
  25258. var interp_vertex = function (i1, i2, c1, c2) {
  25259. // vertex is interpolated from
  25260. // - face_vertex_pos[0..2]
  25261. // - face_vertex_uv[0..2]
  25262. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25263. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25264. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25265. pos_interp.normalize();
  25266. var vertex_normal;
  25267. if (flat) {
  25268. // in flat mode, recalculate normal as face centroid normal
  25269. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25270. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25271. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25272. }
  25273. else {
  25274. // in smooth mode, recalculate normal from each single vertex position
  25275. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25276. }
  25277. // Vertex normal need correction due to X,Y,Z radius scaling
  25278. vertex_normal.x /= radiusX;
  25279. vertex_normal.y /= radiusY;
  25280. vertex_normal.z /= radiusZ;
  25281. vertex_normal.normalize();
  25282. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25283. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25284. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25285. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25286. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25287. uvs.push(uv_interp.x, uv_interp.y);
  25288. // push each vertex has member of a face
  25289. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25290. indices.push(current_indice);
  25291. current_indice++;
  25292. };
  25293. for (var i2 = 0; i2 < subdivisions; i2++) {
  25294. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25295. // face : (i1,i2) for /\ :
  25296. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25297. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25298. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25299. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25300. if (i1 + i2 + 1 < subdivisions) {
  25301. // face : (i1,i2)' for \/ :
  25302. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25303. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25304. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25305. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25306. }
  25307. }
  25308. }
  25309. }
  25310. // Sides
  25311. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25312. // Result
  25313. var vertexData = new VertexData();
  25314. vertexData.indices = indices;
  25315. vertexData.positions = positions;
  25316. vertexData.normals = normals;
  25317. vertexData.uvs = uvs;
  25318. return vertexData;
  25319. };
  25320. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25321. VertexData.CreatePolyhedron = function (options) {
  25322. // provided polyhedron types :
  25323. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25324. // 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)
  25325. var polyhedra = [];
  25326. 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]] };
  25327. 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]] };
  25328. polyhedra[2] = {
  25329. 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]],
  25330. 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]]
  25331. };
  25332. polyhedra[3] = {
  25333. 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]],
  25334. 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]]
  25335. };
  25336. polyhedra[4] = {
  25337. 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]],
  25338. 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]]
  25339. };
  25340. 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]] };
  25341. 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]] };
  25342. 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]] };
  25343. 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]] };
  25344. 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]] };
  25345. 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]] };
  25346. 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]] };
  25347. 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]] };
  25348. 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]] };
  25349. polyhedra[14] = {
  25350. 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]],
  25351. 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]]
  25352. };
  25353. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25354. var size = options.size;
  25355. var sizeX = options.sizeX || size || 1;
  25356. var sizeY = options.sizeY || size || 1;
  25357. var sizeZ = options.sizeZ || size || 1;
  25358. var data = options.custom || polyhedra[type];
  25359. var nbfaces = data.face.length;
  25360. var faceUV = options.faceUV || new Array(nbfaces);
  25361. var faceColors = options.faceColors;
  25362. var flat = (options.flat === undefined) ? true : options.flat;
  25363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25364. var positions = [];
  25365. var indices = [];
  25366. var normals = [];
  25367. var uvs = [];
  25368. var colors = [];
  25369. var index = 0;
  25370. var faceIdx = 0; // face cursor in the array "indexes"
  25371. var indexes = [];
  25372. var i = 0;
  25373. var f = 0;
  25374. var u, v, ang, x, y, tmp;
  25375. // default face colors and UV if undefined
  25376. if (flat) {
  25377. for (f = 0; f < nbfaces; f++) {
  25378. if (faceColors && faceColors[f] === undefined) {
  25379. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25380. }
  25381. if (faceUV && faceUV[f] === undefined) {
  25382. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25383. }
  25384. }
  25385. }
  25386. if (!flat) {
  25387. for (i = 0; i < data.vertex.length; i++) {
  25388. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25389. uvs.push(0, 0);
  25390. }
  25391. for (f = 0; f < nbfaces; f++) {
  25392. for (i = 0; i < data.face[f].length - 2; i++) {
  25393. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25394. }
  25395. }
  25396. }
  25397. else {
  25398. for (f = 0; f < nbfaces; f++) {
  25399. var fl = data.face[f].length; // number of vertices of the current face
  25400. ang = 2 * Math.PI / fl;
  25401. x = 0.5 * Math.tan(ang / 2);
  25402. y = 0.5;
  25403. // positions, uvs, colors
  25404. for (i = 0; i < fl; i++) {
  25405. // positions
  25406. 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);
  25407. indexes.push(index);
  25408. index++;
  25409. // uvs
  25410. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25411. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25412. uvs.push(u, v);
  25413. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25414. y = x * Math.sin(ang) + y * Math.cos(ang);
  25415. x = tmp;
  25416. // colors
  25417. if (faceColors) {
  25418. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25419. }
  25420. }
  25421. // indices from indexes
  25422. for (i = 0; i < fl - 2; i++) {
  25423. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25424. }
  25425. faceIdx += fl;
  25426. }
  25427. }
  25428. VertexData.ComputeNormals(positions, indices, normals);
  25429. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25430. var vertexData = new VertexData();
  25431. vertexData.positions = positions;
  25432. vertexData.indices = indices;
  25433. vertexData.normals = normals;
  25434. vertexData.uvs = uvs;
  25435. if (faceColors && flat) {
  25436. vertexData.colors = colors;
  25437. }
  25438. return vertexData;
  25439. };
  25440. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25441. VertexData.CreateTorusKnot = function (options) {
  25442. var indices = [];
  25443. var positions = [];
  25444. var normals = [];
  25445. var uvs = [];
  25446. var radius = options.radius || 2;
  25447. var tube = options.tube || 0.5;
  25448. var radialSegments = options.radialSegments || 32;
  25449. var tubularSegments = options.tubularSegments || 32;
  25450. var p = options.p || 2;
  25451. var q = options.q || 3;
  25452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25453. // Helper
  25454. var getPos = function (angle) {
  25455. var cu = Math.cos(angle);
  25456. var su = Math.sin(angle);
  25457. var quOverP = q / p * angle;
  25458. var cs = Math.cos(quOverP);
  25459. var tx = radius * (2 + cs) * 0.5 * cu;
  25460. var ty = radius * (2 + cs) * su * 0.5;
  25461. var tz = radius * Math.sin(quOverP) * 0.5;
  25462. return new BABYLON.Vector3(tx, ty, tz);
  25463. };
  25464. // Vertices
  25465. var i;
  25466. var j;
  25467. for (i = 0; i <= radialSegments; i++) {
  25468. var modI = i % radialSegments;
  25469. var u = modI / radialSegments * 2 * p * Math.PI;
  25470. var p1 = getPos(u);
  25471. var p2 = getPos(u + 0.01);
  25472. var tang = p2.subtract(p1);
  25473. var n = p2.add(p1);
  25474. var bitan = BABYLON.Vector3.Cross(tang, n);
  25475. n = BABYLON.Vector3.Cross(bitan, tang);
  25476. bitan.normalize();
  25477. n.normalize();
  25478. for (j = 0; j < tubularSegments; j++) {
  25479. var modJ = j % tubularSegments;
  25480. var v = modJ / tubularSegments * 2 * Math.PI;
  25481. var cx = -tube * Math.cos(v);
  25482. var cy = tube * Math.sin(v);
  25483. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25484. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25485. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25486. uvs.push(i / radialSegments);
  25487. uvs.push(j / tubularSegments);
  25488. }
  25489. }
  25490. for (i = 0; i < radialSegments; i++) {
  25491. for (j = 0; j < tubularSegments; j++) {
  25492. var jNext = (j + 1) % tubularSegments;
  25493. var a = i * tubularSegments + j;
  25494. var b = (i + 1) * tubularSegments + j;
  25495. var c = (i + 1) * tubularSegments + jNext;
  25496. var d = i * tubularSegments + jNext;
  25497. indices.push(d);
  25498. indices.push(b);
  25499. indices.push(a);
  25500. indices.push(d);
  25501. indices.push(c);
  25502. indices.push(b);
  25503. }
  25504. }
  25505. // Normals
  25506. VertexData.ComputeNormals(positions, indices, normals);
  25507. // Sides
  25508. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25509. // Result
  25510. var vertexData = new VertexData();
  25511. vertexData.indices = indices;
  25512. vertexData.positions = positions;
  25513. vertexData.normals = normals;
  25514. vertexData.uvs = uvs;
  25515. return vertexData;
  25516. };
  25517. // Tools
  25518. /**
  25519. * @param {any} - positions (number[] or Float32Array)
  25520. * @param {any} - indices (number[] or Uint16Array)
  25521. * @param {any} - normals (number[] or Float32Array)
  25522. */
  25523. VertexData.ComputeNormals = function (positions, indices, normals) {
  25524. var index = 0;
  25525. var p1p2x = 0.0;
  25526. var p1p2y = 0.0;
  25527. var p1p2z = 0.0;
  25528. var p3p2x = 0.0;
  25529. var p3p2y = 0.0;
  25530. var p3p2z = 0.0;
  25531. var faceNormalx = 0.0;
  25532. var faceNormaly = 0.0;
  25533. var faceNormalz = 0.0;
  25534. var length = 0.0;
  25535. var i1 = 0;
  25536. var i2 = 0;
  25537. var i3 = 0;
  25538. for (index = 0; index < positions.length; index++) {
  25539. normals[index] = 0.0;
  25540. }
  25541. // indice triplet = 1 face
  25542. var nbFaces = indices.length / 3;
  25543. for (index = 0; index < nbFaces; index++) {
  25544. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25545. i2 = indices[index * 3 + 1];
  25546. i3 = indices[index * 3 + 2];
  25547. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25548. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25549. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25550. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25551. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25552. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25553. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25554. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25555. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25556. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25557. length = (length === 0) ? 1.0 : length;
  25558. faceNormalx /= length; // normalize this normal
  25559. faceNormaly /= length;
  25560. faceNormalz /= length;
  25561. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25562. normals[i1 * 3 + 1] += faceNormaly;
  25563. normals[i1 * 3 + 2] += faceNormalz;
  25564. normals[i2 * 3] += faceNormalx;
  25565. normals[i2 * 3 + 1] += faceNormaly;
  25566. normals[i2 * 3 + 2] += faceNormalz;
  25567. normals[i3 * 3] += faceNormalx;
  25568. normals[i3 * 3 + 1] += faceNormaly;
  25569. normals[i3 * 3 + 2] += faceNormalz;
  25570. }
  25571. // last normalization of each normal
  25572. for (index = 0; index < normals.length / 3; index++) {
  25573. faceNormalx = normals[index * 3];
  25574. faceNormaly = normals[index * 3 + 1];
  25575. faceNormalz = normals[index * 3 + 2];
  25576. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25577. length = (length === 0) ? 1.0 : length;
  25578. faceNormalx /= length;
  25579. faceNormaly /= length;
  25580. faceNormalz /= length;
  25581. normals[index * 3] = faceNormalx;
  25582. normals[index * 3 + 1] = faceNormaly;
  25583. normals[index * 3 + 2] = faceNormalz;
  25584. }
  25585. };
  25586. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25587. var li = indices.length;
  25588. var ln = normals.length;
  25589. var i;
  25590. var n;
  25591. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25592. switch (sideOrientation) {
  25593. case BABYLON.Mesh.FRONTSIDE:
  25594. // nothing changed
  25595. break;
  25596. case BABYLON.Mesh.BACKSIDE:
  25597. var tmp;
  25598. // indices
  25599. for (i = 0; i < li; i += 3) {
  25600. tmp = indices[i];
  25601. indices[i] = indices[i + 2];
  25602. indices[i + 2] = tmp;
  25603. }
  25604. // normals
  25605. for (n = 0; n < ln; n++) {
  25606. normals[n] = -normals[n];
  25607. }
  25608. break;
  25609. case BABYLON.Mesh.DOUBLESIDE:
  25610. // positions
  25611. var lp = positions.length;
  25612. var l = lp / 3;
  25613. for (var p = 0; p < lp; p++) {
  25614. positions[lp + p] = positions[p];
  25615. }
  25616. // indices
  25617. for (i = 0; i < li; i += 3) {
  25618. indices[i + li] = indices[i + 2] + l;
  25619. indices[i + 1 + li] = indices[i + 1] + l;
  25620. indices[i + 2 + li] = indices[i] + l;
  25621. }
  25622. // normals
  25623. for (n = 0; n < ln; n++) {
  25624. normals[ln + n] = -normals[n];
  25625. }
  25626. // uvs
  25627. var lu = uvs.length;
  25628. for (var u = 0; u < lu; u++) {
  25629. uvs[u + lu] = uvs[u];
  25630. }
  25631. break;
  25632. }
  25633. };
  25634. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25635. var vertexData = new VertexData();
  25636. // positions
  25637. var positions = parsedVertexData.positions;
  25638. if (positions) {
  25639. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25640. }
  25641. // normals
  25642. var normals = parsedVertexData.normals;
  25643. if (normals) {
  25644. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25645. }
  25646. // uvs
  25647. var uvs = parsedVertexData.uvs;
  25648. if (uvs) {
  25649. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25650. }
  25651. // uv2s
  25652. var uv2s = parsedVertexData.uv2s;
  25653. if (uv2s) {
  25654. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25655. }
  25656. // uv3s
  25657. var uv3s = parsedVertexData.uv3s;
  25658. if (uv3s) {
  25659. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25660. }
  25661. // uv4s
  25662. var uv4s = parsedVertexData.uv4s;
  25663. if (uv4s) {
  25664. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25665. }
  25666. // uv5s
  25667. var uv5s = parsedVertexData.uv5s;
  25668. if (uv5s) {
  25669. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25670. }
  25671. // uv6s
  25672. var uv6s = parsedVertexData.uv6s;
  25673. if (uv6s) {
  25674. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25675. }
  25676. // colors
  25677. var colors = parsedVertexData.colors;
  25678. if (colors) {
  25679. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25680. }
  25681. // matricesIndices
  25682. var matricesIndices = parsedVertexData.matricesIndices;
  25683. if (matricesIndices) {
  25684. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25685. }
  25686. // matricesWeights
  25687. var matricesWeights = parsedVertexData.matricesWeights;
  25688. if (matricesWeights) {
  25689. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25690. }
  25691. // indices
  25692. var indices = parsedVertexData.indices;
  25693. if (indices) {
  25694. vertexData.indices = indices;
  25695. }
  25696. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25697. };
  25698. return VertexData;
  25699. })();
  25700. BABYLON.VertexData = VertexData;
  25701. })(BABYLON || (BABYLON = {}));
  25702. var BABYLON;
  25703. (function (BABYLON) {
  25704. var Tags = (function () {
  25705. function Tags() {
  25706. }
  25707. Tags.EnableFor = function (obj) {
  25708. obj._tags = obj._tags || {};
  25709. obj.hasTags = function () {
  25710. return Tags.HasTags(obj);
  25711. };
  25712. obj.addTags = function (tagsString) {
  25713. return Tags.AddTagsTo(obj, tagsString);
  25714. };
  25715. obj.removeTags = function (tagsString) {
  25716. return Tags.RemoveTagsFrom(obj, tagsString);
  25717. };
  25718. obj.matchesTagsQuery = function (tagsQuery) {
  25719. return Tags.MatchesQuery(obj, tagsQuery);
  25720. };
  25721. };
  25722. Tags.DisableFor = function (obj) {
  25723. delete obj._tags;
  25724. delete obj.hasTags;
  25725. delete obj.addTags;
  25726. delete obj.removeTags;
  25727. delete obj.matchesTagsQuery;
  25728. };
  25729. Tags.HasTags = function (obj) {
  25730. if (!obj._tags) {
  25731. return false;
  25732. }
  25733. return !BABYLON.Tools.IsEmpty(obj._tags);
  25734. };
  25735. Tags.GetTags = function (obj, asString) {
  25736. if (asString === void 0) { asString = true; }
  25737. if (!obj._tags) {
  25738. return null;
  25739. }
  25740. if (asString) {
  25741. var tagsArray = [];
  25742. for (var tag in obj._tags) {
  25743. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25744. tagsArray.push(tag);
  25745. }
  25746. }
  25747. return tagsArray.join(" ");
  25748. }
  25749. else {
  25750. return obj._tags;
  25751. }
  25752. };
  25753. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25754. // a tag cannot start with '||', '&&', and '!'
  25755. // it cannot contain whitespaces
  25756. Tags.AddTagsTo = function (obj, tagsString) {
  25757. if (!tagsString) {
  25758. return;
  25759. }
  25760. if (typeof tagsString !== "string") {
  25761. return;
  25762. }
  25763. var tags = tagsString.split(" ");
  25764. for (var t in tags) {
  25765. Tags._AddTagTo(obj, tags[t]);
  25766. }
  25767. };
  25768. Tags._AddTagTo = function (obj, tag) {
  25769. tag = tag.trim();
  25770. if (tag === "" || tag === "true" || tag === "false") {
  25771. return;
  25772. }
  25773. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25774. return;
  25775. }
  25776. Tags.EnableFor(obj);
  25777. obj._tags[tag] = true;
  25778. };
  25779. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25780. if (!Tags.HasTags(obj)) {
  25781. return;
  25782. }
  25783. var tags = tagsString.split(" ");
  25784. for (var t in tags) {
  25785. Tags._RemoveTagFrom(obj, tags[t]);
  25786. }
  25787. };
  25788. Tags._RemoveTagFrom = function (obj, tag) {
  25789. delete obj._tags[tag];
  25790. };
  25791. Tags.MatchesQuery = function (obj, tagsQuery) {
  25792. if (tagsQuery === undefined) {
  25793. return true;
  25794. }
  25795. if (tagsQuery === "") {
  25796. return Tags.HasTags(obj);
  25797. }
  25798. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25799. };
  25800. return Tags;
  25801. })();
  25802. BABYLON.Tags = Tags;
  25803. })(BABYLON || (BABYLON = {}));
  25804. var BABYLON;
  25805. (function (BABYLON) {
  25806. var Internals;
  25807. (function (Internals) {
  25808. var AndOrNotEvaluator = (function () {
  25809. function AndOrNotEvaluator() {
  25810. }
  25811. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25812. if (!query.match(/\([^\(\)]*\)/g)) {
  25813. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25814. }
  25815. else {
  25816. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25817. // remove parenthesis
  25818. r = r.slice(1, r.length - 1);
  25819. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25820. });
  25821. }
  25822. if (query === "true") {
  25823. return true;
  25824. }
  25825. if (query === "false") {
  25826. return false;
  25827. }
  25828. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25829. };
  25830. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25831. evaluateCallback = evaluateCallback || (function (r) {
  25832. return r === "true" ? true : false;
  25833. });
  25834. var result;
  25835. var or = parenthesisContent.split("||");
  25836. for (var i in or) {
  25837. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25838. var and = ori.split("&&");
  25839. if (and.length > 1) {
  25840. for (var j = 0; j < and.length; ++j) {
  25841. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25842. if (andj !== "true" && andj !== "false") {
  25843. if (andj[0] === "!") {
  25844. result = !evaluateCallback(andj.substring(1));
  25845. }
  25846. else {
  25847. result = evaluateCallback(andj);
  25848. }
  25849. }
  25850. else {
  25851. result = andj === "true" ? true : false;
  25852. }
  25853. if (!result) {
  25854. ori = "false";
  25855. break;
  25856. }
  25857. }
  25858. }
  25859. if (result || ori === "true") {
  25860. result = true;
  25861. break;
  25862. }
  25863. // result equals false (or undefined)
  25864. if (ori !== "true" && ori !== "false") {
  25865. if (ori[0] === "!") {
  25866. result = !evaluateCallback(ori.substring(1));
  25867. }
  25868. else {
  25869. result = evaluateCallback(ori);
  25870. }
  25871. }
  25872. else {
  25873. result = ori === "true" ? true : false;
  25874. }
  25875. }
  25876. // the whole parenthesis scope is replaced by 'true' or 'false'
  25877. return result ? "true" : "false";
  25878. };
  25879. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25880. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25881. // remove whitespaces
  25882. r = r.replace(/[\s]/g, function () { return ""; });
  25883. return r.length % 2 ? "!" : "";
  25884. });
  25885. booleanString = booleanString.trim();
  25886. if (booleanString === "!true") {
  25887. booleanString = "false";
  25888. }
  25889. else if (booleanString === "!false") {
  25890. booleanString = "true";
  25891. }
  25892. return booleanString;
  25893. };
  25894. return AndOrNotEvaluator;
  25895. })();
  25896. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25897. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25898. })(BABYLON || (BABYLON = {}));
  25899. var BABYLON;
  25900. (function (BABYLON) {
  25901. var PostProcessRenderPass = (function () {
  25902. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25903. this._enabled = true;
  25904. this._refCount = 0;
  25905. this._name = name;
  25906. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25907. this.setRenderList(renderList);
  25908. this._renderTexture.onBeforeRender = beforeRender;
  25909. this._renderTexture.onAfterRender = afterRender;
  25910. this._scene = scene;
  25911. this._renderList = renderList;
  25912. }
  25913. // private
  25914. PostProcessRenderPass.prototype._incRefCount = function () {
  25915. if (this._refCount === 0) {
  25916. this._scene.customRenderTargets.push(this._renderTexture);
  25917. }
  25918. return ++this._refCount;
  25919. };
  25920. PostProcessRenderPass.prototype._decRefCount = function () {
  25921. this._refCount--;
  25922. if (this._refCount <= 0) {
  25923. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25924. }
  25925. return this._refCount;
  25926. };
  25927. PostProcessRenderPass.prototype._update = function () {
  25928. this.setRenderList(this._renderList);
  25929. };
  25930. // public
  25931. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25932. this._renderTexture.renderList = renderList;
  25933. };
  25934. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25935. return this._renderTexture;
  25936. };
  25937. return PostProcessRenderPass;
  25938. })();
  25939. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25940. })(BABYLON || (BABYLON = {}));
  25941. var BABYLON;
  25942. (function (BABYLON) {
  25943. var PostProcessRenderEffect = (function () {
  25944. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25945. this._engine = engine;
  25946. this._name = name;
  25947. this._singleInstance = singleInstance || true;
  25948. this._getPostProcess = getPostProcess;
  25949. this._cameras = [];
  25950. this._indicesForCamera = [];
  25951. this._postProcesses = {};
  25952. this._renderPasses = {};
  25953. this._renderEffectAsPasses = {};
  25954. }
  25955. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25956. get: function () {
  25957. for (var index in this._postProcesses) {
  25958. if (!this._postProcesses[index].isSupported) {
  25959. return false;
  25960. }
  25961. }
  25962. return true;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. PostProcessRenderEffect.prototype._update = function () {
  25968. for (var renderPassName in this._renderPasses) {
  25969. this._renderPasses[renderPassName]._update();
  25970. }
  25971. };
  25972. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25973. this._renderPasses[renderPass._name] = renderPass;
  25974. this._linkParameters();
  25975. };
  25976. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25977. delete this._renderPasses[renderPass._name];
  25978. this._linkParameters();
  25979. };
  25980. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25981. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25982. this._linkParameters();
  25983. };
  25984. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25985. for (var renderPassName in this._renderPasses) {
  25986. if (renderPassName === passName) {
  25987. return this._renderPasses[passName];
  25988. }
  25989. }
  25990. };
  25991. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25992. this._renderPasses = {};
  25993. this._linkParameters();
  25994. };
  25995. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25996. var cameraKey;
  25997. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25998. for (var i = 0; i < _cam.length; i++) {
  25999. var camera = _cam[i];
  26000. var cameraName = camera.name;
  26001. if (this._singleInstance) {
  26002. cameraKey = 0;
  26003. }
  26004. else {
  26005. cameraKey = cameraName;
  26006. }
  26007. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26008. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26009. if (!this._indicesForCamera[cameraName]) {
  26010. this._indicesForCamera[cameraName] = [];
  26011. }
  26012. this._indicesForCamera[cameraName].push(index);
  26013. if (this._cameras.indexOf(camera) === -1) {
  26014. this._cameras[cameraName] = camera;
  26015. }
  26016. for (var passName in this._renderPasses) {
  26017. this._renderPasses[passName]._incRefCount();
  26018. }
  26019. }
  26020. this._linkParameters();
  26021. };
  26022. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26023. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26024. for (var i = 0; i < _cam.length; i++) {
  26025. var camera = _cam[i];
  26026. var cameraName = camera.name;
  26027. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26028. var index = this._cameras.indexOf(cameraName);
  26029. this._indicesForCamera.splice(index, 1);
  26030. this._cameras.splice(index, 1);
  26031. for (var passName in this._renderPasses) {
  26032. this._renderPasses[passName]._decRefCount();
  26033. }
  26034. }
  26035. };
  26036. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26037. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26038. for (var i = 0; i < _cam.length; i++) {
  26039. var camera = _cam[i];
  26040. var cameraName = camera.name;
  26041. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26042. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26043. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26044. }
  26045. }
  26046. for (var passName in this._renderPasses) {
  26047. this._renderPasses[passName]._incRefCount();
  26048. }
  26049. }
  26050. };
  26051. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26052. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26053. for (var i = 0; i < _cam.length; i++) {
  26054. var camera = _cam[i];
  26055. var cameraName = camera.Name;
  26056. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26057. for (var passName in this._renderPasses) {
  26058. this._renderPasses[passName]._decRefCount();
  26059. }
  26060. }
  26061. };
  26062. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26063. if (this._singleInstance) {
  26064. return this._postProcesses[0];
  26065. }
  26066. else {
  26067. return this._postProcesses[camera.name];
  26068. }
  26069. };
  26070. PostProcessRenderEffect.prototype._linkParameters = function () {
  26071. var _this = this;
  26072. for (var index in this._postProcesses) {
  26073. if (this.applyParameters) {
  26074. this.applyParameters(this._postProcesses[index]);
  26075. }
  26076. this._postProcesses[index].onBeforeRender = function (effect) {
  26077. _this._linkTextures(effect);
  26078. };
  26079. }
  26080. };
  26081. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26082. for (var renderPassName in this._renderPasses) {
  26083. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26084. }
  26085. for (var renderEffectName in this._renderEffectAsPasses) {
  26086. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26087. }
  26088. };
  26089. return PostProcessRenderEffect;
  26090. })();
  26091. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26092. })(BABYLON || (BABYLON = {}));
  26093. var BABYLON;
  26094. (function (BABYLON) {
  26095. var PostProcessRenderPipeline = (function () {
  26096. function PostProcessRenderPipeline(engine, name) {
  26097. this._engine = engine;
  26098. this._name = name;
  26099. this._renderEffects = {};
  26100. this._renderEffectsForIsolatedPass = {};
  26101. this._cameras = [];
  26102. }
  26103. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26104. get: function () {
  26105. for (var renderEffectName in this._renderEffects) {
  26106. if (!this._renderEffects[renderEffectName].isSupported) {
  26107. return false;
  26108. }
  26109. }
  26110. return true;
  26111. },
  26112. enumerable: true,
  26113. configurable: true
  26114. });
  26115. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26116. this._renderEffects[renderEffect._name] = renderEffect;
  26117. };
  26118. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26119. var renderEffects = this._renderEffects[renderEffectName];
  26120. if (!renderEffects) {
  26121. return;
  26122. }
  26123. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26124. };
  26125. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26126. var renderEffects = this._renderEffects[renderEffectName];
  26127. if (!renderEffects) {
  26128. return;
  26129. }
  26130. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26131. };
  26132. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26133. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26134. var indicesToDelete = [];
  26135. var i;
  26136. for (i = 0; i < _cam.length; i++) {
  26137. var camera = _cam[i];
  26138. var cameraName = camera.name;
  26139. if (this._cameras.indexOf(camera) === -1) {
  26140. this._cameras[cameraName] = camera;
  26141. }
  26142. else if (unique) {
  26143. indicesToDelete.push(i);
  26144. }
  26145. }
  26146. for (i = 0; i < indicesToDelete.length; i++) {
  26147. cameras.splice(indicesToDelete[i], 1);
  26148. }
  26149. for (var renderEffectName in this._renderEffects) {
  26150. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26151. }
  26152. };
  26153. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26154. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26155. for (var renderEffectName in this._renderEffects) {
  26156. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26157. }
  26158. for (var i = 0; i < _cam.length; i++) {
  26159. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26160. }
  26161. };
  26162. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26163. var _this = this;
  26164. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26165. var pass = null;
  26166. var renderEffectName;
  26167. for (renderEffectName in this._renderEffects) {
  26168. pass = this._renderEffects[renderEffectName].getPass(passName);
  26169. if (pass != null) {
  26170. break;
  26171. }
  26172. }
  26173. if (pass === null) {
  26174. return;
  26175. }
  26176. for (renderEffectName in this._renderEffects) {
  26177. this._renderEffects[renderEffectName]._disable(_cam);
  26178. }
  26179. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26180. for (var i = 0; i < _cam.length; i++) {
  26181. var camera = _cam[i];
  26182. var cameraName = camera.name;
  26183. 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); });
  26184. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26185. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26186. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26187. }
  26188. };
  26189. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26190. var _this = this;
  26191. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26192. for (var i = 0; i < _cam.length; i++) {
  26193. var camera = _cam[i];
  26194. var cameraName = camera.name;
  26195. 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); });
  26196. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26197. }
  26198. for (var renderEffectName in this._renderEffects) {
  26199. this._renderEffects[renderEffectName]._enable(_cam);
  26200. }
  26201. };
  26202. PostProcessRenderPipeline.prototype._update = function () {
  26203. for (var renderEffectName in this._renderEffects) {
  26204. this._renderEffects[renderEffectName]._update();
  26205. }
  26206. for (var i = 0; i < this._cameras.length; i++) {
  26207. var cameraName = this._cameras[i].name;
  26208. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26209. this._renderEffectsForIsolatedPass[cameraName]._update();
  26210. }
  26211. }
  26212. };
  26213. PostProcessRenderPipeline.prototype.dispose = function () {
  26214. // Must be implemented by children
  26215. };
  26216. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26217. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26218. return PostProcessRenderPipeline;
  26219. })();
  26220. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26221. })(BABYLON || (BABYLON = {}));
  26222. var BABYLON;
  26223. (function (BABYLON) {
  26224. var PostProcessRenderPipelineManager = (function () {
  26225. function PostProcessRenderPipelineManager() {
  26226. this._renderPipelines = {};
  26227. }
  26228. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26229. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26230. };
  26231. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26232. var renderPipeline = this._renderPipelines[renderPipelineName];
  26233. if (!renderPipeline) {
  26234. return;
  26235. }
  26236. renderPipeline._attachCameras(cameras, unique);
  26237. };
  26238. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26239. var renderPipeline = this._renderPipelines[renderPipelineName];
  26240. if (!renderPipeline) {
  26241. return;
  26242. }
  26243. renderPipeline._detachCameras(cameras);
  26244. };
  26245. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26246. var renderPipeline = this._renderPipelines[renderPipelineName];
  26247. if (!renderPipeline) {
  26248. return;
  26249. }
  26250. renderPipeline._enableEffect(renderEffectName, cameras);
  26251. };
  26252. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26253. var renderPipeline = this._renderPipelines[renderPipelineName];
  26254. if (!renderPipeline) {
  26255. return;
  26256. }
  26257. renderPipeline._disableEffect(renderEffectName, cameras);
  26258. };
  26259. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26260. var renderPipeline = this._renderPipelines[renderPipelineName];
  26261. if (!renderPipeline) {
  26262. return;
  26263. }
  26264. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26265. };
  26266. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26267. var renderPipeline = this._renderPipelines[renderPipelineName];
  26268. if (!renderPipeline) {
  26269. return;
  26270. }
  26271. renderPipeline._disableDisplayOnlyPass(cameras);
  26272. };
  26273. PostProcessRenderPipelineManager.prototype.update = function () {
  26274. for (var renderPipelineName in this._renderPipelines) {
  26275. var pipeline = this._renderPipelines[renderPipelineName];
  26276. if (!pipeline.isSupported) {
  26277. pipeline.dispose();
  26278. delete this._renderPipelines[renderPipelineName];
  26279. }
  26280. else {
  26281. pipeline._update();
  26282. }
  26283. }
  26284. };
  26285. return PostProcessRenderPipelineManager;
  26286. })();
  26287. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26288. })(BABYLON || (BABYLON = {}));
  26289. var BABYLON;
  26290. (function (BABYLON) {
  26291. var BoundingBoxRenderer = (function () {
  26292. function BoundingBoxRenderer(scene) {
  26293. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26294. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26295. this.showBackLines = true;
  26296. this.renderList = new BABYLON.SmartArray(32);
  26297. this._scene = scene;
  26298. }
  26299. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26300. if (this._colorShader) {
  26301. return;
  26302. }
  26303. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26304. attributes: ["position"],
  26305. uniforms: ["worldViewProjection", "color"]
  26306. });
  26307. var engine = this._scene.getEngine();
  26308. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26309. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26310. 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]);
  26311. };
  26312. BoundingBoxRenderer.prototype.reset = function () {
  26313. this.renderList.reset();
  26314. };
  26315. BoundingBoxRenderer.prototype.render = function () {
  26316. if (this.renderList.length === 0) {
  26317. return;
  26318. }
  26319. this._prepareRessources();
  26320. if (!this._colorShader.isReady()) {
  26321. return;
  26322. }
  26323. var engine = this._scene.getEngine();
  26324. engine.setDepthWrite(false);
  26325. this._colorShader._preBind();
  26326. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26327. var boundingBox = this.renderList.data[boundingBoxIndex];
  26328. var min = boundingBox.minimum;
  26329. var max = boundingBox.maximum;
  26330. var diff = max.subtract(min);
  26331. var median = min.add(diff.scale(0.5));
  26332. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26333. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26334. .multiply(boundingBox.getWorldMatrix());
  26335. // VBOs
  26336. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26337. if (this.showBackLines) {
  26338. // Back
  26339. engine.setDepthFunctionToGreaterOrEqual();
  26340. this._scene.resetCachedMaterial();
  26341. this._colorShader.setColor4("color", this.backColor.toColor4());
  26342. this._colorShader.bind(worldMatrix);
  26343. // Draw order
  26344. engine.draw(false, 0, 24);
  26345. }
  26346. // Front
  26347. engine.setDepthFunctionToLess();
  26348. this._scene.resetCachedMaterial();
  26349. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26350. this._colorShader.bind(worldMatrix);
  26351. // Draw order
  26352. engine.draw(false, 0, 24);
  26353. }
  26354. this._colorShader.unbind();
  26355. engine.setDepthFunctionToLessOrEqual();
  26356. engine.setDepthWrite(true);
  26357. };
  26358. BoundingBoxRenderer.prototype.dispose = function () {
  26359. if (!this._colorShader) {
  26360. return;
  26361. }
  26362. this._colorShader.dispose();
  26363. this._vb.dispose();
  26364. this._scene.getEngine()._releaseBuffer(this._ib);
  26365. };
  26366. return BoundingBoxRenderer;
  26367. })();
  26368. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26369. })(BABYLON || (BABYLON = {}));
  26370. var BABYLON;
  26371. (function (BABYLON) {
  26372. var Condition = (function () {
  26373. function Condition(actionManager) {
  26374. this._actionManager = actionManager;
  26375. }
  26376. Condition.prototype.isValid = function () {
  26377. return true;
  26378. };
  26379. Condition.prototype._getProperty = function (propertyPath) {
  26380. return this._actionManager._getProperty(propertyPath);
  26381. };
  26382. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26383. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26384. };
  26385. return Condition;
  26386. })();
  26387. BABYLON.Condition = Condition;
  26388. var ValueCondition = (function (_super) {
  26389. __extends(ValueCondition, _super);
  26390. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26391. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26392. _super.call(this, actionManager);
  26393. this.propertyPath = propertyPath;
  26394. this.value = value;
  26395. this.operator = operator;
  26396. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26397. this._property = this._getProperty(this.propertyPath);
  26398. }
  26399. Object.defineProperty(ValueCondition, "IsEqual", {
  26400. get: function () {
  26401. return ValueCondition._IsEqual;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. Object.defineProperty(ValueCondition, "IsDifferent", {
  26407. get: function () {
  26408. return ValueCondition._IsDifferent;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. Object.defineProperty(ValueCondition, "IsGreater", {
  26414. get: function () {
  26415. return ValueCondition._IsGreater;
  26416. },
  26417. enumerable: true,
  26418. configurable: true
  26419. });
  26420. Object.defineProperty(ValueCondition, "IsLesser", {
  26421. get: function () {
  26422. return ValueCondition._IsLesser;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. // Methods
  26428. ValueCondition.prototype.isValid = function () {
  26429. switch (this.operator) {
  26430. case ValueCondition.IsGreater:
  26431. return this._target[this._property] > this.value;
  26432. case ValueCondition.IsLesser:
  26433. return this._target[this._property] < this.value;
  26434. case ValueCondition.IsEqual:
  26435. case ValueCondition.IsDifferent:
  26436. var check;
  26437. if (this.value.equals) {
  26438. check = this.value.equals(this._target[this._property]);
  26439. }
  26440. else {
  26441. check = this.value === this._target[this._property];
  26442. }
  26443. return this.operator === ValueCondition.IsEqual ? check : !check;
  26444. }
  26445. return false;
  26446. };
  26447. // Statics
  26448. ValueCondition._IsEqual = 0;
  26449. ValueCondition._IsDifferent = 1;
  26450. ValueCondition._IsGreater = 2;
  26451. ValueCondition._IsLesser = 3;
  26452. return ValueCondition;
  26453. })(Condition);
  26454. BABYLON.ValueCondition = ValueCondition;
  26455. var PredicateCondition = (function (_super) {
  26456. __extends(PredicateCondition, _super);
  26457. function PredicateCondition(actionManager, predicate) {
  26458. _super.call(this, actionManager);
  26459. this.predicate = predicate;
  26460. }
  26461. PredicateCondition.prototype.isValid = function () {
  26462. return this.predicate();
  26463. };
  26464. return PredicateCondition;
  26465. })(Condition);
  26466. BABYLON.PredicateCondition = PredicateCondition;
  26467. var StateCondition = (function (_super) {
  26468. __extends(StateCondition, _super);
  26469. function StateCondition(actionManager, target, value) {
  26470. _super.call(this, actionManager);
  26471. this.value = value;
  26472. this._target = target;
  26473. }
  26474. // Methods
  26475. StateCondition.prototype.isValid = function () {
  26476. return this._target.state === this.value;
  26477. };
  26478. return StateCondition;
  26479. })(Condition);
  26480. BABYLON.StateCondition = StateCondition;
  26481. })(BABYLON || (BABYLON = {}));
  26482. var BABYLON;
  26483. (function (BABYLON) {
  26484. var Action = (function () {
  26485. function Action(triggerOptions, condition) {
  26486. this.triggerOptions = triggerOptions;
  26487. if (triggerOptions.parameter) {
  26488. this.trigger = triggerOptions.trigger;
  26489. this._triggerParameter = triggerOptions.parameter;
  26490. }
  26491. else {
  26492. this.trigger = triggerOptions;
  26493. }
  26494. this._nextActiveAction = this;
  26495. this._condition = condition;
  26496. }
  26497. // Methods
  26498. Action.prototype._prepare = function () {
  26499. };
  26500. Action.prototype.getTriggerParameter = function () {
  26501. return this._triggerParameter;
  26502. };
  26503. Action.prototype._executeCurrent = function (evt) {
  26504. if (this._nextActiveAction._condition) {
  26505. var condition = this._nextActiveAction._condition;
  26506. var currentRenderId = this._actionManager.getScene().getRenderId();
  26507. // We cache the current evaluation for the current frame
  26508. if (condition._evaluationId === currentRenderId) {
  26509. if (!condition._currentResult) {
  26510. return;
  26511. }
  26512. }
  26513. else {
  26514. condition._evaluationId = currentRenderId;
  26515. if (!condition.isValid()) {
  26516. condition._currentResult = false;
  26517. return;
  26518. }
  26519. condition._currentResult = true;
  26520. }
  26521. }
  26522. this._nextActiveAction.execute(evt);
  26523. this.skipToNextActiveAction();
  26524. };
  26525. Action.prototype.execute = function (evt) {
  26526. };
  26527. Action.prototype.skipToNextActiveAction = function () {
  26528. if (this._nextActiveAction._child) {
  26529. if (!this._nextActiveAction._child._actionManager) {
  26530. this._nextActiveAction._child._actionManager = this._actionManager;
  26531. }
  26532. this._nextActiveAction = this._nextActiveAction._child;
  26533. }
  26534. else {
  26535. this._nextActiveAction = this;
  26536. }
  26537. };
  26538. Action.prototype.then = function (action) {
  26539. this._child = action;
  26540. action._actionManager = this._actionManager;
  26541. action._prepare();
  26542. return action;
  26543. };
  26544. Action.prototype._getProperty = function (propertyPath) {
  26545. return this._actionManager._getProperty(propertyPath);
  26546. };
  26547. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26548. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26549. };
  26550. return Action;
  26551. })();
  26552. BABYLON.Action = Action;
  26553. })(BABYLON || (BABYLON = {}));
  26554. var BABYLON;
  26555. (function (BABYLON) {
  26556. /**
  26557. * ActionEvent is the event beint sent when an action is triggered.
  26558. */
  26559. var ActionEvent = (function () {
  26560. /**
  26561. * @constructor
  26562. * @param source The mesh or sprite that triggered the action.
  26563. * @param pointerX The X mouse cursor position at the time of the event
  26564. * @param pointerY The Y mouse cursor position at the time of the event
  26565. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26566. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26567. */
  26568. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26569. this.source = source;
  26570. this.pointerX = pointerX;
  26571. this.pointerY = pointerY;
  26572. this.meshUnderPointer = meshUnderPointer;
  26573. this.sourceEvent = sourceEvent;
  26574. this.additionalData = additionalData;
  26575. }
  26576. /**
  26577. * Helper function to auto-create an ActionEvent from a source mesh.
  26578. * @param source The source mesh that triggered the event
  26579. * @param evt {Event} The original (browser) event
  26580. */
  26581. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26582. var scene = source.getScene();
  26583. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26584. };
  26585. /**
  26586. * Helper function to auto-create an ActionEvent from a source mesh.
  26587. * @param source The source sprite that triggered the event
  26588. * @param scene Scene associated with the sprite
  26589. * @param evt {Event} The original (browser) event
  26590. */
  26591. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26592. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26593. };
  26594. /**
  26595. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26596. * @param scene the scene where the event occurred
  26597. * @param evt {Event} The original (browser) event
  26598. */
  26599. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26600. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26601. };
  26602. return ActionEvent;
  26603. })();
  26604. BABYLON.ActionEvent = ActionEvent;
  26605. /**
  26606. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26607. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26608. */
  26609. var ActionManager = (function () {
  26610. function ActionManager(scene) {
  26611. // Members
  26612. this.actions = new Array();
  26613. this._scene = scene;
  26614. scene._actionManagers.push(this);
  26615. }
  26616. Object.defineProperty(ActionManager, "NothingTrigger", {
  26617. get: function () {
  26618. return ActionManager._NothingTrigger;
  26619. },
  26620. enumerable: true,
  26621. configurable: true
  26622. });
  26623. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26624. get: function () {
  26625. return ActionManager._OnPickTrigger;
  26626. },
  26627. enumerable: true,
  26628. configurable: true
  26629. });
  26630. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26631. get: function () {
  26632. return ActionManager._OnLeftPickTrigger;
  26633. },
  26634. enumerable: true,
  26635. configurable: true
  26636. });
  26637. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26638. get: function () {
  26639. return ActionManager._OnRightPickTrigger;
  26640. },
  26641. enumerable: true,
  26642. configurable: true
  26643. });
  26644. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26645. get: function () {
  26646. return ActionManager._OnCenterPickTrigger;
  26647. },
  26648. enumerable: true,
  26649. configurable: true
  26650. });
  26651. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26652. get: function () {
  26653. return ActionManager._OnPickDownTrigger;
  26654. },
  26655. enumerable: true,
  26656. configurable: true
  26657. });
  26658. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26659. get: function () {
  26660. return ActionManager._OnPickUpTrigger;
  26661. },
  26662. enumerable: true,
  26663. configurable: true
  26664. });
  26665. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26666. /// This trigger will only be raised if you also declared a OnPickDown
  26667. get: function () {
  26668. return ActionManager._OnPickOutTrigger;
  26669. },
  26670. enumerable: true,
  26671. configurable: true
  26672. });
  26673. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26674. get: function () {
  26675. return ActionManager._OnLongPressTrigger;
  26676. },
  26677. enumerable: true,
  26678. configurable: true
  26679. });
  26680. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26681. get: function () {
  26682. return ActionManager._OnPointerOverTrigger;
  26683. },
  26684. enumerable: true,
  26685. configurable: true
  26686. });
  26687. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26688. get: function () {
  26689. return ActionManager._OnPointerOutTrigger;
  26690. },
  26691. enumerable: true,
  26692. configurable: true
  26693. });
  26694. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26695. get: function () {
  26696. return ActionManager._OnEveryFrameTrigger;
  26697. },
  26698. enumerable: true,
  26699. configurable: true
  26700. });
  26701. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26702. get: function () {
  26703. return ActionManager._OnIntersectionEnterTrigger;
  26704. },
  26705. enumerable: true,
  26706. configurable: true
  26707. });
  26708. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26709. get: function () {
  26710. return ActionManager._OnIntersectionExitTrigger;
  26711. },
  26712. enumerable: true,
  26713. configurable: true
  26714. });
  26715. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26716. get: function () {
  26717. return ActionManager._OnKeyDownTrigger;
  26718. },
  26719. enumerable: true,
  26720. configurable: true
  26721. });
  26722. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26723. get: function () {
  26724. return ActionManager._OnKeyUpTrigger;
  26725. },
  26726. enumerable: true,
  26727. configurable: true
  26728. });
  26729. // Methods
  26730. ActionManager.prototype.dispose = function () {
  26731. var index = this._scene._actionManagers.indexOf(this);
  26732. if (index > -1) {
  26733. this._scene._actionManagers.splice(index, 1);
  26734. }
  26735. };
  26736. ActionManager.prototype.getScene = function () {
  26737. return this._scene;
  26738. };
  26739. /**
  26740. * Does this action manager handles actions of any of the given triggers
  26741. * @param {number[]} triggers - the triggers to be tested
  26742. * @return {boolean} whether one (or more) of the triggers is handeled
  26743. */
  26744. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26745. for (var index = 0; index < this.actions.length; index++) {
  26746. var action = this.actions[index];
  26747. if (triggers.indexOf(action.trigger) > -1) {
  26748. return true;
  26749. }
  26750. }
  26751. return false;
  26752. };
  26753. /**
  26754. * Does this action manager handles actions of a given trigger
  26755. * @param {number} trigger - the trigger to be tested
  26756. * @return {boolean} whether the trigger is handeled
  26757. */
  26758. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26759. for (var index = 0; index < this.actions.length; index++) {
  26760. var action = this.actions[index];
  26761. if (action.trigger === trigger) {
  26762. return true;
  26763. }
  26764. }
  26765. return false;
  26766. };
  26767. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26768. /**
  26769. * Does this action manager has pointer triggers
  26770. * @return {boolean} whether or not it has pointer triggers
  26771. */
  26772. get: function () {
  26773. for (var index = 0; index < this.actions.length; index++) {
  26774. var action = this.actions[index];
  26775. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26776. return true;
  26777. }
  26778. }
  26779. return false;
  26780. },
  26781. enumerable: true,
  26782. configurable: true
  26783. });
  26784. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26785. /**
  26786. * Does this action manager has pick triggers
  26787. * @return {boolean} whether or not it has pick triggers
  26788. */
  26789. get: function () {
  26790. for (var index = 0; index < this.actions.length; index++) {
  26791. var action = this.actions[index];
  26792. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26793. return true;
  26794. }
  26795. }
  26796. return false;
  26797. },
  26798. enumerable: true,
  26799. configurable: true
  26800. });
  26801. /**
  26802. * Registers an action to this action manager
  26803. * @param {BABYLON.Action} action - the action to be registered
  26804. * @return {BABYLON.Action} the action amended (prepared) after registration
  26805. */
  26806. ActionManager.prototype.registerAction = function (action) {
  26807. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26808. if (this.getScene().actionManager !== this) {
  26809. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26810. return null;
  26811. }
  26812. }
  26813. this.actions.push(action);
  26814. action._actionManager = this;
  26815. action._prepare();
  26816. return action;
  26817. };
  26818. /**
  26819. * Process a specific trigger
  26820. * @param {number} trigger - the trigger to process
  26821. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26822. */
  26823. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26824. for (var index = 0; index < this.actions.length; index++) {
  26825. var action = this.actions[index];
  26826. if (action.trigger === trigger) {
  26827. if (trigger === ActionManager.OnKeyUpTrigger
  26828. || trigger === ActionManager.OnKeyDownTrigger) {
  26829. var parameter = action.getTriggerParameter();
  26830. if (parameter) {
  26831. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26832. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26833. if (actualkey !== parameter.toLowerCase()) {
  26834. continue;
  26835. }
  26836. }
  26837. }
  26838. action._executeCurrent(evt);
  26839. }
  26840. }
  26841. };
  26842. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26843. var properties = propertyPath.split(".");
  26844. for (var index = 0; index < properties.length - 1; index++) {
  26845. target = target[properties[index]];
  26846. }
  26847. return target;
  26848. };
  26849. ActionManager.prototype._getProperty = function (propertyPath) {
  26850. var properties = propertyPath.split(".");
  26851. return properties[properties.length - 1];
  26852. };
  26853. ActionManager.Parse = function (parsedActions, object, scene) {
  26854. var actionManager = new BABYLON.ActionManager(scene);
  26855. if (object === null)
  26856. scene.actionManager = actionManager;
  26857. else
  26858. object.actionManager = actionManager;
  26859. // instanciate a new object
  26860. var instanciate = function (name, params) {
  26861. var newInstance = Object.create(BABYLON[name].prototype);
  26862. newInstance.constructor.apply(newInstance, params);
  26863. return newInstance;
  26864. };
  26865. var parseParameter = function (name, value, target, propertyPath) {
  26866. if (propertyPath === null) {
  26867. // String, boolean or float
  26868. var floatValue = parseFloat(value);
  26869. if (value === "true" || value === "false")
  26870. return value === "true";
  26871. else
  26872. return isNaN(floatValue) ? value : floatValue;
  26873. }
  26874. var effectiveTarget = propertyPath.split(".");
  26875. var values = value.split(",");
  26876. // Get effective Target
  26877. for (var i = 0; i < effectiveTarget.length; i++) {
  26878. target = target[effectiveTarget[i]];
  26879. }
  26880. // Return appropriate value with its type
  26881. if (typeof (target) === "boolean")
  26882. return values[0] === "true";
  26883. if (typeof (target) === "string")
  26884. return values[0];
  26885. // Parameters with multiple values such as Vector3 etc.
  26886. var split = new Array();
  26887. for (var i = 0; i < values.length; i++)
  26888. split.push(parseFloat(values[i]));
  26889. if (target instanceof BABYLON.Vector3)
  26890. return BABYLON.Vector3.FromArray(split);
  26891. if (target instanceof BABYLON.Vector4)
  26892. return BABYLON.Vector4.FromArray(split);
  26893. if (target instanceof BABYLON.Color3)
  26894. return BABYLON.Color3.FromArray(split);
  26895. if (target instanceof BABYLON.Color4)
  26896. return BABYLON.Color4.FromArray(split);
  26897. return parseFloat(values[0]);
  26898. };
  26899. // traverse graph per trigger
  26900. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26901. if (combineArray === void 0) { combineArray = null; }
  26902. if (parsedAction.detached)
  26903. return;
  26904. var parameters = new Array();
  26905. var target = null;
  26906. var propertyPath = null;
  26907. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26908. // Parameters
  26909. if (parsedAction.type === 2)
  26910. parameters.push(actionManager);
  26911. else
  26912. parameters.push(trigger);
  26913. if (combine) {
  26914. var actions = new Array();
  26915. for (var j = 0; j < parsedAction.combine.length; j++) {
  26916. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26917. }
  26918. parameters.push(actions);
  26919. }
  26920. else {
  26921. for (var i = 0; i < parsedAction.properties.length; i++) {
  26922. var value = parsedAction.properties[i].value;
  26923. var name = parsedAction.properties[i].name;
  26924. var targetType = parsedAction.properties[i].targetType;
  26925. if (name === "target")
  26926. if (targetType !== null && targetType === "SceneProperties")
  26927. value = target = scene;
  26928. else
  26929. value = target = scene.getNodeByName(value);
  26930. else if (name === "parent")
  26931. value = scene.getNodeByName(value);
  26932. else if (name === "sound")
  26933. value = scene.getSoundByName(value);
  26934. else if (name !== "propertyPath") {
  26935. if (parsedAction.type === 2 && name === "operator")
  26936. value = BABYLON.ValueCondition[value];
  26937. else
  26938. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26939. }
  26940. else {
  26941. propertyPath = value;
  26942. }
  26943. parameters.push(value);
  26944. }
  26945. }
  26946. if (combineArray === null) {
  26947. parameters.push(condition);
  26948. }
  26949. else {
  26950. parameters.push(null);
  26951. }
  26952. // If interpolate value action
  26953. if (parsedAction.name === "InterpolateValueAction") {
  26954. var param = parameters[parameters.length - 2];
  26955. parameters[parameters.length - 1] = param;
  26956. parameters[parameters.length - 2] = condition;
  26957. }
  26958. // Action or condition(s) and not CombineAction
  26959. var newAction = instanciate(parsedAction.name, parameters);
  26960. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26961. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26962. if (action)
  26963. action.then(nothing);
  26964. else
  26965. actionManager.registerAction(nothing);
  26966. action = nothing;
  26967. }
  26968. if (combineArray === null) {
  26969. if (newAction instanceof BABYLON.Condition) {
  26970. condition = newAction;
  26971. newAction = action;
  26972. }
  26973. else {
  26974. condition = null;
  26975. if (action)
  26976. action.then(newAction);
  26977. else
  26978. actionManager.registerAction(newAction);
  26979. }
  26980. }
  26981. else {
  26982. combineArray.push(newAction);
  26983. }
  26984. for (var i = 0; i < parsedAction.children.length; i++)
  26985. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26986. };
  26987. // triggers
  26988. for (var i = 0; i < parsedActions.children.length; i++) {
  26989. var triggerParams;
  26990. var trigger = parsedActions.children[i];
  26991. if (trigger.properties.length > 0) {
  26992. var param = trigger.properties[0].value;
  26993. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26994. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26995. }
  26996. else
  26997. triggerParams = BABYLON.ActionManager[trigger.name];
  26998. for (var j = 0; j < trigger.children.length; j++) {
  26999. if (!trigger.detached)
  27000. traverse(trigger.children[j], triggerParams, null, null);
  27001. }
  27002. }
  27003. };
  27004. // Statics
  27005. ActionManager._NothingTrigger = 0;
  27006. ActionManager._OnPickTrigger = 1;
  27007. ActionManager._OnLeftPickTrigger = 2;
  27008. ActionManager._OnRightPickTrigger = 3;
  27009. ActionManager._OnCenterPickTrigger = 4;
  27010. ActionManager._OnPickDownTrigger = 5;
  27011. ActionManager._OnPickUpTrigger = 6;
  27012. ActionManager._OnLongPressTrigger = 7;
  27013. ActionManager._OnPointerOverTrigger = 8;
  27014. ActionManager._OnPointerOutTrigger = 9;
  27015. ActionManager._OnEveryFrameTrigger = 10;
  27016. ActionManager._OnIntersectionEnterTrigger = 11;
  27017. ActionManager._OnIntersectionExitTrigger = 12;
  27018. ActionManager._OnKeyDownTrigger = 13;
  27019. ActionManager._OnKeyUpTrigger = 14;
  27020. ActionManager._OnPickOutTrigger = 15;
  27021. ActionManager.DragMovementThreshold = 10; // in pixels
  27022. ActionManager.LongPressDelay = 500; // in milliseconds
  27023. return ActionManager;
  27024. })();
  27025. BABYLON.ActionManager = ActionManager;
  27026. })(BABYLON || (BABYLON = {}));
  27027. var BABYLON;
  27028. (function (BABYLON) {
  27029. var InterpolateValueAction = (function (_super) {
  27030. __extends(InterpolateValueAction, _super);
  27031. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27032. if (duration === void 0) { duration = 1000; }
  27033. _super.call(this, triggerOptions, condition);
  27034. this.propertyPath = propertyPath;
  27035. this.value = value;
  27036. this.duration = duration;
  27037. this.stopOtherAnimations = stopOtherAnimations;
  27038. this.onInterpolationDone = onInterpolationDone;
  27039. this._target = target;
  27040. }
  27041. InterpolateValueAction.prototype._prepare = function () {
  27042. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27043. this._property = this._getProperty(this.propertyPath);
  27044. };
  27045. InterpolateValueAction.prototype.execute = function () {
  27046. var scene = this._actionManager.getScene();
  27047. var keys = [
  27048. {
  27049. frame: 0,
  27050. value: this._target[this._property]
  27051. }, {
  27052. frame: 100,
  27053. value: this.value
  27054. }
  27055. ];
  27056. var dataType;
  27057. if (typeof this.value === "number") {
  27058. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27059. }
  27060. else if (this.value instanceof BABYLON.Color3) {
  27061. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27062. }
  27063. else if (this.value instanceof BABYLON.Vector3) {
  27064. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27065. }
  27066. else if (this.value instanceof BABYLON.Matrix) {
  27067. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27068. }
  27069. else if (this.value instanceof BABYLON.Quaternion) {
  27070. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27071. }
  27072. else {
  27073. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27074. return;
  27075. }
  27076. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27077. animation.setKeys(keys);
  27078. if (this.stopOtherAnimations) {
  27079. scene.stopAnimation(this._target);
  27080. }
  27081. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27082. };
  27083. return InterpolateValueAction;
  27084. })(BABYLON.Action);
  27085. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27086. })(BABYLON || (BABYLON = {}));
  27087. var BABYLON;
  27088. (function (BABYLON) {
  27089. var SwitchBooleanAction = (function (_super) {
  27090. __extends(SwitchBooleanAction, _super);
  27091. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27092. _super.call(this, triggerOptions, condition);
  27093. this.propertyPath = propertyPath;
  27094. this._target = target;
  27095. }
  27096. SwitchBooleanAction.prototype._prepare = function () {
  27097. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27098. this._property = this._getProperty(this.propertyPath);
  27099. };
  27100. SwitchBooleanAction.prototype.execute = function () {
  27101. this._target[this._property] = !this._target[this._property];
  27102. };
  27103. return SwitchBooleanAction;
  27104. })(BABYLON.Action);
  27105. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27106. var SetStateAction = (function (_super) {
  27107. __extends(SetStateAction, _super);
  27108. function SetStateAction(triggerOptions, target, value, condition) {
  27109. _super.call(this, triggerOptions, condition);
  27110. this.value = value;
  27111. this._target = target;
  27112. }
  27113. SetStateAction.prototype.execute = function () {
  27114. this._target.state = this.value;
  27115. };
  27116. return SetStateAction;
  27117. })(BABYLON.Action);
  27118. BABYLON.SetStateAction = SetStateAction;
  27119. var SetValueAction = (function (_super) {
  27120. __extends(SetValueAction, _super);
  27121. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27122. _super.call(this, triggerOptions, condition);
  27123. this.propertyPath = propertyPath;
  27124. this.value = value;
  27125. this._target = target;
  27126. }
  27127. SetValueAction.prototype._prepare = function () {
  27128. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27129. this._property = this._getProperty(this.propertyPath);
  27130. };
  27131. SetValueAction.prototype.execute = function () {
  27132. this._target[this._property] = this.value;
  27133. };
  27134. return SetValueAction;
  27135. })(BABYLON.Action);
  27136. BABYLON.SetValueAction = SetValueAction;
  27137. var IncrementValueAction = (function (_super) {
  27138. __extends(IncrementValueAction, _super);
  27139. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27140. _super.call(this, triggerOptions, condition);
  27141. this.propertyPath = propertyPath;
  27142. this.value = value;
  27143. this._target = target;
  27144. }
  27145. IncrementValueAction.prototype._prepare = function () {
  27146. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27147. this._property = this._getProperty(this.propertyPath);
  27148. if (typeof this._target[this._property] !== "number") {
  27149. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27150. }
  27151. };
  27152. IncrementValueAction.prototype.execute = function () {
  27153. this._target[this._property] += this.value;
  27154. };
  27155. return IncrementValueAction;
  27156. })(BABYLON.Action);
  27157. BABYLON.IncrementValueAction = IncrementValueAction;
  27158. var PlayAnimationAction = (function (_super) {
  27159. __extends(PlayAnimationAction, _super);
  27160. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27161. _super.call(this, triggerOptions, condition);
  27162. this.from = from;
  27163. this.to = to;
  27164. this.loop = loop;
  27165. this._target = target;
  27166. }
  27167. PlayAnimationAction.prototype._prepare = function () {
  27168. };
  27169. PlayAnimationAction.prototype.execute = function () {
  27170. var scene = this._actionManager.getScene();
  27171. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27172. };
  27173. return PlayAnimationAction;
  27174. })(BABYLON.Action);
  27175. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27176. var StopAnimationAction = (function (_super) {
  27177. __extends(StopAnimationAction, _super);
  27178. function StopAnimationAction(triggerOptions, target, condition) {
  27179. _super.call(this, triggerOptions, condition);
  27180. this._target = target;
  27181. }
  27182. StopAnimationAction.prototype._prepare = function () {
  27183. };
  27184. StopAnimationAction.prototype.execute = function () {
  27185. var scene = this._actionManager.getScene();
  27186. scene.stopAnimation(this._target);
  27187. };
  27188. return StopAnimationAction;
  27189. })(BABYLON.Action);
  27190. BABYLON.StopAnimationAction = StopAnimationAction;
  27191. var DoNothingAction = (function (_super) {
  27192. __extends(DoNothingAction, _super);
  27193. function DoNothingAction(triggerOptions, condition) {
  27194. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27195. _super.call(this, triggerOptions, condition);
  27196. }
  27197. DoNothingAction.prototype.execute = function () {
  27198. };
  27199. return DoNothingAction;
  27200. })(BABYLON.Action);
  27201. BABYLON.DoNothingAction = DoNothingAction;
  27202. var CombineAction = (function (_super) {
  27203. __extends(CombineAction, _super);
  27204. function CombineAction(triggerOptions, children, condition) {
  27205. _super.call(this, triggerOptions, condition);
  27206. this.children = children;
  27207. }
  27208. CombineAction.prototype._prepare = function () {
  27209. for (var index = 0; index < this.children.length; index++) {
  27210. this.children[index]._actionManager = this._actionManager;
  27211. this.children[index]._prepare();
  27212. }
  27213. };
  27214. CombineAction.prototype.execute = function (evt) {
  27215. for (var index = 0; index < this.children.length; index++) {
  27216. this.children[index].execute(evt);
  27217. }
  27218. };
  27219. return CombineAction;
  27220. })(BABYLON.Action);
  27221. BABYLON.CombineAction = CombineAction;
  27222. var ExecuteCodeAction = (function (_super) {
  27223. __extends(ExecuteCodeAction, _super);
  27224. function ExecuteCodeAction(triggerOptions, func, condition) {
  27225. _super.call(this, triggerOptions, condition);
  27226. this.func = func;
  27227. }
  27228. ExecuteCodeAction.prototype.execute = function (evt) {
  27229. this.func(evt);
  27230. };
  27231. return ExecuteCodeAction;
  27232. })(BABYLON.Action);
  27233. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27234. var SetParentAction = (function (_super) {
  27235. __extends(SetParentAction, _super);
  27236. function SetParentAction(triggerOptions, target, parent, condition) {
  27237. _super.call(this, triggerOptions, condition);
  27238. this._target = target;
  27239. this._parent = parent;
  27240. }
  27241. SetParentAction.prototype._prepare = function () {
  27242. };
  27243. SetParentAction.prototype.execute = function () {
  27244. if (this._target.parent === this._parent) {
  27245. return;
  27246. }
  27247. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27248. invertParentWorldMatrix.invert();
  27249. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27250. this._target.parent = this._parent;
  27251. };
  27252. return SetParentAction;
  27253. })(BABYLON.Action);
  27254. BABYLON.SetParentAction = SetParentAction;
  27255. var PlaySoundAction = (function (_super) {
  27256. __extends(PlaySoundAction, _super);
  27257. function PlaySoundAction(triggerOptions, sound, condition) {
  27258. _super.call(this, triggerOptions, condition);
  27259. this._sound = sound;
  27260. }
  27261. PlaySoundAction.prototype._prepare = function () {
  27262. };
  27263. PlaySoundAction.prototype.execute = function () {
  27264. if (this._sound !== undefined)
  27265. this._sound.play();
  27266. };
  27267. return PlaySoundAction;
  27268. })(BABYLON.Action);
  27269. BABYLON.PlaySoundAction = PlaySoundAction;
  27270. var StopSoundAction = (function (_super) {
  27271. __extends(StopSoundAction, _super);
  27272. function StopSoundAction(triggerOptions, sound, condition) {
  27273. _super.call(this, triggerOptions, condition);
  27274. this._sound = sound;
  27275. }
  27276. StopSoundAction.prototype._prepare = function () {
  27277. };
  27278. StopSoundAction.prototype.execute = function () {
  27279. if (this._sound !== undefined)
  27280. this._sound.stop();
  27281. };
  27282. return StopSoundAction;
  27283. })(BABYLON.Action);
  27284. BABYLON.StopSoundAction = StopSoundAction;
  27285. })(BABYLON || (BABYLON = {}));
  27286. var BABYLON;
  27287. (function (BABYLON) {
  27288. var Geometry = (function () {
  27289. function Geometry(id, scene, vertexData, updatable, mesh) {
  27290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27291. this._totalVertices = 0;
  27292. this._isDisposed = false;
  27293. this.id = id;
  27294. this._engine = scene.getEngine();
  27295. this._meshes = [];
  27296. this._scene = scene;
  27297. //Init vertex buffer cache
  27298. this._vertexBuffers = {};
  27299. this._indices = [];
  27300. // vertexData
  27301. if (vertexData) {
  27302. this.setAllVerticesData(vertexData, updatable);
  27303. }
  27304. else {
  27305. this._totalVertices = 0;
  27306. this._indices = [];
  27307. }
  27308. // applyToMesh
  27309. if (mesh) {
  27310. this.applyToMesh(mesh);
  27311. mesh.computeWorldMatrix(true);
  27312. }
  27313. }
  27314. Object.defineProperty(Geometry.prototype, "extend", {
  27315. get: function () {
  27316. return this._extend;
  27317. },
  27318. enumerable: true,
  27319. configurable: true
  27320. });
  27321. Geometry.prototype.getScene = function () {
  27322. return this._scene;
  27323. };
  27324. Geometry.prototype.getEngine = function () {
  27325. return this._engine;
  27326. };
  27327. Geometry.prototype.isReady = function () {
  27328. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27329. };
  27330. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27331. vertexData.applyToGeometry(this, updatable);
  27332. this.notifyUpdate();
  27333. };
  27334. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27335. if (this._vertexBuffers[kind]) {
  27336. this._vertexBuffers[kind].dispose();
  27337. }
  27338. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27339. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27340. stride = this._vertexBuffers[kind].getStrideSize();
  27341. this._totalVertices = data.length / stride;
  27342. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27343. var meshes = this._meshes;
  27344. var numOfMeshes = meshes.length;
  27345. for (var index = 0; index < numOfMeshes; index++) {
  27346. var mesh = meshes[index];
  27347. mesh._resetPointsArrayCache();
  27348. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27349. mesh._createGlobalSubMesh();
  27350. mesh.computeWorldMatrix(true);
  27351. }
  27352. }
  27353. this.notifyUpdate(kind);
  27354. };
  27355. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27356. var vertexBuffer = this.getVertexBuffer(kind);
  27357. if (!vertexBuffer) {
  27358. return;
  27359. }
  27360. vertexBuffer.updateDirectly(data, offset);
  27361. this.notifyUpdate(kind);
  27362. };
  27363. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27364. var vertexBuffer = this.getVertexBuffer(kind);
  27365. if (!vertexBuffer) {
  27366. return;
  27367. }
  27368. vertexBuffer.update(data);
  27369. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27370. var stride = vertexBuffer.getStrideSize();
  27371. this._totalVertices = data.length / stride;
  27372. if (updateExtends) {
  27373. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27374. }
  27375. var meshes = this._meshes;
  27376. var numOfMeshes = meshes.length;
  27377. for (var index = 0; index < numOfMeshes; index++) {
  27378. var mesh = meshes[index];
  27379. mesh._resetPointsArrayCache();
  27380. if (updateExtends) {
  27381. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27382. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27383. var subMesh = mesh.subMeshes[subIndex];
  27384. subMesh.refreshBoundingInfo();
  27385. }
  27386. }
  27387. }
  27388. }
  27389. this.notifyUpdate(kind);
  27390. };
  27391. Geometry.prototype.getTotalVertices = function () {
  27392. if (!this.isReady()) {
  27393. return 0;
  27394. }
  27395. return this._totalVertices;
  27396. };
  27397. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27398. var vertexBuffer = this.getVertexBuffer(kind);
  27399. if (!vertexBuffer) {
  27400. return null;
  27401. }
  27402. var orig = vertexBuffer.getData();
  27403. if (!copyWhenShared || this._meshes.length === 1) {
  27404. return orig;
  27405. }
  27406. else {
  27407. var len = orig.length;
  27408. var copy = [];
  27409. for (var i = 0; i < len; i++) {
  27410. copy.push(orig[i]);
  27411. }
  27412. return copy;
  27413. }
  27414. };
  27415. Geometry.prototype.getVertexBuffer = function (kind) {
  27416. if (!this.isReady()) {
  27417. return null;
  27418. }
  27419. return this._vertexBuffers[kind];
  27420. };
  27421. Geometry.prototype.getVertexBuffers = function () {
  27422. if (!this.isReady()) {
  27423. return null;
  27424. }
  27425. return this._vertexBuffers;
  27426. };
  27427. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27428. if (!this._vertexBuffers) {
  27429. if (this._delayInfo) {
  27430. return this._delayInfo.indexOf(kind) !== -1;
  27431. }
  27432. return false;
  27433. }
  27434. return this._vertexBuffers[kind] !== undefined;
  27435. };
  27436. Geometry.prototype.getVerticesDataKinds = function () {
  27437. var result = [];
  27438. var kind;
  27439. if (!this._vertexBuffers && this._delayInfo) {
  27440. for (kind in this._delayInfo) {
  27441. result.push(kind);
  27442. }
  27443. }
  27444. else {
  27445. for (kind in this._vertexBuffers) {
  27446. result.push(kind);
  27447. }
  27448. }
  27449. return result;
  27450. };
  27451. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27452. if (this._indexBuffer) {
  27453. this._engine._releaseBuffer(this._indexBuffer);
  27454. }
  27455. this._indices = indices;
  27456. if (this._meshes.length !== 0 && this._indices) {
  27457. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27458. }
  27459. if (totalVertices !== undefined) {
  27460. this._totalVertices = totalVertices;
  27461. }
  27462. var meshes = this._meshes;
  27463. var numOfMeshes = meshes.length;
  27464. for (var index = 0; index < numOfMeshes; index++) {
  27465. meshes[index]._createGlobalSubMesh();
  27466. }
  27467. this.notifyUpdate();
  27468. };
  27469. Geometry.prototype.getTotalIndices = function () {
  27470. if (!this.isReady()) {
  27471. return 0;
  27472. }
  27473. return this._indices.length;
  27474. };
  27475. Geometry.prototype.getIndices = function (copyWhenShared) {
  27476. if (!this.isReady()) {
  27477. return null;
  27478. }
  27479. var orig = this._indices;
  27480. if (!copyWhenShared || this._meshes.length === 1) {
  27481. return orig;
  27482. }
  27483. else {
  27484. var len = orig.length;
  27485. var copy = [];
  27486. for (var i = 0; i < len; i++) {
  27487. copy.push(orig[i]);
  27488. }
  27489. return copy;
  27490. }
  27491. };
  27492. Geometry.prototype.getIndexBuffer = function () {
  27493. if (!this.isReady()) {
  27494. return null;
  27495. }
  27496. return this._indexBuffer;
  27497. };
  27498. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27499. var meshes = this._meshes;
  27500. var index = meshes.indexOf(mesh);
  27501. if (index === -1) {
  27502. return;
  27503. }
  27504. for (var kind in this._vertexBuffers) {
  27505. this._vertexBuffers[kind].dispose();
  27506. }
  27507. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27508. this._indexBuffer = null;
  27509. }
  27510. meshes.splice(index, 1);
  27511. mesh._geometry = null;
  27512. if (meshes.length === 0 && shouldDispose) {
  27513. this.dispose();
  27514. }
  27515. };
  27516. Geometry.prototype.applyToMesh = function (mesh) {
  27517. if (mesh._geometry === this) {
  27518. return;
  27519. }
  27520. var previousGeometry = mesh._geometry;
  27521. if (previousGeometry) {
  27522. previousGeometry.releaseForMesh(mesh);
  27523. }
  27524. var meshes = this._meshes;
  27525. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27526. mesh._geometry = this;
  27527. this._scene.pushGeometry(this);
  27528. meshes.push(mesh);
  27529. if (this.isReady()) {
  27530. this._applyToMesh(mesh);
  27531. }
  27532. else {
  27533. mesh._boundingInfo = this._boundingInfo;
  27534. }
  27535. };
  27536. Geometry.prototype._applyToMesh = function (mesh) {
  27537. var numOfMeshes = this._meshes.length;
  27538. // vertexBuffers
  27539. for (var kind in this._vertexBuffers) {
  27540. if (numOfMeshes === 1) {
  27541. this._vertexBuffers[kind].create();
  27542. }
  27543. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27544. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27545. mesh._resetPointsArrayCache();
  27546. if (!this._extend) {
  27547. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27548. }
  27549. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27550. mesh._createGlobalSubMesh();
  27551. //bounding info was just created again, world matrix should be applied again.
  27552. mesh._updateBoundingInfo();
  27553. }
  27554. }
  27555. // indexBuffer
  27556. if (numOfMeshes === 1 && this._indices) {
  27557. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27558. }
  27559. if (this._indexBuffer) {
  27560. this._indexBuffer.references = numOfMeshes;
  27561. }
  27562. };
  27563. Geometry.prototype.notifyUpdate = function (kind) {
  27564. if (this.onGeometryUpdated) {
  27565. this.onGeometryUpdated(this, kind);
  27566. }
  27567. };
  27568. Geometry.prototype.load = function (scene, onLoaded) {
  27569. var _this = this;
  27570. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27571. return;
  27572. }
  27573. if (this.isReady()) {
  27574. if (onLoaded) {
  27575. onLoaded();
  27576. }
  27577. return;
  27578. }
  27579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27580. scene._addPendingData(this);
  27581. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27582. _this._delayLoadingFunction(JSON.parse(data), _this);
  27583. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27584. _this._delayInfo = [];
  27585. scene._removePendingData(_this);
  27586. var meshes = _this._meshes;
  27587. var numOfMeshes = meshes.length;
  27588. for (var index = 0; index < numOfMeshes; index++) {
  27589. _this._applyToMesh(meshes[index]);
  27590. }
  27591. if (onLoaded) {
  27592. onLoaded();
  27593. }
  27594. }, function () { }, scene.database);
  27595. };
  27596. Geometry.prototype.isDisposed = function () {
  27597. return this._isDisposed;
  27598. };
  27599. Geometry.prototype.dispose = function () {
  27600. var meshes = this._meshes;
  27601. var numOfMeshes = meshes.length;
  27602. var index;
  27603. for (index = 0; index < numOfMeshes; index++) {
  27604. this.releaseForMesh(meshes[index]);
  27605. }
  27606. this._meshes = [];
  27607. for (var kind in this._vertexBuffers) {
  27608. this._vertexBuffers[kind].dispose();
  27609. }
  27610. this._vertexBuffers = [];
  27611. this._totalVertices = 0;
  27612. if (this._indexBuffer) {
  27613. this._engine._releaseBuffer(this._indexBuffer);
  27614. }
  27615. this._indexBuffer = null;
  27616. this._indices = [];
  27617. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27618. this.delayLoadingFile = null;
  27619. this._delayLoadingFunction = null;
  27620. this._delayInfo = [];
  27621. this._boundingInfo = null;
  27622. this._scene.removeGeometry(this);
  27623. this._isDisposed = true;
  27624. };
  27625. Geometry.prototype.copy = function (id) {
  27626. var vertexData = new BABYLON.VertexData();
  27627. vertexData.indices = [];
  27628. var indices = this.getIndices();
  27629. for (var index = 0; index < indices.length; index++) {
  27630. vertexData.indices.push(indices[index]);
  27631. }
  27632. var updatable = false;
  27633. var stopChecking = false;
  27634. var kind;
  27635. for (kind in this._vertexBuffers) {
  27636. // using slice() to make a copy of the array and not just reference it
  27637. var data = this.getVerticesData(kind);
  27638. if (data instanceof Float32Array) {
  27639. vertexData.set(new Float32Array(data), kind);
  27640. }
  27641. else {
  27642. vertexData.set(data.slice(0), kind);
  27643. }
  27644. if (!stopChecking) {
  27645. updatable = this.getVertexBuffer(kind).isUpdatable();
  27646. stopChecking = !updatable;
  27647. }
  27648. }
  27649. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27650. geometry.delayLoadState = this.delayLoadState;
  27651. geometry.delayLoadingFile = this.delayLoadingFile;
  27652. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27653. for (kind in this._delayInfo) {
  27654. geometry._delayInfo = geometry._delayInfo || [];
  27655. geometry._delayInfo.push(kind);
  27656. }
  27657. // Bounding info
  27658. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27659. return geometry;
  27660. };
  27661. Geometry.prototype.serialize = function () {
  27662. var serializationObject = {};
  27663. serializationObject.id = this.id;
  27664. if (BABYLON.Tags.HasTags(this)) {
  27665. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27666. }
  27667. return serializationObject;
  27668. };
  27669. Geometry.prototype.serializeVerticeData = function () {
  27670. var serializationObject = this.serialize();
  27671. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27672. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27673. }
  27674. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27675. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27676. }
  27677. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27678. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27679. }
  27680. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27681. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27682. }
  27683. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27684. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27685. }
  27686. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27687. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27688. }
  27689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27690. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27691. }
  27692. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27693. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27694. }
  27695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27696. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27697. }
  27698. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27699. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27700. serializationObject.matricesIndices._isExpanded = true;
  27701. }
  27702. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27703. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27704. }
  27705. serializationObject.indices = this.getIndices();
  27706. return serializationObject;
  27707. };
  27708. // Statics
  27709. Geometry.ExtractFromMesh = function (mesh, id) {
  27710. var geometry = mesh._geometry;
  27711. if (!geometry) {
  27712. return null;
  27713. }
  27714. return geometry.copy(id);
  27715. };
  27716. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27717. // be aware Math.random() could cause collisions
  27718. Geometry.RandomId = function () {
  27719. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27720. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27721. return v.toString(16);
  27722. });
  27723. };
  27724. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27725. var scene = mesh.getScene();
  27726. // Geometry
  27727. var geometryId = parsedGeometry.geometryId;
  27728. if (geometryId) {
  27729. var geometry = scene.getGeometryByID(geometryId);
  27730. if (geometry) {
  27731. geometry.applyToMesh(mesh);
  27732. }
  27733. }
  27734. else if (parsedGeometry instanceof ArrayBuffer) {
  27735. var binaryInfo = mesh._binaryInfo;
  27736. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27737. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27738. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27739. }
  27740. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27741. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27742. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27743. }
  27744. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27745. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27746. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27747. }
  27748. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27749. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27750. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27751. }
  27752. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27753. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27754. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27755. }
  27756. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27757. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27758. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27759. }
  27760. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27761. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27762. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27763. }
  27764. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27765. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27766. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27767. }
  27768. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27769. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27770. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27771. }
  27772. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27773. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27774. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27775. }
  27776. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27777. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27779. }
  27780. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27781. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27782. mesh.setIndices(indicesData);
  27783. }
  27784. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27785. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27786. mesh.subMeshes = [];
  27787. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27788. var materialIndex = subMeshesData[(i * 5) + 0];
  27789. var verticesStart = subMeshesData[(i * 5) + 1];
  27790. var verticesCount = subMeshesData[(i * 5) + 2];
  27791. var indexStart = subMeshesData[(i * 5) + 3];
  27792. var indexCount = subMeshesData[(i * 5) + 4];
  27793. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27794. }
  27795. }
  27796. }
  27797. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27798. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27799. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27800. if (parsedGeometry.uvs) {
  27801. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27802. }
  27803. if (parsedGeometry.uvs2) {
  27804. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27805. }
  27806. if (parsedGeometry.uvs3) {
  27807. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27808. }
  27809. if (parsedGeometry.uvs4) {
  27810. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27811. }
  27812. if (parsedGeometry.uvs5) {
  27813. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27814. }
  27815. if (parsedGeometry.uvs6) {
  27816. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27817. }
  27818. if (parsedGeometry.colors) {
  27819. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27820. }
  27821. if (parsedGeometry.matricesIndices) {
  27822. if (!parsedGeometry.matricesIndices._isExpanded) {
  27823. var floatIndices = [];
  27824. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27825. var matricesIndex = parsedGeometry.matricesIndices[i];
  27826. floatIndices.push(matricesIndex & 0x000000FF);
  27827. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27828. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27829. floatIndices.push(matricesIndex >> 24);
  27830. }
  27831. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27832. }
  27833. else {
  27834. delete parsedGeometry.matricesIndices._isExpanded;
  27835. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27836. }
  27837. }
  27838. if (parsedGeometry.matricesIndicesExtra) {
  27839. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27840. var floatIndices = [];
  27841. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27842. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27843. floatIndices.push(matricesIndex & 0x000000FF);
  27844. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27845. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27846. floatIndices.push(matricesIndex >> 24);
  27847. }
  27848. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27849. }
  27850. else {
  27851. delete parsedGeometry.matricesIndices._isExpanded;
  27852. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27853. }
  27854. }
  27855. if (parsedGeometry.matricesWeights) {
  27856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27857. }
  27858. if (parsedGeometry.matricesWeightsExtra) {
  27859. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27860. }
  27861. mesh.setIndices(parsedGeometry.indices);
  27862. }
  27863. // SubMeshes
  27864. if (parsedGeometry.subMeshes) {
  27865. mesh.subMeshes = [];
  27866. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27867. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27868. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27869. }
  27870. }
  27871. // Flat shading
  27872. if (mesh._shouldGenerateFlatShading) {
  27873. mesh.convertToFlatShadedMesh();
  27874. delete mesh._shouldGenerateFlatShading;
  27875. }
  27876. // Update
  27877. mesh.computeWorldMatrix(true);
  27878. // Octree
  27879. if (scene['_selectionOctree']) {
  27880. scene['_selectionOctree'].addMesh(mesh);
  27881. }
  27882. };
  27883. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27884. if (scene.getGeometryByID(parsedVertexData.id)) {
  27885. return null; // null since geometry could be something else than a box...
  27886. }
  27887. var geometry = new Geometry(parsedVertexData.id, scene);
  27888. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27889. if (parsedVertexData.delayLoadingFile) {
  27890. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27891. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27892. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27893. geometry._delayInfo = [];
  27894. if (parsedVertexData.hasUVs) {
  27895. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27896. }
  27897. if (parsedVertexData.hasUVs2) {
  27898. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27899. }
  27900. if (parsedVertexData.hasUVs3) {
  27901. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27902. }
  27903. if (parsedVertexData.hasUVs4) {
  27904. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27905. }
  27906. if (parsedVertexData.hasUVs5) {
  27907. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27908. }
  27909. if (parsedVertexData.hasUVs6) {
  27910. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27911. }
  27912. if (parsedVertexData.hasColors) {
  27913. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27914. }
  27915. if (parsedVertexData.hasMatricesIndices) {
  27916. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27917. }
  27918. if (parsedVertexData.hasMatricesWeights) {
  27919. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27920. }
  27921. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27922. }
  27923. else {
  27924. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27925. }
  27926. scene.pushGeometry(geometry, true);
  27927. return geometry;
  27928. };
  27929. return Geometry;
  27930. })();
  27931. BABYLON.Geometry = Geometry;
  27932. /////// Primitives //////////////////////////////////////////////
  27933. var Geometry;
  27934. (function (Geometry) {
  27935. var Primitives;
  27936. (function (Primitives) {
  27937. /// Abstract class
  27938. var _Primitive = (function (_super) {
  27939. __extends(_Primitive, _super);
  27940. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27941. this._beingRegenerated = true;
  27942. this._canBeRegenerated = canBeRegenerated;
  27943. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27944. this._beingRegenerated = false;
  27945. }
  27946. _Primitive.prototype.canBeRegenerated = function () {
  27947. return this._canBeRegenerated;
  27948. };
  27949. _Primitive.prototype.regenerate = function () {
  27950. if (!this._canBeRegenerated) {
  27951. return;
  27952. }
  27953. this._beingRegenerated = true;
  27954. this.setAllVerticesData(this._regenerateVertexData(), false);
  27955. this._beingRegenerated = false;
  27956. };
  27957. _Primitive.prototype.asNewGeometry = function (id) {
  27958. return _super.prototype.copy.call(this, id);
  27959. };
  27960. // overrides
  27961. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27962. if (!this._beingRegenerated) {
  27963. return;
  27964. }
  27965. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27966. };
  27967. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27968. if (!this._beingRegenerated) {
  27969. return;
  27970. }
  27971. _super.prototype.setVerticesData.call(this, kind, data, false);
  27972. };
  27973. // to override
  27974. // protected
  27975. _Primitive.prototype._regenerateVertexData = function () {
  27976. throw new Error("Abstract method");
  27977. };
  27978. _Primitive.prototype.copy = function (id) {
  27979. throw new Error("Must be overriden in sub-classes.");
  27980. };
  27981. _Primitive.prototype.serialize = function () {
  27982. var serializationObject = _super.prototype.serialize.call(this);
  27983. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27984. return serializationObject;
  27985. };
  27986. return _Primitive;
  27987. })(Geometry);
  27988. Primitives._Primitive = _Primitive;
  27989. var Ribbon = (function (_super) {
  27990. __extends(Ribbon, _super);
  27991. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27992. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27993. this.pathArray = pathArray;
  27994. this.closeArray = closeArray;
  27995. this.closePath = closePath;
  27996. this.offset = offset;
  27997. this.side = side;
  27998. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27999. }
  28000. Ribbon.prototype._regenerateVertexData = function () {
  28001. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28002. };
  28003. Ribbon.prototype.copy = function (id) {
  28004. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28005. };
  28006. return Ribbon;
  28007. })(_Primitive);
  28008. Primitives.Ribbon = Ribbon;
  28009. var Box = (function (_super) {
  28010. __extends(Box, _super);
  28011. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28012. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28013. this.size = size;
  28014. this.side = side;
  28015. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28016. }
  28017. Box.prototype._regenerateVertexData = function () {
  28018. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28019. };
  28020. Box.prototype.copy = function (id) {
  28021. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28022. };
  28023. Box.prototype.serialize = function () {
  28024. var serializationObject = _super.prototype.serialize.call(this);
  28025. serializationObject.size = this.size;
  28026. return serializationObject;
  28027. };
  28028. Box.Parse = function (parsedBox, scene) {
  28029. if (scene.getGeometryByID(parsedBox.id)) {
  28030. return null; // null since geometry could be something else than a box...
  28031. }
  28032. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28033. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28034. scene.pushGeometry(box, true);
  28035. return box;
  28036. };
  28037. return Box;
  28038. })(_Primitive);
  28039. Primitives.Box = Box;
  28040. var Sphere = (function (_super) {
  28041. __extends(Sphere, _super);
  28042. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28044. this.segments = segments;
  28045. this.diameter = diameter;
  28046. this.side = side;
  28047. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28048. }
  28049. Sphere.prototype._regenerateVertexData = function () {
  28050. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28051. };
  28052. Sphere.prototype.copy = function (id) {
  28053. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28054. };
  28055. Sphere.prototype.serialize = function () {
  28056. var serializationObject = _super.prototype.serialize.call(this);
  28057. serializationObject.segments = this.segments;
  28058. serializationObject.diameter = this.diameter;
  28059. return serializationObject;
  28060. };
  28061. Sphere.Parse = function (parsedSphere, scene) {
  28062. if (scene.getGeometryByID(parsedSphere.id)) {
  28063. return null; // null since geometry could be something else than a sphere...
  28064. }
  28065. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28066. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28067. scene.pushGeometry(sphere, true);
  28068. return sphere;
  28069. };
  28070. return Sphere;
  28071. })(_Primitive);
  28072. Primitives.Sphere = Sphere;
  28073. var Disc = (function (_super) {
  28074. __extends(Disc, _super);
  28075. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28076. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28077. this.radius = radius;
  28078. this.tessellation = tessellation;
  28079. this.side = side;
  28080. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28081. }
  28082. Disc.prototype._regenerateVertexData = function () {
  28083. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28084. };
  28085. Disc.prototype.copy = function (id) {
  28086. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28087. };
  28088. return Disc;
  28089. })(_Primitive);
  28090. Primitives.Disc = Disc;
  28091. var Cylinder = (function (_super) {
  28092. __extends(Cylinder, _super);
  28093. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28094. if (subdivisions === void 0) { subdivisions = 1; }
  28095. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28096. this.height = height;
  28097. this.diameterTop = diameterTop;
  28098. this.diameterBottom = diameterBottom;
  28099. this.tessellation = tessellation;
  28100. this.subdivisions = subdivisions;
  28101. this.side = side;
  28102. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28103. }
  28104. Cylinder.prototype._regenerateVertexData = function () {
  28105. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28106. };
  28107. Cylinder.prototype.copy = function (id) {
  28108. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28109. };
  28110. Cylinder.prototype.serialize = function () {
  28111. var serializationObject = _super.prototype.serialize.call(this);
  28112. serializationObject.height = this.height;
  28113. serializationObject.diameterTop = this.diameterTop;
  28114. serializationObject.diameterBottom = this.diameterBottom;
  28115. serializationObject.tessellation = this.tessellation;
  28116. return serializationObject;
  28117. };
  28118. Cylinder.Parse = function (parsedCylinder, scene) {
  28119. if (scene.getGeometryByID(parsedCylinder.id)) {
  28120. return null; // null since geometry could be something else than a cylinder...
  28121. }
  28122. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28123. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28124. scene.pushGeometry(cylinder, true);
  28125. return cylinder;
  28126. };
  28127. return Cylinder;
  28128. })(_Primitive);
  28129. Primitives.Cylinder = Cylinder;
  28130. var Torus = (function (_super) {
  28131. __extends(Torus, _super);
  28132. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28133. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28134. this.diameter = diameter;
  28135. this.thickness = thickness;
  28136. this.tessellation = tessellation;
  28137. this.side = side;
  28138. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28139. }
  28140. Torus.prototype._regenerateVertexData = function () {
  28141. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28142. };
  28143. Torus.prototype.copy = function (id) {
  28144. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28145. };
  28146. Torus.prototype.serialize = function () {
  28147. var serializationObject = _super.prototype.serialize.call(this);
  28148. serializationObject.diameter = this.diameter;
  28149. serializationObject.thickness = this.thickness;
  28150. serializationObject.tessellation = this.tessellation;
  28151. return serializationObject;
  28152. };
  28153. Torus.Parse = function (parsedTorus, scene) {
  28154. if (scene.getGeometryByID(parsedTorus.id)) {
  28155. return null; // null since geometry could be something else than a torus...
  28156. }
  28157. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28158. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28159. scene.pushGeometry(torus, true);
  28160. return torus;
  28161. };
  28162. return Torus;
  28163. })(_Primitive);
  28164. Primitives.Torus = Torus;
  28165. var Ground = (function (_super) {
  28166. __extends(Ground, _super);
  28167. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28168. this.width = width;
  28169. this.height = height;
  28170. this.subdivisions = subdivisions;
  28171. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28172. }
  28173. Ground.prototype._regenerateVertexData = function () {
  28174. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28175. };
  28176. Ground.prototype.copy = function (id) {
  28177. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28178. };
  28179. Ground.prototype.serialize = function () {
  28180. var serializationObject = _super.prototype.serialize.call(this);
  28181. serializationObject.width = this.width;
  28182. serializationObject.height = this.height;
  28183. serializationObject.subdivisions = this.subdivisions;
  28184. return serializationObject;
  28185. };
  28186. Ground.Parse = function (parsedGround, scene) {
  28187. if (scene.getGeometryByID(parsedGround.id)) {
  28188. return null; // null since geometry could be something else than a ground...
  28189. }
  28190. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28191. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28192. scene.pushGeometry(ground, true);
  28193. return ground;
  28194. };
  28195. return Ground;
  28196. })(_Primitive);
  28197. Primitives.Ground = Ground;
  28198. var TiledGround = (function (_super) {
  28199. __extends(TiledGround, _super);
  28200. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28201. this.xmin = xmin;
  28202. this.zmin = zmin;
  28203. this.xmax = xmax;
  28204. this.zmax = zmax;
  28205. this.subdivisions = subdivisions;
  28206. this.precision = precision;
  28207. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28208. }
  28209. TiledGround.prototype._regenerateVertexData = function () {
  28210. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28211. };
  28212. TiledGround.prototype.copy = function (id) {
  28213. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28214. };
  28215. return TiledGround;
  28216. })(_Primitive);
  28217. Primitives.TiledGround = TiledGround;
  28218. var Plane = (function (_super) {
  28219. __extends(Plane, _super);
  28220. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28222. this.size = size;
  28223. this.side = side;
  28224. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28225. }
  28226. Plane.prototype._regenerateVertexData = function () {
  28227. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28228. };
  28229. Plane.prototype.copy = function (id) {
  28230. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28231. };
  28232. Plane.prototype.serialize = function () {
  28233. var serializationObject = _super.prototype.serialize.call(this);
  28234. serializationObject.size = this.size;
  28235. return serializationObject;
  28236. };
  28237. Plane.Parse = function (parsedPlane, scene) {
  28238. if (scene.getGeometryByID(parsedPlane.id)) {
  28239. return null; // null since geometry could be something else than a ground...
  28240. }
  28241. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28242. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28243. scene.pushGeometry(plane, true);
  28244. return plane;
  28245. };
  28246. return Plane;
  28247. })(_Primitive);
  28248. Primitives.Plane = Plane;
  28249. var TorusKnot = (function (_super) {
  28250. __extends(TorusKnot, _super);
  28251. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28252. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28253. this.radius = radius;
  28254. this.tube = tube;
  28255. this.radialSegments = radialSegments;
  28256. this.tubularSegments = tubularSegments;
  28257. this.p = p;
  28258. this.q = q;
  28259. this.side = side;
  28260. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28261. }
  28262. TorusKnot.prototype._regenerateVertexData = function () {
  28263. 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 });
  28264. };
  28265. TorusKnot.prototype.copy = function (id) {
  28266. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28267. };
  28268. TorusKnot.prototype.serialize = function () {
  28269. var serializationObject = _super.prototype.serialize.call(this);
  28270. serializationObject.radius = this.radius;
  28271. serializationObject.tube = this.tube;
  28272. serializationObject.radialSegments = this.radialSegments;
  28273. serializationObject.tubularSegments = this.tubularSegments;
  28274. serializationObject.p = this.p;
  28275. serializationObject.q = this.q;
  28276. return serializationObject;
  28277. };
  28278. ;
  28279. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28280. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28281. return null; // null since geometry could be something else than a ground...
  28282. }
  28283. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28284. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28285. scene.pushGeometry(torusKnot, true);
  28286. return torusKnot;
  28287. };
  28288. return TorusKnot;
  28289. })(_Primitive);
  28290. Primitives.TorusKnot = TorusKnot;
  28291. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28292. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28293. })(BABYLON || (BABYLON = {}));
  28294. var BABYLON;
  28295. (function (BABYLON) {
  28296. var GroundMesh = (function (_super) {
  28297. __extends(GroundMesh, _super);
  28298. function GroundMesh(name, scene) {
  28299. _super.call(this, name, scene);
  28300. this.generateOctree = false;
  28301. this._worldInverse = new BABYLON.Matrix();
  28302. }
  28303. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28304. get: function () {
  28305. return this._subdivisions;
  28306. },
  28307. enumerable: true,
  28308. configurable: true
  28309. });
  28310. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28311. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28312. this._subdivisions = chunksCount;
  28313. this.subdivide(this._subdivisions);
  28314. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28315. };
  28316. /**
  28317. * Returns a height (y) value in the Worl system :
  28318. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28319. * Returns the ground y position if (x, z) are outside the ground surface.
  28320. * Not pertinent if the ground is rotated.
  28321. */
  28322. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28323. // express x and y in the ground local system
  28324. x -= this.position.x;
  28325. z -= this.position.z;
  28326. x /= this.scaling.x;
  28327. z /= this.scaling.z;
  28328. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28329. return this.position.y;
  28330. }
  28331. if (!this._heightQuads || this._heightQuads.length == 0) {
  28332. this._initHeightQuads();
  28333. this._computeHeightQuads();
  28334. }
  28335. var facet = this._getFacetAt(x, z);
  28336. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28337. // return y in the World system
  28338. return y * this.scaling.y + this.position.y;
  28339. };
  28340. /**
  28341. * Returns a normalized vector (Vector3) orthogonal to the ground
  28342. * at the ground coordinates (x, z) expressed in the World system.
  28343. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28344. * Not pertinent if the ground is rotated.
  28345. */
  28346. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28347. var normal = new BABYLON.Vector3(0, 1, 0);
  28348. this.getNormalAtCoordinatesToRef(x, z, normal);
  28349. return normal;
  28350. };
  28351. /**
  28352. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28353. * at the ground coordinates (x, z) expressed in the World system.
  28354. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28355. * Not pertinent if the ground is rotated.
  28356. */
  28357. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28358. // express x and y in the ground local system
  28359. x -= this.position.x;
  28360. z -= this.position.z;
  28361. x /= this.scaling.x;
  28362. z /= this.scaling.z;
  28363. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28364. return;
  28365. }
  28366. if (!this._heightQuads || this._heightQuads.length == 0) {
  28367. this._initHeightQuads();
  28368. this._computeHeightQuads();
  28369. }
  28370. var facet = this._getFacetAt(x, z);
  28371. ref.x = facet.x;
  28372. ref.y = facet.y;
  28373. ref.z = facet.z;
  28374. };
  28375. /**
  28376. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28377. * if the ground has been updated.
  28378. * This can be used in the render loop
  28379. */
  28380. GroundMesh.prototype.updateCoordinateHeights = function () {
  28381. if (!this._heightQuads || this._heightQuads.length == 0) {
  28382. this._initHeightQuads();
  28383. }
  28384. this._computeHeightQuads();
  28385. };
  28386. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28387. GroundMesh.prototype._getFacetAt = function (x, z) {
  28388. // retrieve col and row from x, z coordinates in the ground local system
  28389. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28390. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28391. var quad = this._heightQuads[row * this._subdivisions + col];
  28392. var facet;
  28393. if (z < quad.slope.x * x + quad.slope.y) {
  28394. facet = quad.facet1;
  28395. }
  28396. else {
  28397. facet = quad.facet2;
  28398. }
  28399. return facet;
  28400. };
  28401. // Creates and populates the heightMap array with "facet" elements :
  28402. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28403. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28404. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28405. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28406. GroundMesh.prototype._initHeightQuads = function () {
  28407. this._heightQuads = new Array();
  28408. for (var row = 0; row < this._subdivisions; row++) {
  28409. for (var col = 0; col < this._subdivisions; col++) {
  28410. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  28411. this._heightQuads[row * this._subdivisions + col] = quad;
  28412. }
  28413. }
  28414. };
  28415. // Compute each quad element values and update the the heightMap array :
  28416. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28417. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28418. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28419. GroundMesh.prototype._computeHeightQuads = function () {
  28420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28421. var v1 = BABYLON.Tmp.Vector3[0];
  28422. var v2 = BABYLON.Tmp.Vector3[1];
  28423. var v3 = BABYLON.Tmp.Vector3[2];
  28424. var v4 = BABYLON.Tmp.Vector3[3];
  28425. var v1v2 = BABYLON.Tmp.Vector3[4];
  28426. var v1v3 = BABYLON.Tmp.Vector3[5];
  28427. var v1v4 = BABYLON.Tmp.Vector3[6];
  28428. var norm1 = BABYLON.Tmp.Vector3[7];
  28429. var norm2 = BABYLON.Tmp.Vector3[8];
  28430. var i = 0;
  28431. var j = 0;
  28432. var k = 0;
  28433. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28434. var h = 0;
  28435. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28436. var d2 = 0;
  28437. for (var row = 0; row < this._subdivisions; row++) {
  28438. for (var col = 0; col < this._subdivisions; col++) {
  28439. i = col * 3;
  28440. j = row * (this._subdivisions + 1) * 3;
  28441. k = (row + 1) * (this._subdivisions + 1) * 3;
  28442. v1.x = positions[j + i];
  28443. v1.y = positions[j + i + 1];
  28444. v1.z = positions[j + i + 2];
  28445. v2.x = positions[j + i + 3];
  28446. v2.y = positions[j + i + 4];
  28447. v2.z = positions[j + i + 5];
  28448. v3.x = positions[k + i];
  28449. v3.y = positions[k + i + 1];
  28450. v3.z = positions[k + i + 2];
  28451. v4.x = positions[k + i + 3];
  28452. v4.y = positions[k + i + 4];
  28453. v4.z = positions[k + i + 5];
  28454. // 2D slope V1V4
  28455. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28456. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28457. // facet equations :
  28458. // we compute each facet normal vector
  28459. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28460. // we compute the value d by applying the equation to v1 which belongs to the plane
  28461. // then we store the facet equation in a Vector4
  28462. v2.subtractToRef(v1, v1v2);
  28463. v3.subtractToRef(v1, v1v3);
  28464. v4.subtractToRef(v1, v1v4);
  28465. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28466. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28467. norm1.normalize();
  28468. norm2.normalize();
  28469. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28470. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28471. var quad = this._heightQuads[row * this._subdivisions + col];
  28472. quad.slope.copyFromFloats(cd, h);
  28473. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  28474. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  28475. }
  28476. }
  28477. };
  28478. return GroundMesh;
  28479. })(BABYLON.Mesh);
  28480. BABYLON.GroundMesh = GroundMesh;
  28481. })(BABYLON || (BABYLON = {}));
  28482. var BABYLON;
  28483. (function (BABYLON) {
  28484. var LinesMesh = (function (_super) {
  28485. __extends(LinesMesh, _super);
  28486. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28487. if (parent === void 0) { parent = null; }
  28488. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28489. this.color = new BABYLON.Color3(1, 1, 1);
  28490. this.alpha = 1;
  28491. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28492. attributes: ["position"],
  28493. uniforms: ["worldViewProjection", "color"],
  28494. needAlphaBlending: true
  28495. });
  28496. }
  28497. Object.defineProperty(LinesMesh.prototype, "material", {
  28498. get: function () {
  28499. return this._colorShader;
  28500. },
  28501. enumerable: true,
  28502. configurable: true
  28503. });
  28504. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28505. get: function () {
  28506. return false;
  28507. },
  28508. enumerable: true,
  28509. configurable: true
  28510. });
  28511. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28512. get: function () {
  28513. return false;
  28514. },
  28515. enumerable: true,
  28516. configurable: true
  28517. });
  28518. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28519. var engine = this.getScene().getEngine();
  28520. var indexToBind = this._geometry.getIndexBuffer();
  28521. // VBOs
  28522. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28523. // Color
  28524. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28525. };
  28526. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28527. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28528. return;
  28529. }
  28530. var engine = this.getScene().getEngine();
  28531. // Draw order
  28532. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28533. };
  28534. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28535. return null;
  28536. };
  28537. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28538. this._colorShader.dispose();
  28539. _super.prototype.dispose.call(this, doNotRecurse);
  28540. };
  28541. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28542. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28543. };
  28544. return LinesMesh;
  28545. })(BABYLON.Mesh);
  28546. BABYLON.LinesMesh = LinesMesh;
  28547. })(BABYLON || (BABYLON = {}));
  28548. var BABYLON;
  28549. (function (BABYLON) {
  28550. var DebugLayer = (function () {
  28551. function DebugLayer(scene) {
  28552. var _this = this;
  28553. this._transformationMatrix = BABYLON.Matrix.Identity();
  28554. this._enabled = false;
  28555. this._labelsEnabled = false;
  28556. this._displayStatistics = true;
  28557. this._displayTree = false;
  28558. this._displayLogs = false;
  28559. this._identityMatrix = BABYLON.Matrix.Identity();
  28560. this.axisRatio = 0.02;
  28561. this.accentColor = "orange";
  28562. this._scene = scene;
  28563. this._syncPositions = function () {
  28564. var engine = _this._scene.getEngine();
  28565. var canvasRect = engine.getRenderingCanvasClientRect();
  28566. if (_this._showUI) {
  28567. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28568. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28569. _this._statsDiv.style.width = "400px";
  28570. _this._statsDiv.style.height = "auto";
  28571. _this._statsSubsetDiv.style.maxHeight = "240px";
  28572. _this._optionsDiv.style.left = "0px";
  28573. _this._optionsDiv.style.top = "10px";
  28574. _this._optionsDiv.style.width = "200px";
  28575. _this._optionsDiv.style.height = "auto";
  28576. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28577. _this._logDiv.style.left = "0px";
  28578. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28579. _this._logDiv.style.width = "600px";
  28580. _this._logDiv.style.height = "160px";
  28581. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28582. _this._treeDiv.style.top = "10px";
  28583. _this._treeDiv.style.width = "300px";
  28584. _this._treeDiv.style.height = "auto";
  28585. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28586. }
  28587. _this._globalDiv.style.left = canvasRect.left + "px";
  28588. _this._globalDiv.style.top = canvasRect.top + "px";
  28589. _this._drawingCanvas.style.left = "0px";
  28590. _this._drawingCanvas.style.top = "0px";
  28591. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28592. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28593. var devicePixelRatio = window.devicePixelRatio || 1;
  28594. var context = _this._drawingContext;
  28595. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28596. context.mozBackingStorePixelRatio ||
  28597. context.msBackingStorePixelRatio ||
  28598. context.oBackingStorePixelRatio ||
  28599. context.backingStorePixelRatio || 1;
  28600. _this._ratio = devicePixelRatio / backingStoreRatio;
  28601. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28602. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28603. };
  28604. this._onCanvasClick = function (evt) {
  28605. _this._clickPosition = {
  28606. x: evt.clientX * _this._ratio,
  28607. y: evt.clientY * _this._ratio
  28608. };
  28609. };
  28610. this._syncUI = function () {
  28611. if (_this._showUI) {
  28612. if (_this._displayStatistics) {
  28613. _this._displayStats();
  28614. _this._statsDiv.style.display = "";
  28615. }
  28616. else {
  28617. _this._statsDiv.style.display = "none";
  28618. }
  28619. if (_this._displayLogs) {
  28620. _this._logDiv.style.display = "";
  28621. }
  28622. else {
  28623. _this._logDiv.style.display = "none";
  28624. }
  28625. if (_this._displayTree) {
  28626. _this._treeDiv.style.display = "";
  28627. if (_this._needToRefreshMeshesTree) {
  28628. _this._needToRefreshMeshesTree = false;
  28629. _this._refreshMeshesTreeContent();
  28630. }
  28631. }
  28632. else {
  28633. _this._treeDiv.style.display = "none";
  28634. }
  28635. }
  28636. };
  28637. this._syncData = function () {
  28638. if (_this._labelsEnabled || !_this._showUI) {
  28639. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28640. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28641. var engine = _this._scene.getEngine();
  28642. var viewport = _this._camera.viewport;
  28643. var globalViewport = viewport.toGlobal(engine);
  28644. // Meshes
  28645. var meshes = _this._camera.getActiveMeshes();
  28646. var index;
  28647. var projectedPosition;
  28648. for (index = 0; index < meshes.length; index++) {
  28649. var mesh = meshes.data[index];
  28650. var position = mesh.getBoundingInfo().boundingSphere.center;
  28651. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28652. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28653. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28654. }
  28655. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28656. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28657. }
  28658. }
  28659. // Cameras
  28660. var cameras = _this._scene.cameras;
  28661. for (index = 0; index < cameras.length; index++) {
  28662. var camera = cameras[index];
  28663. if (camera === _this._camera) {
  28664. continue;
  28665. }
  28666. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28667. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28668. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28669. _this._camera.detachControl(engine.getRenderingCanvas());
  28670. _this._camera = camera;
  28671. _this._camera.attachControl(engine.getRenderingCanvas());
  28672. }, function () { return "purple"; });
  28673. }
  28674. }
  28675. // Lights
  28676. var lights = _this._scene.lights;
  28677. for (index = 0; index < lights.length; index++) {
  28678. var light = lights[index];
  28679. if (light.position) {
  28680. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28681. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28682. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28683. light.setEnabled(!light.isEnabled());
  28684. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28685. }
  28686. }
  28687. }
  28688. }
  28689. _this._clickPosition = undefined;
  28690. };
  28691. }
  28692. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28693. while (this._treeSubsetDiv.hasChildNodes()) {
  28694. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28695. }
  28696. // Add meshes
  28697. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28698. sortedArray.sort(function (a, b) {
  28699. if (a.name === b.name) {
  28700. return 0;
  28701. }
  28702. return (a.name > b.name) ? 1 : -1;
  28703. });
  28704. for (var index = 0; index < sortedArray.length; index++) {
  28705. var mesh = sortedArray[index];
  28706. if (!mesh.isEnabled()) {
  28707. continue;
  28708. }
  28709. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28710. m.isVisible = element.checked;
  28711. }, mesh);
  28712. }
  28713. };
  28714. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28715. this._drawingContext.beginPath();
  28716. this._drawingContext.moveTo(zero.x, zero.y);
  28717. this._drawingContext.lineTo(unit.x, unit.y);
  28718. this._drawingContext.strokeStyle = color;
  28719. this._drawingContext.lineWidth = 4;
  28720. this._drawingContext.stroke();
  28721. this._drawingContext.font = "normal 14px Segoe UI";
  28722. this._drawingContext.fillStyle = color;
  28723. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28724. };
  28725. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28726. var position = mesh.getBoundingInfo().boundingSphere.center;
  28727. var worldMatrix = mesh.getWorldMatrix();
  28728. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28729. var unit = (unprojectedVector.subtract(position)).length();
  28730. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28731. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28732. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28733. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28734. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28735. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28736. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28737. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28738. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28739. };
  28740. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28741. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28742. this._drawingContext.font = "normal 12px Segoe UI";
  28743. var textMetrics = this._drawingContext.measureText(text);
  28744. var centerX = projectedPosition.x - textMetrics.width / 2;
  28745. var centerY = projectedPosition.y;
  28746. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28747. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28748. onClick();
  28749. }
  28750. this._drawingContext.beginPath();
  28751. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28752. this._drawingContext.fillStyle = getFillStyle();
  28753. this._drawingContext.globalAlpha = 0.5;
  28754. this._drawingContext.fill();
  28755. this._drawingContext.globalAlpha = 1.0;
  28756. this._drawingContext.strokeStyle = '#FFFFFF';
  28757. this._drawingContext.lineWidth = 1;
  28758. this._drawingContext.stroke();
  28759. this._drawingContext.fillStyle = "#FFFFFF";
  28760. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28761. this._drawingContext.beginPath();
  28762. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28763. this._drawingContext.fill();
  28764. }
  28765. };
  28766. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28767. if (!this._clickPosition) {
  28768. return false;
  28769. }
  28770. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28771. return false;
  28772. }
  28773. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28774. return false;
  28775. }
  28776. return true;
  28777. };
  28778. DebugLayer.prototype.isVisible = function () {
  28779. return this._enabled;
  28780. };
  28781. DebugLayer.prototype.hide = function () {
  28782. if (!this._enabled) {
  28783. return;
  28784. }
  28785. this._enabled = false;
  28786. var engine = this._scene.getEngine();
  28787. this._scene.unregisterBeforeRender(this._syncData);
  28788. this._scene.unregisterAfterRender(this._syncUI);
  28789. this._rootElement.removeChild(this._globalDiv);
  28790. this._scene.forceShowBoundingBoxes = false;
  28791. this._scene.forceWireframe = false;
  28792. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28793. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28794. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28795. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28796. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28797. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28798. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28799. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28800. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28801. this._scene.shadowsEnabled = true;
  28802. this._scene.particlesEnabled = true;
  28803. this._scene.postProcessesEnabled = true;
  28804. this._scene.collisionsEnabled = true;
  28805. this._scene.lightsEnabled = true;
  28806. this._scene.texturesEnabled = true;
  28807. this._scene.lensFlaresEnabled = true;
  28808. this._scene.proceduralTexturesEnabled = true;
  28809. this._scene.renderTargetsEnabled = true;
  28810. this._scene.probesEnabled = true;
  28811. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28812. };
  28813. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28814. if (showUI === void 0) { showUI = true; }
  28815. if (camera === void 0) { camera = null; }
  28816. if (rootElement === void 0) { rootElement = null; }
  28817. if (this._enabled) {
  28818. return;
  28819. }
  28820. this._enabled = true;
  28821. if (camera) {
  28822. this._camera = camera;
  28823. }
  28824. else {
  28825. this._camera = this._scene.activeCamera;
  28826. }
  28827. this._showUI = showUI;
  28828. var engine = this._scene.getEngine();
  28829. this._globalDiv = document.createElement("div");
  28830. this._rootElement = rootElement || document.body;
  28831. this._rootElement.appendChild(this._globalDiv);
  28832. this._generateDOMelements();
  28833. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28834. this._syncPositions();
  28835. this._scene.registerBeforeRender(this._syncData);
  28836. this._scene.registerAfterRender(this._syncUI);
  28837. };
  28838. DebugLayer.prototype._clearLabels = function () {
  28839. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28840. for (var index = 0; index < this._scene.meshes.length; index++) {
  28841. var mesh = this._scene.meshes[index];
  28842. mesh.renderOverlay = false;
  28843. }
  28844. };
  28845. DebugLayer.prototype._generateheader = function (root, text) {
  28846. var header = document.createElement("div");
  28847. header.innerHTML = text + "&nbsp;";
  28848. header.style.textAlign = "right";
  28849. header.style.width = "100%";
  28850. header.style.color = "white";
  28851. header.style.backgroundColor = "Black";
  28852. header.style.padding = "5px 5px 4px 0px";
  28853. header.style.marginLeft = "-5px";
  28854. header.style.fontWeight = "bold";
  28855. root.appendChild(header);
  28856. };
  28857. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28858. var label = document.createElement("label");
  28859. label.innerHTML = title;
  28860. label.style.color = color;
  28861. root.appendChild(label);
  28862. root.appendChild(document.createElement("br"));
  28863. };
  28864. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28865. if (tag === void 0) { tag = null; }
  28866. var label = document.createElement("label");
  28867. var boundingBoxesCheckbox = document.createElement("input");
  28868. boundingBoxesCheckbox.type = "checkbox";
  28869. boundingBoxesCheckbox.checked = initialState;
  28870. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28871. task(evt.target, tag);
  28872. });
  28873. label.appendChild(boundingBoxesCheckbox);
  28874. var container = document.createElement("span");
  28875. var leftPart = document.createElement("span");
  28876. var rightPart = document.createElement("span");
  28877. rightPart.style.cssFloat = "right";
  28878. leftPart.innerHTML = leftTitle;
  28879. rightPart.innerHTML = rightTitle;
  28880. rightPart.style.fontSize = "12px";
  28881. rightPart.style.maxWidth = "200px";
  28882. container.appendChild(leftPart);
  28883. container.appendChild(rightPart);
  28884. label.appendChild(container);
  28885. root.appendChild(label);
  28886. root.appendChild(document.createElement("br"));
  28887. };
  28888. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28889. if (tag === void 0) { tag = null; }
  28890. var label = document.createElement("label");
  28891. var checkBox = document.createElement("input");
  28892. checkBox.type = "checkbox";
  28893. checkBox.checked = initialState;
  28894. checkBox.addEventListener("change", function (evt) {
  28895. task(evt.target, tag);
  28896. });
  28897. label.appendChild(checkBox);
  28898. label.appendChild(document.createTextNode(title));
  28899. root.appendChild(label);
  28900. root.appendChild(document.createElement("br"));
  28901. };
  28902. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28903. if (tag === void 0) { tag = null; }
  28904. var button = document.createElement("button");
  28905. button.innerHTML = title;
  28906. button.style.height = "24px";
  28907. button.style.width = "150px";
  28908. button.style.marginBottom = "5px";
  28909. button.style.color = "#444444";
  28910. button.style.border = "1px solid white";
  28911. button.className = "debugLayerButton";
  28912. button.addEventListener("click", function (evt) {
  28913. task(evt.target, tag);
  28914. });
  28915. root.appendChild(button);
  28916. root.appendChild(document.createElement("br"));
  28917. };
  28918. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28919. if (tag === void 0) { tag = null; }
  28920. var label = document.createElement("label");
  28921. var boundingBoxesRadio = document.createElement("input");
  28922. boundingBoxesRadio.type = "radio";
  28923. boundingBoxesRadio.name = name;
  28924. boundingBoxesRadio.checked = initialState;
  28925. boundingBoxesRadio.addEventListener("change", function (evt) {
  28926. task(evt.target, tag);
  28927. });
  28928. label.appendChild(boundingBoxesRadio);
  28929. label.appendChild(document.createTextNode(title));
  28930. root.appendChild(label);
  28931. root.appendChild(document.createElement("br"));
  28932. };
  28933. DebugLayer.prototype._generateDOMelements = function () {
  28934. var _this = this;
  28935. this._globalDiv.id = "DebugLayer";
  28936. this._globalDiv.style.position = "absolute";
  28937. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28938. this._globalDiv.style.fontSize = "14px";
  28939. this._globalDiv.style.color = "white";
  28940. // Drawing canvas
  28941. this._drawingCanvas = document.createElement("canvas");
  28942. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28943. this._drawingCanvas.style.position = "absolute";
  28944. this._drawingCanvas.style.pointerEvents = "none";
  28945. this._drawingCanvas.style.backgroundColor = "transparent";
  28946. this._drawingContext = this._drawingCanvas.getContext("2d");
  28947. this._globalDiv.appendChild(this._drawingCanvas);
  28948. if (this._showUI) {
  28949. var background = "rgba(128, 128, 128, 0.4)";
  28950. var border = "rgb(180, 180, 180) solid 1px";
  28951. // Stats
  28952. this._statsDiv = document.createElement("div");
  28953. this._statsDiv.id = "DebugLayerStats";
  28954. this._statsDiv.style.border = border;
  28955. this._statsDiv.style.position = "absolute";
  28956. this._statsDiv.style.background = background;
  28957. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28958. this._generateheader(this._statsDiv, "STATISTICS");
  28959. this._statsSubsetDiv = document.createElement("div");
  28960. this._statsSubsetDiv.style.paddingTop = "5px";
  28961. this._statsSubsetDiv.style.paddingBottom = "5px";
  28962. this._statsSubsetDiv.style.overflowY = "auto";
  28963. this._statsDiv.appendChild(this._statsSubsetDiv);
  28964. // Tree
  28965. this._treeDiv = document.createElement("div");
  28966. this._treeDiv.id = "DebugLayerTree";
  28967. this._treeDiv.style.border = border;
  28968. this._treeDiv.style.position = "absolute";
  28969. this._treeDiv.style.background = background;
  28970. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28971. this._treeDiv.style.display = "none";
  28972. this._generateheader(this._treeDiv, "MESHES TREE");
  28973. this._treeSubsetDiv = document.createElement("div");
  28974. this._treeSubsetDiv.style.paddingTop = "5px";
  28975. this._treeSubsetDiv.style.paddingRight = "5px";
  28976. this._treeSubsetDiv.style.overflowY = "auto";
  28977. this._treeSubsetDiv.style.maxHeight = "300px";
  28978. this._treeDiv.appendChild(this._treeSubsetDiv);
  28979. this._needToRefreshMeshesTree = true;
  28980. // Logs
  28981. this._logDiv = document.createElement("div");
  28982. this._logDiv.style.border = border;
  28983. this._logDiv.id = "DebugLayerLogs";
  28984. this._logDiv.style.position = "absolute";
  28985. this._logDiv.style.background = background;
  28986. this._logDiv.style.padding = "0px 0px 0px 5px";
  28987. this._logDiv.style.display = "none";
  28988. this._generateheader(this._logDiv, "LOGS");
  28989. this._logSubsetDiv = document.createElement("div");
  28990. this._logSubsetDiv.style.height = "127px";
  28991. this._logSubsetDiv.style.paddingTop = "5px";
  28992. this._logSubsetDiv.style.overflowY = "auto";
  28993. this._logSubsetDiv.style.fontSize = "12px";
  28994. this._logSubsetDiv.style.fontFamily = "consolas";
  28995. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28996. this._logDiv.appendChild(this._logSubsetDiv);
  28997. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28998. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28999. };
  29000. // Options
  29001. this._optionsDiv = document.createElement("div");
  29002. this._optionsDiv.id = "DebugLayerOptions";
  29003. this._optionsDiv.style.border = border;
  29004. this._optionsDiv.style.position = "absolute";
  29005. this._optionsDiv.style.background = background;
  29006. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29007. this._optionsDiv.style.overflowY = "auto";
  29008. this._generateheader(this._optionsDiv, "OPTIONS");
  29009. this._optionsSubsetDiv = document.createElement("div");
  29010. this._optionsSubsetDiv.style.paddingTop = "5px";
  29011. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29012. this._optionsSubsetDiv.style.overflowY = "auto";
  29013. this._optionsSubsetDiv.style.maxHeight = "200px";
  29014. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29015. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29016. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29017. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29018. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29019. _this._displayTree = element.checked;
  29020. _this._needToRefreshMeshesTree = true;
  29021. });
  29022. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29023. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29024. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29025. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29026. _this._labelsEnabled = element.checked;
  29027. if (!_this._labelsEnabled) {
  29028. _this._clearLabels();
  29029. }
  29030. });
  29031. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29032. if (element.checked) {
  29033. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29034. }
  29035. else {
  29036. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29037. }
  29038. });
  29039. ;
  29040. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29041. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29042. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29043. if (element.checked) {
  29044. _this._scene.forceWireframe = false;
  29045. _this._scene.forcePointsCloud = false;
  29046. }
  29047. });
  29048. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29049. if (element.checked) {
  29050. _this._scene.forceWireframe = true;
  29051. _this._scene.forcePointsCloud = false;
  29052. }
  29053. });
  29054. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29055. if (element.checked) {
  29056. _this._scene.forceWireframe = false;
  29057. _this._scene.forcePointsCloud = true;
  29058. }
  29059. });
  29060. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29061. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29062. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29063. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29064. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29065. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29066. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29067. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29068. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29069. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29070. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29071. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29072. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29073. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29074. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29075. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29076. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29077. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29078. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29079. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29080. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29081. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29082. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29083. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29084. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29085. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29086. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29087. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29088. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29089. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29090. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29091. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29092. if (element.checked) {
  29093. _this._scene.headphone = true;
  29094. }
  29095. });
  29096. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29097. if (element.checked) {
  29098. _this._scene.headphone = false;
  29099. }
  29100. });
  29101. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29102. _this._scene.audioEnabled = !element.checked;
  29103. });
  29104. }
  29105. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29106. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29107. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29108. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29109. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29110. if (_this._camera) {
  29111. console.log(_this._camera);
  29112. }
  29113. else {
  29114. console.warn("No camera defined, or debug layer created before camera creation!");
  29115. }
  29116. });
  29117. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29118. this._globalDiv.appendChild(this._statsDiv);
  29119. this._globalDiv.appendChild(this._logDiv);
  29120. this._globalDiv.appendChild(this._optionsDiv);
  29121. this._globalDiv.appendChild(this._treeDiv);
  29122. }
  29123. };
  29124. DebugLayer.prototype._displayStats = function () {
  29125. var scene = this._scene;
  29126. var engine = scene.getEngine();
  29127. var glInfo = engine.getGlInfo();
  29128. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29129. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29130. + "<b>Count</b><br>"
  29131. + "Total meshes: " + scene.meshes.length + "<br>"
  29132. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29133. + "Total materials: " + scene.materials.length + "<br>"
  29134. + "Total textures: " + scene.textures.length + "<br>"
  29135. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29136. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29137. + "Active bones: " + scene.getActiveBones() + "<br>"
  29138. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29139. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29140. + "<b>Duration</b><br>"
  29141. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29142. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29143. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29144. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29145. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29146. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29147. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29148. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29149. + "</div>"
  29150. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29151. + "<b>Extensions</b><br>"
  29152. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29153. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29154. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29155. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29156. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29157. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29158. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29159. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29160. + "</div><br>"
  29161. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29162. + "<b>Caps.</b><br>"
  29163. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29164. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29165. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29166. + "<b>Info</b><br>"
  29167. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29168. + glInfo.version + "<br>"
  29169. + "</div><br>"
  29170. + glInfo.renderer + "<br>";
  29171. if (this.customStatsFunction) {
  29172. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29173. }
  29174. };
  29175. return DebugLayer;
  29176. })();
  29177. BABYLON.DebugLayer = DebugLayer;
  29178. })(BABYLON || (BABYLON = {}));
  29179. var BABYLON;
  29180. (function (BABYLON) {
  29181. var DefaultLoadingScreen = (function () {
  29182. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29183. var _this = this;
  29184. if (_loadingText === void 0) { _loadingText = ""; }
  29185. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29186. this._renderingCanvas = _renderingCanvas;
  29187. this._loadingText = _loadingText;
  29188. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29189. // Resize
  29190. this._resizeLoadingUI = function () {
  29191. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29192. _this._loadingDiv.style.position = "absolute";
  29193. _this._loadingDiv.style.left = canvasRect.left + "px";
  29194. _this._loadingDiv.style.top = canvasRect.top + "px";
  29195. _this._loadingDiv.style.width = canvasRect.width + "px";
  29196. _this._loadingDiv.style.height = canvasRect.height + "px";
  29197. };
  29198. }
  29199. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29200. var _this = this;
  29201. if (this._loadingDiv) {
  29202. // Do not add a loading screen if there is already one
  29203. return;
  29204. }
  29205. this._loadingDiv = document.createElement("div");
  29206. this._loadingDiv.id = "babylonjsLoadingDiv";
  29207. this._loadingDiv.style.opacity = "0";
  29208. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29209. // Loading text
  29210. this._loadingTextDiv = document.createElement("div");
  29211. this._loadingTextDiv.style.position = "absolute";
  29212. this._loadingTextDiv.style.left = "0";
  29213. this._loadingTextDiv.style.top = "50%";
  29214. this._loadingTextDiv.style.marginTop = "80px";
  29215. this._loadingTextDiv.style.width = "100%";
  29216. this._loadingTextDiv.style.height = "20px";
  29217. this._loadingTextDiv.style.fontFamily = "Arial";
  29218. this._loadingTextDiv.style.fontSize = "14px";
  29219. this._loadingTextDiv.style.color = "white";
  29220. this._loadingTextDiv.style.textAlign = "center";
  29221. this._loadingTextDiv.innerHTML = "Loading";
  29222. this._loadingDiv.appendChild(this._loadingTextDiv);
  29223. //set the predefined text
  29224. this._loadingTextDiv.innerHTML = this._loadingText;
  29225. // Loading img
  29226. var imgBack = new Image();
  29227. 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==";
  29228. imgBack.style.position = "absolute";
  29229. imgBack.style.left = "50%";
  29230. imgBack.style.top = "50%";
  29231. imgBack.style.marginLeft = "-50px";
  29232. imgBack.style.marginTop = "-50px";
  29233. imgBack.style.transition = "transform 1.0s ease";
  29234. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29235. var deg = 360;
  29236. var onTransitionEnd = function () {
  29237. deg += 360;
  29238. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29239. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29240. };
  29241. imgBack.addEventListener("transitionend", onTransitionEnd);
  29242. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29243. this._loadingDiv.appendChild(imgBack);
  29244. // front image
  29245. var imgFront = new Image();
  29246. 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=";
  29247. imgFront.style.position = "absolute";
  29248. imgFront.style.left = "50%";
  29249. imgFront.style.top = "50%";
  29250. imgFront.style.marginLeft = "-50px";
  29251. imgFront.style.marginTop = "-50px";
  29252. this._loadingDiv.appendChild(imgFront);
  29253. this._resizeLoadingUI();
  29254. window.addEventListener("resize", this._resizeLoadingUI);
  29255. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29256. document.body.appendChild(this._loadingDiv);
  29257. setTimeout(function () {
  29258. _this._loadingDiv.style.opacity = "1";
  29259. imgBack.style.transform = "rotateZ(360deg)";
  29260. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29261. }, 0);
  29262. };
  29263. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29264. var _this = this;
  29265. if (!this._loadingDiv) {
  29266. return;
  29267. }
  29268. var onTransitionEnd = function () {
  29269. if (!_this._loadingDiv) {
  29270. return;
  29271. }
  29272. document.body.removeChild(_this._loadingDiv);
  29273. window.removeEventListener("resize", _this._resizeLoadingUI);
  29274. _this._loadingDiv = null;
  29275. };
  29276. this._loadingDiv.style.opacity = "0";
  29277. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29278. };
  29279. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29280. set: function (text) {
  29281. this._loadingText = text;
  29282. if (this._loadingTextDiv) {
  29283. this._loadingTextDiv.innerHTML = this._loadingText;
  29284. }
  29285. },
  29286. enumerable: true,
  29287. configurable: true
  29288. });
  29289. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29290. get: function () {
  29291. return this._loadingDivBackgroundColor;
  29292. },
  29293. set: function (color) {
  29294. this._loadingDivBackgroundColor = color;
  29295. if (!this._loadingDiv) {
  29296. return;
  29297. }
  29298. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. return DefaultLoadingScreen;
  29304. })();
  29305. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29306. })(BABYLON || (BABYLON = {}));
  29307. var BABYLON;
  29308. (function (BABYLON) {
  29309. var AudioEngine = (function () {
  29310. function AudioEngine() {
  29311. this._audioContext = null;
  29312. this._audioContextInitialized = false;
  29313. this.canUseWebAudio = false;
  29314. this.WarnedWebAudioUnsupported = false;
  29315. this.unlocked = false;
  29316. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29317. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29318. this.canUseWebAudio = true;
  29319. }
  29320. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  29321. this._unlockiOSaudio();
  29322. }
  29323. else {
  29324. this.unlocked = true;
  29325. }
  29326. }
  29327. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29328. get: function () {
  29329. if (!this._audioContextInitialized) {
  29330. this._initializeAudioContext();
  29331. }
  29332. return this._audioContext;
  29333. },
  29334. enumerable: true,
  29335. configurable: true
  29336. });
  29337. AudioEngine.prototype._unlockiOSaudio = function () {
  29338. var _this = this;
  29339. var unlockaudio = function () {
  29340. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  29341. var source = _this.audioContext.createBufferSource();
  29342. source.buffer = buffer;
  29343. source.connect(_this.audioContext.destination);
  29344. source.start(0);
  29345. setTimeout(function () {
  29346. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  29347. _this.unlocked = true;
  29348. window.removeEventListener('touchend', unlockaudio, false);
  29349. if (_this.onAudioUnlocked) {
  29350. _this.onAudioUnlocked();
  29351. }
  29352. }
  29353. }, 0);
  29354. };
  29355. window.addEventListener('touchend', unlockaudio, false);
  29356. };
  29357. AudioEngine.prototype._initializeAudioContext = function () {
  29358. try {
  29359. if (this.canUseWebAudio) {
  29360. this._audioContext = new AudioContext();
  29361. // create a global volume gain node
  29362. this.masterGain = this._audioContext.createGain();
  29363. this.masterGain.gain.value = 1;
  29364. this.masterGain.connect(this._audioContext.destination);
  29365. this._audioContextInitialized = true;
  29366. }
  29367. }
  29368. catch (e) {
  29369. this.canUseWebAudio = false;
  29370. BABYLON.Tools.Error("Web Audio: " + e.message);
  29371. }
  29372. };
  29373. AudioEngine.prototype.dispose = function () {
  29374. if (this.canUseWebAudio && this._audioContextInitialized) {
  29375. if (this._connectedAnalyser) {
  29376. this._connectedAnalyser.stopDebugCanvas();
  29377. this._connectedAnalyser.dispose();
  29378. this.masterGain.disconnect();
  29379. this.masterGain.connect(this._audioContext.destination);
  29380. this._connectedAnalyser = null;
  29381. }
  29382. this.masterGain.gain.value = 1;
  29383. }
  29384. this.WarnedWebAudioUnsupported = false;
  29385. };
  29386. AudioEngine.prototype.getGlobalVolume = function () {
  29387. if (this.canUseWebAudio && this._audioContextInitialized) {
  29388. return this.masterGain.gain.value;
  29389. }
  29390. else {
  29391. return -1;
  29392. }
  29393. };
  29394. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29395. if (this.canUseWebAudio && this._audioContextInitialized) {
  29396. this.masterGain.gain.value = newVolume;
  29397. }
  29398. };
  29399. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29400. if (this._connectedAnalyser) {
  29401. this._connectedAnalyser.stopDebugCanvas();
  29402. }
  29403. if (this.canUseWebAudio && this._audioContextInitialized) {
  29404. this._connectedAnalyser = analyser;
  29405. this.masterGain.disconnect();
  29406. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29407. }
  29408. };
  29409. return AudioEngine;
  29410. })();
  29411. BABYLON.AudioEngine = AudioEngine;
  29412. })(BABYLON || (BABYLON = {}));
  29413. var BABYLON;
  29414. (function (BABYLON) {
  29415. var Sound = (function () {
  29416. /**
  29417. * Create a sound and attach it to a scene
  29418. * @param name Name of your sound
  29419. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29420. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29421. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  29422. */
  29423. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29424. var _this = this;
  29425. this.autoplay = false;
  29426. this.loop = false;
  29427. this.useCustomAttenuation = false;
  29428. this.spatialSound = false;
  29429. this.refDistance = 1;
  29430. this.rolloffFactor = 1;
  29431. this.maxDistance = 100;
  29432. this.distanceModel = "linear";
  29433. this._panningModel = "equalpower";
  29434. this._playbackRate = 1;
  29435. this._streaming = false;
  29436. this._startTime = 0;
  29437. this._startOffset = 0;
  29438. this._position = BABYLON.Vector3.Zero();
  29439. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29440. this._volume = 1;
  29441. this._isLoaded = false;
  29442. this._isReadyToPlay = false;
  29443. this.isPlaying = false;
  29444. this.isPaused = false;
  29445. this._isDirectional = false;
  29446. // Used if you'd like to create a directional sound.
  29447. // If not set, the sound will be omnidirectional
  29448. this._coneInnerAngle = 360;
  29449. this._coneOuterAngle = 360;
  29450. this._coneOuterGain = 0;
  29451. this._isOutputConnected = false;
  29452. this.name = name;
  29453. this._scene = scene;
  29454. this._readyToPlayCallback = readyToPlayCallback;
  29455. // Default custom attenuation function is a linear attenuation
  29456. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29457. if (currentDistance < maxDistance) {
  29458. return currentVolume * (1 - currentDistance / maxDistance);
  29459. }
  29460. else {
  29461. return 0;
  29462. }
  29463. };
  29464. if (options) {
  29465. this.autoplay = options.autoplay || false;
  29466. this.loop = options.loop || false;
  29467. // if volume === 0, we need another way to check this option
  29468. if (options.volume !== undefined) {
  29469. this._volume = options.volume;
  29470. }
  29471. this.spatialSound = options.spatialSound || false;
  29472. this.maxDistance = options.maxDistance || 100;
  29473. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29474. this.rolloffFactor = options.rolloffFactor || 1;
  29475. this.refDistance = options.refDistance || 1;
  29476. this.distanceModel = options.distanceModel || "linear";
  29477. this._playbackRate = options.playbackRate || 1;
  29478. this._streaming = options.streaming || false;
  29479. }
  29480. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29481. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29482. this._soundGain.gain.value = this._volume;
  29483. this._inputAudioNode = this._soundGain;
  29484. this._ouputAudioNode = this._soundGain;
  29485. if (this.spatialSound) {
  29486. this._createSpatialParameters();
  29487. }
  29488. this._scene.mainSoundTrack.AddSound(this);
  29489. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29490. if (urlOrArrayBuffer) {
  29491. // If it's an URL
  29492. if (typeof (urlOrArrayBuffer) === "string") {
  29493. // Loading sound using XHR2
  29494. if (!this._streaming) {
  29495. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  29496. }
  29497. else {
  29498. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  29499. this._htmlAudioElement.controls = false;
  29500. this._htmlAudioElement.loop = this.loop;
  29501. this._htmlAudioElement.crossOrigin = "anonymous";
  29502. this._htmlAudioElement.preload = "auto";
  29503. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  29504. _this._isReadyToPlay = true;
  29505. if (_this.autoplay) {
  29506. _this.play();
  29507. }
  29508. if (_this._readyToPlayCallback) {
  29509. _this._readyToPlayCallback();
  29510. }
  29511. });
  29512. document.body.appendChild(this._htmlAudioElement);
  29513. }
  29514. }
  29515. else {
  29516. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29517. if (urlOrArrayBuffer.byteLength > 0) {
  29518. this._soundLoaded(urlOrArrayBuffer);
  29519. }
  29520. }
  29521. else {
  29522. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29523. }
  29524. }
  29525. }
  29526. }
  29527. else {
  29528. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29529. this._scene.mainSoundTrack.AddSound(this);
  29530. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29531. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29532. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29533. }
  29534. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29535. if (this._readyToPlayCallback) {
  29536. window.setTimeout(function () {
  29537. _this._readyToPlayCallback();
  29538. }, 1000);
  29539. }
  29540. }
  29541. }
  29542. Sound.prototype.dispose = function () {
  29543. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29544. if (this.isPlaying) {
  29545. this.stop();
  29546. }
  29547. this._isReadyToPlay = false;
  29548. if (this.soundTrackId === -1) {
  29549. this._scene.mainSoundTrack.RemoveSound(this);
  29550. }
  29551. else {
  29552. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29553. }
  29554. if (this._soundGain) {
  29555. this._soundGain.disconnect();
  29556. this._soundGain = null;
  29557. }
  29558. if (this._soundPanner) {
  29559. this._soundPanner.disconnect();
  29560. this._soundPanner = null;
  29561. }
  29562. if (this._soundSource) {
  29563. this._soundSource.disconnect();
  29564. this._soundSource = null;
  29565. }
  29566. this._audioBuffer = null;
  29567. if (this._htmlAudioElement) {
  29568. this._htmlAudioElement.pause();
  29569. this._htmlAudioElement.src = "";
  29570. document.body.removeChild(this._htmlAudioElement);
  29571. }
  29572. if (this._connectedMesh) {
  29573. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29574. this._connectedMesh = null;
  29575. }
  29576. }
  29577. };
  29578. Sound.prototype._soundLoaded = function (audioData) {
  29579. var _this = this;
  29580. this._isLoaded = true;
  29581. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29582. _this._audioBuffer = buffer;
  29583. _this._isReadyToPlay = true;
  29584. if (_this.autoplay) {
  29585. _this.play();
  29586. }
  29587. if (_this._readyToPlayCallback) {
  29588. _this._readyToPlayCallback();
  29589. }
  29590. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  29591. };
  29592. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29593. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29594. this._audioBuffer = audioBuffer;
  29595. this._isReadyToPlay = true;
  29596. }
  29597. };
  29598. Sound.prototype.updateOptions = function (options) {
  29599. if (options) {
  29600. this.loop = options.loop || this.loop;
  29601. this.maxDistance = options.maxDistance || this.maxDistance;
  29602. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29603. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29604. this.refDistance = options.refDistance || this.refDistance;
  29605. this.distanceModel = options.distanceModel || this.distanceModel;
  29606. this._playbackRate = options.playbackRate || this._playbackRate;
  29607. this._updateSpatialParameters();
  29608. if (this.isPlaying) {
  29609. if (this._streaming) {
  29610. this._htmlAudioElement.playbackRate = this._playbackRate;
  29611. }
  29612. else {
  29613. this._soundSource.playbackRate.value = this._playbackRate;
  29614. }
  29615. }
  29616. }
  29617. };
  29618. Sound.prototype._createSpatialParameters = function () {
  29619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29620. if (this._scene.headphone) {
  29621. this._panningModel = "HRTF";
  29622. }
  29623. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29624. this._updateSpatialParameters();
  29625. this._soundPanner.connect(this._ouputAudioNode);
  29626. this._inputAudioNode = this._soundPanner;
  29627. }
  29628. };
  29629. Sound.prototype._updateSpatialParameters = function () {
  29630. if (this.spatialSound) {
  29631. if (this.useCustomAttenuation) {
  29632. // Tricks to disable in a way embedded Web Audio attenuation
  29633. this._soundPanner.distanceModel = "linear";
  29634. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29635. this._soundPanner.refDistance = 1;
  29636. this._soundPanner.rolloffFactor = 1;
  29637. this._soundPanner.panningModel = this._panningModel;
  29638. }
  29639. else {
  29640. this._soundPanner.distanceModel = this.distanceModel;
  29641. this._soundPanner.maxDistance = this.maxDistance;
  29642. this._soundPanner.refDistance = this.refDistance;
  29643. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29644. this._soundPanner.panningModel = this._panningModel;
  29645. }
  29646. }
  29647. };
  29648. Sound.prototype.switchPanningModelToHRTF = function () {
  29649. this._panningModel = "HRTF";
  29650. this._switchPanningModel();
  29651. };
  29652. Sound.prototype.switchPanningModelToEqualPower = function () {
  29653. this._panningModel = "equalpower";
  29654. this._switchPanningModel();
  29655. };
  29656. Sound.prototype._switchPanningModel = function () {
  29657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29658. this._soundPanner.panningModel = this._panningModel;
  29659. }
  29660. };
  29661. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29663. if (this._isOutputConnected) {
  29664. this._ouputAudioNode.disconnect();
  29665. }
  29666. this._ouputAudioNode.connect(soundTrackAudioNode);
  29667. this._isOutputConnected = true;
  29668. }
  29669. };
  29670. /**
  29671. * Transform this sound into a directional source
  29672. * @param coneInnerAngle Size of the inner cone in degree
  29673. * @param coneOuterAngle Size of the outer cone in degree
  29674. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29675. */
  29676. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29677. if (coneOuterAngle < coneInnerAngle) {
  29678. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29679. return;
  29680. }
  29681. this._coneInnerAngle = coneInnerAngle;
  29682. this._coneOuterAngle = coneOuterAngle;
  29683. this._coneOuterGain = coneOuterGain;
  29684. this._isDirectional = true;
  29685. if (this.isPlaying && this.loop) {
  29686. this.stop();
  29687. this.play();
  29688. }
  29689. };
  29690. Sound.prototype.setPosition = function (newPosition) {
  29691. this._position = newPosition;
  29692. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29693. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29694. }
  29695. };
  29696. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29697. this._localDirection = newLocalDirection;
  29698. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29699. this._updateDirection();
  29700. }
  29701. };
  29702. Sound.prototype._updateDirection = function () {
  29703. var mat = this._connectedMesh.getWorldMatrix();
  29704. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29705. direction.normalize();
  29706. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29707. };
  29708. Sound.prototype.updateDistanceFromListener = function () {
  29709. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29710. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29711. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29712. }
  29713. };
  29714. Sound.prototype.setAttenuationFunction = function (callback) {
  29715. this._customAttenuationFunction = callback;
  29716. };
  29717. /**
  29718. * Play the sound
  29719. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29720. */
  29721. Sound.prototype.play = function (time) {
  29722. var _this = this;
  29723. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29724. try {
  29725. if (this._startOffset < 0) {
  29726. time = -this._startOffset;
  29727. this._startOffset = 0;
  29728. }
  29729. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29730. if (!this._soundSource || !this._streamingSource) {
  29731. if (this.spatialSound) {
  29732. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29733. if (this._isDirectional) {
  29734. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29735. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29736. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29737. if (this._connectedMesh) {
  29738. this._updateDirection();
  29739. }
  29740. else {
  29741. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29742. }
  29743. }
  29744. }
  29745. }
  29746. if (this._streaming) {
  29747. if (!this._streamingSource) {
  29748. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  29749. this._htmlAudioElement.onended = function () { _this._onended(); };
  29750. this._htmlAudioElement.playbackRate = this._playbackRate;
  29751. }
  29752. this._streamingSource.disconnect();
  29753. this._streamingSource.connect(this._inputAudioNode);
  29754. this._htmlAudioElement.play();
  29755. }
  29756. else {
  29757. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29758. this._soundSource.buffer = this._audioBuffer;
  29759. this._soundSource.connect(this._inputAudioNode);
  29760. this._soundSource.loop = this.loop;
  29761. this._soundSource.playbackRate.value = this._playbackRate;
  29762. this._soundSource.onended = function () { _this._onended(); };
  29763. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29764. }
  29765. this._startTime = startTime;
  29766. this.isPlaying = true;
  29767. this.isPaused = false;
  29768. }
  29769. catch (ex) {
  29770. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29771. }
  29772. }
  29773. };
  29774. Sound.prototype._onended = function () {
  29775. this.isPlaying = false;
  29776. if (this.onended) {
  29777. this.onended();
  29778. }
  29779. };
  29780. /**
  29781. * Stop the sound
  29782. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29783. */
  29784. Sound.prototype.stop = function (time) {
  29785. if (this.isPlaying) {
  29786. if (this._streaming) {
  29787. this._htmlAudioElement.pause();
  29788. // Test needed for Firefox or it will generate an Invalid State Error
  29789. if (this._htmlAudioElement.currentTime > 0) {
  29790. this._htmlAudioElement.currentTime = 0;
  29791. }
  29792. }
  29793. else {
  29794. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29795. this._soundSource.stop(stopTime);
  29796. if (!this.isPaused) {
  29797. this._startOffset = 0;
  29798. }
  29799. }
  29800. this.isPlaying = false;
  29801. }
  29802. };
  29803. Sound.prototype.pause = function () {
  29804. if (this.isPlaying) {
  29805. this.isPaused = true;
  29806. if (this._streaming) {
  29807. this._htmlAudioElement.pause();
  29808. }
  29809. else {
  29810. this.stop(0);
  29811. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29812. }
  29813. }
  29814. };
  29815. Sound.prototype.setVolume = function (newVolume, time) {
  29816. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29817. if (time) {
  29818. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  29819. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29820. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  29821. }
  29822. else {
  29823. this._soundGain.gain.value = newVolume;
  29824. }
  29825. }
  29826. this._volume = newVolume;
  29827. };
  29828. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29829. this._playbackRate = newPlaybackRate;
  29830. if (this.isPlaying) {
  29831. if (this._streaming) {
  29832. this._htmlAudioElement.playbackRate = this._playbackRate;
  29833. }
  29834. else {
  29835. this._soundSource.playbackRate.value = this._playbackRate;
  29836. }
  29837. }
  29838. };
  29839. Sound.prototype.getVolume = function () {
  29840. return this._volume;
  29841. };
  29842. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29843. var _this = this;
  29844. if (this._connectedMesh) {
  29845. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29846. this._registerFunc = null;
  29847. }
  29848. this._connectedMesh = meshToConnectTo;
  29849. if (!this.spatialSound) {
  29850. this.spatialSound = true;
  29851. this._createSpatialParameters();
  29852. if (this.isPlaying && this.loop) {
  29853. this.stop();
  29854. this.play();
  29855. }
  29856. }
  29857. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29858. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29859. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29860. };
  29861. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29862. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29863. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29864. this._updateDirection();
  29865. }
  29866. };
  29867. Sound.prototype.clone = function () {
  29868. var _this = this;
  29869. if (!this._streaming) {
  29870. var setBufferAndRun = function () {
  29871. if (_this._isReadyToPlay) {
  29872. clonedSound._audioBuffer = _this.getAudioBuffer();
  29873. clonedSound._isReadyToPlay = true;
  29874. if (clonedSound.autoplay) {
  29875. clonedSound.play();
  29876. }
  29877. }
  29878. else {
  29879. window.setTimeout(setBufferAndRun, 300);
  29880. }
  29881. };
  29882. var currentOptions = {
  29883. autoplay: this.autoplay, loop: this.loop,
  29884. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  29885. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  29886. refDistance: this.refDistance, distanceModel: this.distanceModel
  29887. };
  29888. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  29889. if (this.useCustomAttenuation) {
  29890. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  29891. }
  29892. clonedSound.setPosition(this._position);
  29893. clonedSound.setPlaybackRate(this._playbackRate);
  29894. setBufferAndRun();
  29895. return clonedSound;
  29896. }
  29897. else {
  29898. return null;
  29899. }
  29900. };
  29901. Sound.prototype.getAudioBuffer = function () {
  29902. return this._audioBuffer;
  29903. };
  29904. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  29905. var soundName = parsedSound.name;
  29906. var soundUrl;
  29907. if (parsedSound.url) {
  29908. soundUrl = rootUrl + parsedSound.url;
  29909. }
  29910. else {
  29911. soundUrl = rootUrl + soundName;
  29912. }
  29913. var options = {
  29914. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  29915. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  29916. rolloffFactor: parsedSound.rolloffFactor,
  29917. refDistance: parsedSound.refDistance,
  29918. distanceModel: parsedSound.distanceModel,
  29919. playbackRate: parsedSound.playbackRate
  29920. };
  29921. var newSound;
  29922. if (!sourceSound) {
  29923. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  29924. scene._addPendingData(newSound);
  29925. }
  29926. else {
  29927. var setBufferAndRun = function () {
  29928. if (sourceSound._isReadyToPlay) {
  29929. newSound._audioBuffer = sourceSound.getAudioBuffer();
  29930. newSound._isReadyToPlay = true;
  29931. if (newSound.autoplay) {
  29932. newSound.play();
  29933. }
  29934. }
  29935. else {
  29936. window.setTimeout(setBufferAndRun, 300);
  29937. }
  29938. };
  29939. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  29940. setBufferAndRun();
  29941. }
  29942. if (parsedSound.position) {
  29943. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  29944. newSound.setPosition(soundPosition);
  29945. }
  29946. if (parsedSound.isDirectional) {
  29947. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  29948. if (parsedSound.localDirectionToMesh) {
  29949. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  29950. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  29951. }
  29952. }
  29953. if (parsedSound.connectedMeshId) {
  29954. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  29955. if (connectedMesh) {
  29956. newSound.attachToMesh(connectedMesh);
  29957. }
  29958. }
  29959. return newSound;
  29960. };
  29961. return Sound;
  29962. })();
  29963. BABYLON.Sound = Sound;
  29964. })(BABYLON || (BABYLON = {}));
  29965. var BABYLON;
  29966. (function (BABYLON) {
  29967. var SoundTrack = (function () {
  29968. function SoundTrack(scene, options) {
  29969. this.id = -1;
  29970. this._isMainTrack = false;
  29971. this._isInitialized = false;
  29972. this._scene = scene;
  29973. this.soundCollection = new Array();
  29974. this._options = options;
  29975. if (!this._isMainTrack) {
  29976. this._scene.soundTracks.push(this);
  29977. this.id = this._scene.soundTracks.length - 1;
  29978. }
  29979. }
  29980. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  29981. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29982. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  29983. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  29984. if (this._options) {
  29985. if (this._options.volume) {
  29986. this._outputAudioNode.gain.value = this._options.volume;
  29987. }
  29988. if (this._options.mainTrack) {
  29989. this._isMainTrack = this._options.mainTrack;
  29990. }
  29991. }
  29992. this._isInitialized = true;
  29993. }
  29994. };
  29995. SoundTrack.prototype.dispose = function () {
  29996. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29997. if (this._connectedAnalyser) {
  29998. this._connectedAnalyser.stopDebugCanvas();
  29999. }
  30000. while (this.soundCollection.length) {
  30001. this.soundCollection[0].dispose();
  30002. }
  30003. if (this._outputAudioNode) {
  30004. this._outputAudioNode.disconnect();
  30005. }
  30006. this._outputAudioNode = null;
  30007. }
  30008. };
  30009. SoundTrack.prototype.AddSound = function (sound) {
  30010. if (!this._isInitialized) {
  30011. this._initializeSoundTrackAudioGraph();
  30012. }
  30013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30014. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30015. }
  30016. if (sound.soundTrackId) {
  30017. if (sound.soundTrackId === -1) {
  30018. this._scene.mainSoundTrack.RemoveSound(sound);
  30019. }
  30020. else {
  30021. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30022. }
  30023. }
  30024. this.soundCollection.push(sound);
  30025. sound.soundTrackId = this.id;
  30026. };
  30027. SoundTrack.prototype.RemoveSound = function (sound) {
  30028. var index = this.soundCollection.indexOf(sound);
  30029. if (index !== -1) {
  30030. this.soundCollection.splice(index, 1);
  30031. }
  30032. };
  30033. SoundTrack.prototype.setVolume = function (newVolume) {
  30034. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30035. this._outputAudioNode.gain.value = newVolume;
  30036. }
  30037. };
  30038. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30039. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30040. for (var i = 0; i < this.soundCollection.length; i++) {
  30041. this.soundCollection[i].switchPanningModelToHRTF();
  30042. }
  30043. }
  30044. };
  30045. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30047. for (var i = 0; i < this.soundCollection.length; i++) {
  30048. this.soundCollection[i].switchPanningModelToEqualPower();
  30049. }
  30050. }
  30051. };
  30052. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30053. if (this._connectedAnalyser) {
  30054. this._connectedAnalyser.stopDebugCanvas();
  30055. }
  30056. this._connectedAnalyser = analyser;
  30057. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30058. this._outputAudioNode.disconnect();
  30059. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  30060. }
  30061. };
  30062. return SoundTrack;
  30063. })();
  30064. BABYLON.SoundTrack = SoundTrack;
  30065. })(BABYLON || (BABYLON = {}));
  30066. var BABYLON;
  30067. (function (BABYLON) {
  30068. var SIMDVector3 = (function () {
  30069. function SIMDVector3() {
  30070. }
  30071. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  30072. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  30073. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30074. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30075. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30076. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30077. 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));
  30078. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30079. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30080. };
  30081. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  30082. var v0 = SIMD.float32x4.splat(x);
  30083. var v1 = SIMD.float32x4.splat(y);
  30084. var v2 = SIMD.float32x4.splat(z);
  30085. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30086. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30087. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30088. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30089. 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));
  30090. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30091. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30092. };
  30093. return SIMDVector3;
  30094. })();
  30095. BABYLON.SIMDVector3 = SIMDVector3;
  30096. var SIMDMatrix = (function () {
  30097. function SIMDMatrix() {
  30098. }
  30099. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  30100. if (offset === void 0) { offset = 0; }
  30101. var tm = this.m;
  30102. var om = other.m;
  30103. var om0 = SIMD.float32x4.load(om, 0);
  30104. var om1 = SIMD.float32x4.load(om, 4);
  30105. var om2 = SIMD.float32x4.load(om, 8);
  30106. var om3 = SIMD.float32x4.load(om, 12);
  30107. var tm0 = SIMD.float32x4.load(tm, 0);
  30108. 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)))));
  30109. var tm1 = SIMD.float32x4.load(tm, 4);
  30110. 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)))));
  30111. var tm2 = SIMD.float32x4.load(tm, 8);
  30112. 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)))));
  30113. var tm3 = SIMD.float32x4.load(tm, 12);
  30114. 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)))));
  30115. };
  30116. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  30117. var src = this.m;
  30118. var dest = other.m;
  30119. var row0, row1, row2, row3;
  30120. var tmp1;
  30121. var minor0, minor1, minor2, minor3;
  30122. var det;
  30123. // Load the 4 rows
  30124. var src0 = SIMD.float32x4.load(src, 0);
  30125. var src1 = SIMD.float32x4.load(src, 4);
  30126. var src2 = SIMD.float32x4.load(src, 8);
  30127. var src3 = SIMD.float32x4.load(src, 12);
  30128. // Transpose the source matrix. Sort of. Not a true transpose operation
  30129. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30130. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30131. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  30132. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  30133. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30134. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30135. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  30136. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  30137. // This is a true transposition, but it will lead to an incorrect result
  30138. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30139. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30140. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30141. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30142. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30143. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30144. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30145. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30146. // ----
  30147. tmp1 = SIMD.float32x4.mul(row2, row3);
  30148. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30149. minor0 = SIMD.float32x4.mul(row1, tmp1);
  30150. minor1 = SIMD.float32x4.mul(row0, tmp1);
  30151. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30152. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  30153. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  30154. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  30155. // ----
  30156. tmp1 = SIMD.float32x4.mul(row1, row2);
  30157. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30158. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  30159. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30160. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30161. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30162. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30163. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30164. // ----
  30165. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30166. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30167. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30168. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30169. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30170. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30171. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30172. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30173. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30174. // ----
  30175. tmp1 = SIMD.float32x4.mul(row0, row1);
  30176. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30177. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30178. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30179. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30180. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30181. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30182. // ----
  30183. tmp1 = SIMD.float32x4.mul(row0, row3);
  30184. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30185. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30186. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30187. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30188. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30189. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30190. // ----
  30191. tmp1 = SIMD.float32x4.mul(row0, row2);
  30192. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30193. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30194. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30195. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30196. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30197. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30198. // Compute determinant
  30199. det = SIMD.float32x4.mul(row0, minor0);
  30200. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30201. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30202. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30203. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30204. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30205. // These shuffles aren't necessary if the faulty transposition is done
  30206. // up at the top of this function.
  30207. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30208. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30209. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30210. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30211. // Compute final values by multiplying with 1/det
  30212. minor0 = SIMD.float32x4.mul(det, minor0);
  30213. minor1 = SIMD.float32x4.mul(det, minor1);
  30214. minor2 = SIMD.float32x4.mul(det, minor2);
  30215. minor3 = SIMD.float32x4.mul(det, minor3);
  30216. SIMD.float32x4.store(dest, 0, minor0);
  30217. SIMD.float32x4.store(dest, 4, minor1);
  30218. SIMD.float32x4.store(dest, 8, minor2);
  30219. SIMD.float32x4.store(dest, 12, minor3);
  30220. return this;
  30221. };
  30222. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30223. var out = result.m;
  30224. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30225. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30226. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30227. // cc.kmVec3Subtract(f, pCenter, pEye);
  30228. var f = SIMD.float32x4.sub(center, eye);
  30229. // cc.kmVec3Normalize(f, f);
  30230. var tmp = SIMD.float32x4.mul(f, f);
  30231. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30232. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30233. // cc.kmVec3Assign(up, pUp);
  30234. // cc.kmVec3Normalize(up, up);
  30235. tmp = SIMD.float32x4.mul(up, up);
  30236. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30237. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30238. // cc.kmVec3Cross(s, f, up);
  30239. 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)));
  30240. // cc.kmVec3Normalize(s, s);
  30241. tmp = SIMD.float32x4.mul(s, s);
  30242. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30243. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30244. // cc.kmVec3Cross(u, s, f);
  30245. 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)));
  30246. // cc.kmVec3Normalize(s, s);
  30247. tmp = SIMD.float32x4.mul(s, s);
  30248. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30249. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30250. var zero = SIMD.float32x4.splat(0.0);
  30251. s = SIMD.float32x4.neg(s);
  30252. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30253. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30254. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30255. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30256. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30257. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30258. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30259. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30260. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30261. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30262. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30263. var b3 = SIMD.float32x4.neg(eye);
  30264. b3 = SIMD.float32x4.withW(b3, 1.0);
  30265. 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)))));
  30266. 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)))));
  30267. 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)))));
  30268. 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)))));
  30269. };
  30270. return SIMDMatrix;
  30271. })();
  30272. BABYLON.SIMDMatrix = SIMDMatrix;
  30273. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30274. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30275. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30276. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30277. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30278. var SIMDHelper = (function () {
  30279. function SIMDHelper() {
  30280. }
  30281. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30282. get: function () {
  30283. return SIMDHelper._isEnabled;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. SIMDHelper.DisableSIMD = function () {
  30289. // Replace functions
  30290. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30291. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30292. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30293. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30295. SIMDHelper._isEnabled = false;
  30296. };
  30297. SIMDHelper.EnableSIMD = function () {
  30298. if (window.SIMD === undefined) {
  30299. return;
  30300. }
  30301. // Replace functions
  30302. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30303. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30304. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30305. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30306. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30307. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30308. get: function () { return this._data[0]; },
  30309. set: function (value) {
  30310. if (!this._data) {
  30311. this._data = new Float32Array(3);
  30312. }
  30313. this._data[0] = value;
  30314. }
  30315. });
  30316. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30317. get: function () { return this._data[1]; },
  30318. set: function (value) {
  30319. this._data[1] = value;
  30320. }
  30321. });
  30322. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30323. get: function () { return this._data[2]; },
  30324. set: function (value) {
  30325. this._data[2] = value;
  30326. }
  30327. });
  30328. SIMDHelper._isEnabled = true;
  30329. };
  30330. SIMDHelper._isEnabled = false;
  30331. return SIMDHelper;
  30332. })();
  30333. BABYLON.SIMDHelper = SIMDHelper;
  30334. })(BABYLON || (BABYLON = {}));
  30335. var BABYLON;
  30336. (function (BABYLON) {
  30337. var ShaderMaterial = (function (_super) {
  30338. __extends(ShaderMaterial, _super);
  30339. function ShaderMaterial(name, scene, shaderPath, options) {
  30340. _super.call(this, name, scene);
  30341. this._textures = {};
  30342. this._floats = {};
  30343. this._floatsArrays = {};
  30344. this._colors3 = {};
  30345. this._colors4 = {};
  30346. this._vectors2 = {};
  30347. this._vectors3 = {};
  30348. this._vectors4 = {};
  30349. this._matrices = {};
  30350. this._matrices3x3 = {};
  30351. this._matrices2x2 = {};
  30352. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30353. this._shaderPath = shaderPath;
  30354. options.needAlphaBlending = options.needAlphaBlending || false;
  30355. options.needAlphaTesting = options.needAlphaTesting || false;
  30356. options.attributes = options.attributes || ["position", "normal", "uv"];
  30357. options.uniforms = options.uniforms || ["worldViewProjection"];
  30358. options.samplers = options.samplers || [];
  30359. options.defines = options.defines || [];
  30360. this._options = options;
  30361. }
  30362. ShaderMaterial.prototype.needAlphaBlending = function () {
  30363. return this._options.needAlphaBlending;
  30364. };
  30365. ShaderMaterial.prototype.needAlphaTesting = function () {
  30366. return this._options.needAlphaTesting;
  30367. };
  30368. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30369. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30370. this._options.uniforms.push(uniformName);
  30371. }
  30372. };
  30373. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30374. if (this._options.samplers.indexOf(name) === -1) {
  30375. this._options.samplers.push(name);
  30376. }
  30377. this._textures[name] = texture;
  30378. return this;
  30379. };
  30380. ShaderMaterial.prototype.setFloat = function (name, value) {
  30381. this._checkUniform(name);
  30382. this._floats[name] = value;
  30383. return this;
  30384. };
  30385. ShaderMaterial.prototype.setFloats = function (name, value) {
  30386. this._checkUniform(name);
  30387. this._floatsArrays[name] = value;
  30388. return this;
  30389. };
  30390. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30391. this._checkUniform(name);
  30392. this._colors3[name] = value;
  30393. return this;
  30394. };
  30395. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30396. this._checkUniform(name);
  30397. this._colors4[name] = value;
  30398. return this;
  30399. };
  30400. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30401. this._checkUniform(name);
  30402. this._vectors2[name] = value;
  30403. return this;
  30404. };
  30405. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30406. this._checkUniform(name);
  30407. this._vectors3[name] = value;
  30408. return this;
  30409. };
  30410. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30411. this._checkUniform(name);
  30412. this._vectors4[name] = value;
  30413. return this;
  30414. };
  30415. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30416. this._checkUniform(name);
  30417. this._matrices[name] = value;
  30418. return this;
  30419. };
  30420. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30421. this._checkUniform(name);
  30422. this._matrices3x3[name] = value;
  30423. return this;
  30424. };
  30425. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30426. this._checkUniform(name);
  30427. this._matrices2x2[name] = value;
  30428. return this;
  30429. };
  30430. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30431. var scene = this.getScene();
  30432. var engine = scene.getEngine();
  30433. if (!this.checkReadyOnEveryCall) {
  30434. if (this._renderId === scene.getRenderId()) {
  30435. return true;
  30436. }
  30437. }
  30438. // Instances
  30439. var defines = [];
  30440. var fallbacks = new BABYLON.EffectFallbacks();
  30441. if (useInstances) {
  30442. defines.push("#define INSTANCES");
  30443. }
  30444. for (var index = 0; index < this._options.defines.length; index++) {
  30445. defines.push(this._options.defines[index]);
  30446. }
  30447. // Bones
  30448. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30449. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30450. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30451. fallbacks.addCPUSkinningFallback(0, mesh);
  30452. }
  30453. // Alpha test
  30454. if (engine.getAlphaTesting()) {
  30455. defines.push("#define ALPHATEST");
  30456. }
  30457. var previousEffect = this._effect;
  30458. var join = defines.join("\n");
  30459. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30460. if (!this._effect.isReady()) {
  30461. return false;
  30462. }
  30463. if (previousEffect !== this._effect) {
  30464. scene.resetCachedMaterial();
  30465. }
  30466. this._renderId = scene.getRenderId();
  30467. return true;
  30468. };
  30469. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30470. var scene = this.getScene();
  30471. if (this._options.uniforms.indexOf("world") !== -1) {
  30472. this._effect.setMatrix("world", world);
  30473. }
  30474. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30475. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30476. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30477. }
  30478. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30479. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30480. }
  30481. };
  30482. ShaderMaterial.prototype.bind = function (world, mesh) {
  30483. // Std values
  30484. this.bindOnlyWorldMatrix(world);
  30485. if (this.getScene().getCachedMaterial() !== this) {
  30486. if (this._options.uniforms.indexOf("view") !== -1) {
  30487. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30488. }
  30489. if (this._options.uniforms.indexOf("projection") !== -1) {
  30490. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30491. }
  30492. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30493. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30494. }
  30495. // Bones
  30496. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30497. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30498. }
  30499. // Texture
  30500. for (var name in this._textures) {
  30501. this._effect.setTexture(name, this._textures[name]);
  30502. }
  30503. // Float
  30504. for (name in this._floats) {
  30505. this._effect.setFloat(name, this._floats[name]);
  30506. }
  30507. // Float s
  30508. for (name in this._floatsArrays) {
  30509. this._effect.setArray(name, this._floatsArrays[name]);
  30510. }
  30511. // Color3
  30512. for (name in this._colors3) {
  30513. this._effect.setColor3(name, this._colors3[name]);
  30514. }
  30515. // Color4
  30516. for (name in this._colors4) {
  30517. var color = this._colors4[name];
  30518. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30519. }
  30520. // Vector2
  30521. for (name in this._vectors2) {
  30522. this._effect.setVector2(name, this._vectors2[name]);
  30523. }
  30524. // Vector3
  30525. for (name in this._vectors3) {
  30526. this._effect.setVector3(name, this._vectors3[name]);
  30527. }
  30528. // Vector4
  30529. for (name in this._vectors4) {
  30530. this._effect.setVector4(name, this._vectors4[name]);
  30531. }
  30532. // Matrix
  30533. for (name in this._matrices) {
  30534. this._effect.setMatrix(name, this._matrices[name]);
  30535. }
  30536. // Matrix 3x3
  30537. for (name in this._matrices3x3) {
  30538. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30539. }
  30540. // Matrix 2x2
  30541. for (name in this._matrices2x2) {
  30542. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30543. }
  30544. }
  30545. _super.prototype.bind.call(this, world, mesh);
  30546. };
  30547. ShaderMaterial.prototype.clone = function (name) {
  30548. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30549. return newShaderMaterial;
  30550. };
  30551. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30552. for (var name in this._textures) {
  30553. this._textures[name].dispose();
  30554. }
  30555. this._textures = {};
  30556. _super.prototype.dispose.call(this, forceDisposeEffect);
  30557. };
  30558. ShaderMaterial.prototype.serialize = function () {
  30559. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30560. serializationObject.customType = "BABYLON.ShaderMaterial";
  30561. serializationObject.options = this._options;
  30562. serializationObject.shaderPath = this._shaderPath;
  30563. // Texture
  30564. serializationObject.textures = {};
  30565. for (var name in this._textures) {
  30566. serializationObject.textures[name] = this._textures[name].serialize();
  30567. }
  30568. // Float
  30569. serializationObject.floats = {};
  30570. for (name in this._floats) {
  30571. serializationObject.floats[name] = this._floats[name];
  30572. }
  30573. // Float s
  30574. serializationObject.floatArrays = {};
  30575. for (name in this._floatsArrays) {
  30576. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30577. }
  30578. // Color3
  30579. serializationObject.colors3 = {};
  30580. for (name in this._colors3) {
  30581. serializationObject.colors3[name] = this._colors3[name].asArray();
  30582. }
  30583. // Color4
  30584. serializationObject.colors4 = {};
  30585. for (name in this._colors4) {
  30586. serializationObject.colors4[name] = this._colors4[name].asArray();
  30587. }
  30588. // Vector2
  30589. serializationObject.vectors2 = {};
  30590. for (name in this._vectors2) {
  30591. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30592. }
  30593. // Vector3
  30594. serializationObject.vectors3 = {};
  30595. for (name in this._vectors3) {
  30596. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30597. }
  30598. // Vector4
  30599. serializationObject.vectors4 = {};
  30600. for (name in this._vectors4) {
  30601. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30602. }
  30603. // Matrix
  30604. serializationObject.matrices = {};
  30605. for (name in this._matrices) {
  30606. serializationObject.matrices[name] = this._matrices[name].asArray();
  30607. }
  30608. // Matrix 3x3
  30609. serializationObject.matrices3x3 = {};
  30610. for (name in this._matrices3x3) {
  30611. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30612. }
  30613. // Matrix 2x2
  30614. serializationObject.matrices2x2 = {};
  30615. for (name in this._matrices2x2) {
  30616. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30617. }
  30618. return serializationObject;
  30619. };
  30620. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30621. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30622. // Texture
  30623. for (var name in source.textures) {
  30624. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30625. }
  30626. // Float
  30627. for (name in source.floats) {
  30628. material.setFloat(name, source.floats[name]);
  30629. }
  30630. // Float s
  30631. for (name in source.floatsArrays) {
  30632. material.setFloats(name, source.floatsArrays[name]);
  30633. }
  30634. // Color3
  30635. for (name in source.colors3) {
  30636. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30637. }
  30638. // Color4
  30639. for (name in source.colors4) {
  30640. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30641. }
  30642. // Vector2
  30643. for (name in source.vectors2) {
  30644. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30645. }
  30646. // Vector3
  30647. for (name in source.vectors3) {
  30648. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30649. }
  30650. // Vector4
  30651. for (name in source.vectors4) {
  30652. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30653. }
  30654. // Matrix
  30655. for (name in source.matrices) {
  30656. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30657. }
  30658. // Matrix 3x3
  30659. for (name in source.matrices3x3) {
  30660. material.setMatrix3x3(name, source.matrices3x3[name]);
  30661. }
  30662. // Matrix 2x2
  30663. for (name in source.matrices2x2) {
  30664. material.setMatrix2x2(name, source.matrices2x2[name]);
  30665. }
  30666. return material;
  30667. };
  30668. return ShaderMaterial;
  30669. })(BABYLON.Material);
  30670. BABYLON.ShaderMaterial = ShaderMaterial;
  30671. })(BABYLON || (BABYLON = {}));
  30672. var BABYLON;
  30673. (function (BABYLON) {
  30674. var Internals;
  30675. (function (Internals) {
  30676. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30677. // All values and structures referenced from:
  30678. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30679. var DDS_MAGIC = 0x20534444;
  30680. 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;
  30681. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30682. 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;
  30683. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30684. function FourCCToInt32(value) {
  30685. return value.charCodeAt(0) +
  30686. (value.charCodeAt(1) << 8) +
  30687. (value.charCodeAt(2) << 16) +
  30688. (value.charCodeAt(3) << 24);
  30689. }
  30690. function Int32ToFourCC(value) {
  30691. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30692. }
  30693. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30694. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30695. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30696. var headerLengthInt = 31; // The header length in 32 bit ints
  30697. // Offsets into the header array
  30698. var off_magic = 0;
  30699. var off_size = 1;
  30700. var off_flags = 2;
  30701. var off_height = 3;
  30702. var off_width = 4;
  30703. var off_mipmapCount = 7;
  30704. var off_pfFlags = 20;
  30705. var off_pfFourCC = 21;
  30706. var off_RGBbpp = 22;
  30707. var off_RMask = 23;
  30708. var off_GMask = 24;
  30709. var off_BMask = 25;
  30710. var off_AMask = 26;
  30711. var off_caps1 = 27;
  30712. var off_caps2 = 28;
  30713. ;
  30714. var DDSTools = (function () {
  30715. function DDSTools() {
  30716. }
  30717. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30718. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30719. var mipmapCount = 1;
  30720. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30721. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30722. }
  30723. return {
  30724. width: header[off_width],
  30725. height: header[off_height],
  30726. mipmapCount: mipmapCount,
  30727. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30728. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30729. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30730. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30731. };
  30732. };
  30733. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30734. var byteArray = new Uint8Array(dataLength);
  30735. var srcData = new Uint8Array(arrayBuffer);
  30736. var index = 0;
  30737. for (var y = height - 1; y >= 0; y--) {
  30738. for (var x = 0; x < width; x++) {
  30739. var srcPos = dataOffset + (x + y * width) * 4;
  30740. byteArray[index + 2] = srcData[srcPos];
  30741. byteArray[index + 1] = srcData[srcPos + 1];
  30742. byteArray[index] = srcData[srcPos + 2];
  30743. byteArray[index + 3] = srcData[srcPos + 3];
  30744. index += 4;
  30745. }
  30746. }
  30747. return byteArray;
  30748. };
  30749. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30750. var byteArray = new Uint8Array(dataLength);
  30751. var srcData = new Uint8Array(arrayBuffer);
  30752. var index = 0;
  30753. for (var y = height - 1; y >= 0; y--) {
  30754. for (var x = 0; x < width; x++) {
  30755. var srcPos = dataOffset + (x + y * width) * 3;
  30756. byteArray[index + 2] = srcData[srcPos];
  30757. byteArray[index + 1] = srcData[srcPos + 1];
  30758. byteArray[index] = srcData[srcPos + 2];
  30759. index += 3;
  30760. }
  30761. }
  30762. return byteArray;
  30763. };
  30764. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30765. var byteArray = new Uint8Array(dataLength);
  30766. var srcData = new Uint8Array(arrayBuffer);
  30767. var index = 0;
  30768. for (var y = height - 1; y >= 0; y--) {
  30769. for (var x = 0; x < width; x++) {
  30770. var srcPos = dataOffset + (x + y * width);
  30771. byteArray[index] = srcData[srcPos];
  30772. index++;
  30773. }
  30774. }
  30775. return byteArray;
  30776. };
  30777. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30778. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30779. if (header[off_magic] != DDS_MAGIC) {
  30780. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30781. return;
  30782. }
  30783. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30784. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30785. return;
  30786. }
  30787. if (info.isFourCC) {
  30788. fourCC = header[off_pfFourCC];
  30789. switch (fourCC) {
  30790. case FOURCC_DXT1:
  30791. blockBytes = 8;
  30792. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30793. break;
  30794. case FOURCC_DXT3:
  30795. blockBytes = 16;
  30796. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30797. break;
  30798. case FOURCC_DXT5:
  30799. blockBytes = 16;
  30800. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30801. break;
  30802. default:
  30803. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30804. return;
  30805. }
  30806. }
  30807. mipmapCount = 1;
  30808. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30809. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30810. }
  30811. var bpp = header[off_RGBbpp];
  30812. for (var face = 0; face < faces; face++) {
  30813. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30814. width = header[off_width];
  30815. height = header[off_height];
  30816. dataOffset = header[off_size] + 4;
  30817. for (i = 0; i < mipmapCount; ++i) {
  30818. if (info.isRGB) {
  30819. if (bpp === 24) {
  30820. dataLength = width * height * 3;
  30821. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30822. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30823. }
  30824. else {
  30825. dataLength = width * height * 4;
  30826. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30827. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30828. }
  30829. }
  30830. else if (info.isLuminance) {
  30831. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30832. var unpaddedRowSize = width;
  30833. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30834. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30835. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30836. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30837. }
  30838. else {
  30839. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30840. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30841. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30842. }
  30843. dataOffset += dataLength;
  30844. width *= 0.5;
  30845. height *= 0.5;
  30846. width = Math.max(1.0, width);
  30847. height = Math.max(1.0, height);
  30848. }
  30849. }
  30850. };
  30851. return DDSTools;
  30852. })();
  30853. Internals.DDSTools = DDSTools;
  30854. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30855. })(BABYLON || (BABYLON = {}));
  30856. var BABYLON;
  30857. (function (BABYLON) {
  30858. var CannonJSPlugin = (function () {
  30859. function CannonJSPlugin(_useDeltaForWorldStep) {
  30860. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30861. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30862. this._registeredMeshes = [];
  30863. this._physicsMaterials = [];
  30864. this._fixedTimeStep = 1 / 60;
  30865. //private _maxSubSteps : number = 15;
  30866. this.name = "CannonJS";
  30867. this.updateBodyPosition = function (mesh) {
  30868. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30869. var registeredMesh = this._registeredMeshes[index];
  30870. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30871. var body = registeredMesh.body;
  30872. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30873. body.quaternion.copy(mesh.rotationQuaternion);
  30874. if (registeredMesh.deltaRotation) {
  30875. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30876. body.quaternion = body.quaternion.mult(tmpQ);
  30877. }
  30878. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  30879. //calculate the correct body position:
  30880. var rotationQuaternion = mesh.rotationQuaternion;
  30881. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30882. mesh.computeWorldMatrix(true);
  30883. //get original center with no rotation
  30884. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30885. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30886. //rotation is back
  30887. mesh.rotationQuaternion = rotationQuaternion;
  30888. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30889. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30890. mesh.setPivotMatrix(p);
  30891. mesh.computeWorldMatrix(true);
  30892. //calculate the translation
  30893. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30894. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30895. //add it inverted to the delta
  30896. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30897. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30898. mesh.setPivotMatrix(oldPivot);
  30899. mesh.computeWorldMatrix(true);
  30900. }
  30901. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  30902. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  30903. }
  30904. body.position.set(center.x, center.y, center.z);
  30905. return;
  30906. }
  30907. }
  30908. };
  30909. }
  30910. CannonJSPlugin.prototype.initialize = function (iterations) {
  30911. if (iterations === void 0) { iterations = 10; }
  30912. this._world = new CANNON.World();
  30913. this._world.broadphase = new CANNON.NaiveBroadphase();
  30914. this._world.solver.iterations = iterations;
  30915. };
  30916. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30917. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30918. };
  30919. CannonJSPlugin.prototype.runOneStep = function (delta) {
  30920. var _this = this;
  30921. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30922. this._registeredMeshes.forEach(function (registeredMesh) {
  30923. // Body position
  30924. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  30925. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  30926. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  30927. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  30928. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  30929. if (registeredMesh.deltaRotation) {
  30930. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  30931. }
  30932. //is the physics collision callback is set?
  30933. if (registeredMesh.mesh.onPhysicsCollide) {
  30934. if (!registeredMesh.collisionFunction) {
  30935. registeredMesh.collisionFunction = function (e) {
  30936. //find the mesh that collided with the registered mesh
  30937. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  30938. if (_this._registeredMeshes[idx].body == e.body) {
  30939. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  30940. }
  30941. }
  30942. };
  30943. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  30944. }
  30945. }
  30946. else {
  30947. //unregister, in case the function was removed for some reason
  30948. if (registeredMesh.collisionFunction) {
  30949. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  30950. }
  30951. }
  30952. });
  30953. };
  30954. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30955. this._gravity = gravity;
  30956. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  30957. };
  30958. CannonJSPlugin.prototype.getGravity = function () {
  30959. return this._gravity;
  30960. };
  30961. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30962. this.unregisterMesh(mesh);
  30963. if (!mesh.rotationQuaternion) {
  30964. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30965. }
  30966. mesh.computeWorldMatrix(true);
  30967. var shape = this._createShape(mesh, impostor);
  30968. return this._createRigidBodyFromShape(shape, mesh, options);
  30969. };
  30970. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  30971. //get the correct bounding box
  30972. var oldQuaternion = mesh.rotationQuaternion;
  30973. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30974. mesh.computeWorldMatrix(true);
  30975. var returnValue;
  30976. switch (impostor) {
  30977. case BABYLON.PhysicsEngine.SphereImpostor:
  30978. var bbox = mesh.getBoundingInfo().boundingBox;
  30979. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30980. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30981. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30982. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30983. break;
  30984. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30985. case BABYLON.PhysicsEngine.CylinderImpostor:
  30986. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30987. case BABYLON.PhysicsEngine.BoxImpostor:
  30988. bbox = mesh.getBoundingInfo().boundingBox;
  30989. var min = bbox.minimumWorld;
  30990. var max = bbox.maximumWorld;
  30991. var box = max.subtract(min).scale(0.5);
  30992. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30993. break;
  30994. case BABYLON.PhysicsEngine.PlaneImpostor:
  30995. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  30996. returnValue = new CANNON.Plane();
  30997. break;
  30998. case BABYLON.PhysicsEngine.MeshImpostor:
  30999. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31000. var rawFaces = mesh.getIndices();
  31001. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  31002. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  31003. break;
  31004. case BABYLON.PhysicsEngine.HeightmapImpostor:
  31005. returnValue = this._createHeightmap(mesh);
  31006. break;
  31007. }
  31008. mesh.rotationQuaternion = oldQuaternion;
  31009. return returnValue;
  31010. };
  31011. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  31012. var verts = [], faces = [];
  31013. mesh.computeWorldMatrix(true);
  31014. //reuse this variable
  31015. var transformed = BABYLON.Vector3.Zero();
  31016. // Get vertices
  31017. for (var i = 0; i < rawVerts.length; i += 3) {
  31018. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  31019. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  31020. }
  31021. // Get faces
  31022. for (var j = 0; j < rawFaces.length; j += 3) {
  31023. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  31024. }
  31025. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  31026. return shape;
  31027. };
  31028. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  31029. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31030. var matrix = [];
  31031. //For now pointDepth will not be used and will be automatically calculated.
  31032. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  31033. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  31034. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  31035. var elementSize = dim * 2 / arraySize;
  31036. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  31037. for (var i = 0; i < pos.length; i = i + 3) {
  31038. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  31039. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  31040. var y = pos[i + 1] + minY;
  31041. if (!matrix[x]) {
  31042. matrix[x] = [];
  31043. }
  31044. if (!matrix[x][z]) {
  31045. matrix[x][z] = y;
  31046. }
  31047. matrix[x][z] = Math.max(y, matrix[x][z]);
  31048. }
  31049. for (var x = 0; x <= arraySize; ++x) {
  31050. if (!matrix[x]) {
  31051. var loc = 1;
  31052. while (!matrix[(x + loc) % arraySize]) {
  31053. loc++;
  31054. }
  31055. matrix[x] = matrix[(x + loc) % arraySize].slice();
  31056. }
  31057. for (var z = 0; z <= arraySize; ++z) {
  31058. if (!matrix[x][z]) {
  31059. var loc = 1;
  31060. var newValue;
  31061. while (newValue === undefined) {
  31062. newValue = matrix[x][(z + loc++) % arraySize];
  31063. }
  31064. matrix[x][z] = newValue;
  31065. }
  31066. }
  31067. }
  31068. var shape = new CANNON.Heightfield(matrix, {
  31069. elementSize: elementSize
  31070. });
  31071. //For future reference, needed for body transformation
  31072. shape.minY = minY;
  31073. return shape;
  31074. };
  31075. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  31076. var index;
  31077. var mat;
  31078. for (index = 0; index < this._physicsMaterials.length; index++) {
  31079. mat = this._physicsMaterials[index];
  31080. if (mat.friction === friction && mat.restitution === restitution) {
  31081. return mat;
  31082. }
  31083. }
  31084. var currentMat = new CANNON.Material("mat");
  31085. this._physicsMaterials.push(currentMat);
  31086. for (index = 0; index < this._physicsMaterials.length; index++) {
  31087. mat = this._physicsMaterials[index];
  31088. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  31089. this._world.addContactMaterial(contactMaterial);
  31090. }
  31091. return currentMat;
  31092. };
  31093. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  31094. if (!mesh.rotationQuaternion) {
  31095. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  31096. }
  31097. // The delta between the mesh position and the mesh bounding box center
  31098. var bbox = mesh.getBoundingInfo().boundingBox;
  31099. var deltaPosition = mesh.position.subtract(bbox.center);
  31100. var deltaRotation;
  31101. var material = this._addMaterial(options.friction, options.restitution);
  31102. var body = new CANNON.Body({
  31103. mass: options.mass,
  31104. material: material,
  31105. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  31106. });
  31107. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  31108. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31109. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  31110. //-90 DEG in X, precalculated
  31111. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  31112. body.quaternion = body.quaternion.mult(tmpQ);
  31113. //Invert! (Precalculated, 90 deg in X)
  31114. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  31115. }
  31116. //If it is a heightfield, if should be centered.
  31117. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  31118. //calculate the correct body position:
  31119. var rotationQuaternion = mesh.rotationQuaternion;
  31120. mesh.rotationQuaternion = new BABYLON.Quaternion();
  31121. mesh.computeWorldMatrix(true);
  31122. //get original center with no rotation
  31123. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31124. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31125. //rotation is back
  31126. mesh.rotationQuaternion = rotationQuaternion;
  31127. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31128. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31129. mesh.setPivotMatrix(p);
  31130. mesh.computeWorldMatrix(true);
  31131. //calculate the translation
  31132. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31133. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31134. //add it inverted to the delta
  31135. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  31136. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31137. mesh.setPivotMatrix(oldPivot);
  31138. mesh.computeWorldMatrix(true);
  31139. }
  31140. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  31141. deltaPosition = BABYLON.Vector3.Zero();
  31142. }
  31143. //add the shape
  31144. body.addShape(shape);
  31145. this._world.add(body);
  31146. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  31147. return body;
  31148. };
  31149. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  31150. var initialMesh = parts[0].mesh;
  31151. this.unregisterMesh(initialMesh);
  31152. initialMesh.computeWorldMatrix(true);
  31153. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  31154. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  31155. for (var index = 1; index < parts.length; index++) {
  31156. var mesh = parts[index].mesh;
  31157. mesh.computeWorldMatrix(true);
  31158. var shape = this._createShape(mesh, parts[index].impostor);
  31159. var localPosition = mesh.position;
  31160. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  31161. }
  31162. return body;
  31163. };
  31164. CannonJSPlugin.prototype._unbindBody = function (body) {
  31165. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31166. var registeredMesh = this._registeredMeshes[index];
  31167. if (registeredMesh.body === body) {
  31168. this._world.remove(registeredMesh.body);
  31169. registeredMesh.body = null;
  31170. registeredMesh.delta = null;
  31171. registeredMesh.deltaRotation = null;
  31172. }
  31173. }
  31174. };
  31175. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  31176. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31177. var registeredMesh = this._registeredMeshes[index];
  31178. if (registeredMesh.mesh === mesh) {
  31179. // Remove body
  31180. if (registeredMesh.body) {
  31181. this._unbindBody(registeredMesh.body);
  31182. }
  31183. this._registeredMeshes.splice(index, 1);
  31184. return;
  31185. }
  31186. }
  31187. };
  31188. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  31189. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  31190. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  31191. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31192. var registeredMesh = this._registeredMeshes[index];
  31193. if (registeredMesh.mesh === mesh) {
  31194. registeredMesh.body.applyImpulse(impulse, worldPoint);
  31195. return;
  31196. }
  31197. }
  31198. };
  31199. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  31200. var body1 = null, body2 = null;
  31201. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31202. var registeredMesh = this._registeredMeshes[index];
  31203. if (registeredMesh.mesh === mesh1) {
  31204. body1 = registeredMesh.body;
  31205. if (body2)
  31206. break;
  31207. }
  31208. else if (registeredMesh.mesh === mesh2) {
  31209. body2 = registeredMesh.body;
  31210. if (body1)
  31211. break;
  31212. }
  31213. }
  31214. if (!body1 || !body2) {
  31215. return false;
  31216. }
  31217. 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));
  31218. this._world.addConstraint(constraint);
  31219. return true;
  31220. };
  31221. CannonJSPlugin.prototype.dispose = function () {
  31222. while (this._registeredMeshes.length) {
  31223. this.unregisterMesh(this._registeredMeshes[0].mesh);
  31224. }
  31225. };
  31226. CannonJSPlugin.prototype.isSupported = function () {
  31227. return window.CANNON !== undefined;
  31228. };
  31229. CannonJSPlugin.prototype.getWorldObject = function () {
  31230. return this._world;
  31231. };
  31232. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  31233. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31234. var registeredMesh = this._registeredMeshes[index];
  31235. if (registeredMesh.mesh === mesh) {
  31236. return registeredMesh.body;
  31237. }
  31238. }
  31239. return null;
  31240. };
  31241. return CannonJSPlugin;
  31242. })();
  31243. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31244. })(BABYLON || (BABYLON = {}));
  31245. var BABYLON;
  31246. (function (BABYLON) {
  31247. var OimoJSPlugin = (function () {
  31248. function OimoJSPlugin() {
  31249. this._registeredMeshes = [];
  31250. this.name = "oimo";
  31251. /**
  31252. * Update the body position according to the mesh position
  31253. * @param mesh
  31254. */
  31255. this.updateBodyPosition = function (mesh) {
  31256. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31257. var registeredMesh = this._registeredMeshes[index];
  31258. var body = registeredMesh.body.body;
  31259. var updated = false;
  31260. var newPosition;
  31261. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  31262. mesh.computeWorldMatrix(true);
  31263. newPosition = mesh.getBoundingInfo().boundingBox.center;
  31264. updated = true;
  31265. }
  31266. else if (registeredMesh.mesh.parent === mesh) {
  31267. mesh.computeWorldMatrix(true);
  31268. registeredMesh.mesh.computeWorldMatrix(true);
  31269. newPosition = registeredMesh.mesh.getAbsolutePosition();
  31270. updated = true;
  31271. }
  31272. if (updated) {
  31273. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  31274. body.setQuaternion(mesh.rotationQuaternion);
  31275. body.sleeping = false;
  31276. //force Oimo to update the body's position
  31277. body.updatePosition(1);
  31278. }
  31279. }
  31280. };
  31281. }
  31282. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  31283. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  31284. };
  31285. OimoJSPlugin.prototype.initialize = function (iterations) {
  31286. this._world = new OIMO.World(null, null, iterations);
  31287. this._world.clear();
  31288. };
  31289. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31290. this._gravity = this._world.gravity = gravity;
  31291. };
  31292. OimoJSPlugin.prototype.getGravity = function () {
  31293. return this._gravity;
  31294. };
  31295. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  31296. this.unregisterMesh(mesh);
  31297. if (!mesh.rotationQuaternion) {
  31298. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  31299. }
  31300. mesh.computeWorldMatrix(true);
  31301. var bbox = mesh.getBoundingInfo().boundingBox;
  31302. // The delta between the mesh position and the mesh bounding box center
  31303. var deltaPosition = mesh.position.subtract(bbox.center);
  31304. //calculate rotation to fit Oimo's needs (Euler...)
  31305. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  31306. //get the correct bounding box
  31307. var oldQuaternion = mesh.rotationQuaternion;
  31308. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31309. mesh.computeWorldMatrix(true);
  31310. var bodyConfig = {
  31311. name: mesh.uniqueId,
  31312. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  31313. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  31314. move: options.mass != 0,
  31315. config: [options.mass, options.friction, options.restitution],
  31316. world: this._world
  31317. };
  31318. // register mesh
  31319. switch (impostor) {
  31320. case BABYLON.PhysicsEngine.SphereImpostor:
  31321. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31322. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31323. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31324. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  31325. bodyConfig.type = 'sphere';
  31326. bodyConfig.size = [size];
  31327. break;
  31328. case BABYLON.PhysicsEngine.PlaneImpostor:
  31329. //Oimo "fakes" a cylinder as a box, so why don't we!
  31330. case BABYLON.PhysicsEngine.CylinderImpostor:
  31331. case BABYLON.PhysicsEngine.BoxImpostor:
  31332. var min = bbox.minimumWorld;
  31333. var max = bbox.maximumWorld;
  31334. var box = max.subtract(min);
  31335. var sizeX = this._checkWithEpsilon(box.x);
  31336. var sizeY = this._checkWithEpsilon(box.y);
  31337. var sizeZ = this._checkWithEpsilon(box.z);
  31338. bodyConfig.type = 'box';
  31339. bodyConfig.size = [sizeX, sizeY, sizeZ];
  31340. break;
  31341. }
  31342. var body = new OIMO.Body(bodyConfig);
  31343. //We have to access the rigid body's properties to set the quaternion.
  31344. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  31345. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  31346. //TEST
  31347. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  31348. //update the internal rotation matrix
  31349. //body.body.syncShapes();
  31350. this._registeredMeshes.push({
  31351. mesh: mesh,
  31352. body: body,
  31353. delta: deltaPosition
  31354. });
  31355. //for the sake of consistency.
  31356. mesh.rotationQuaternion = oldQuaternion;
  31357. return body;
  31358. };
  31359. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  31360. var types = [], sizes = [], positions = [], rotations = [];
  31361. var initialMesh = parts[0].mesh;
  31362. for (var index = 0; index < parts.length; index++) {
  31363. var part = parts[index];
  31364. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  31365. types.push(bodyParameters.type);
  31366. sizes.push.apply(sizes, bodyParameters.size);
  31367. positions.push.apply(positions, bodyParameters.pos);
  31368. rotations.push.apply(rotations, bodyParameters.rot);
  31369. }
  31370. var body = new OIMO.Body({
  31371. name: initialMesh.uniqueId,
  31372. type: types,
  31373. size: sizes,
  31374. pos: positions,
  31375. rot: rotations,
  31376. move: options.mass != 0,
  31377. config: [options.mass, options.friction, options.restitution],
  31378. world: this._world
  31379. });
  31380. //Reset the body's rotation to be of the initial mesh's.
  31381. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  31382. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  31383. this._registeredMeshes.push({
  31384. mesh: initialMesh,
  31385. body: body
  31386. });
  31387. return body;
  31388. };
  31389. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  31390. var mesh = part.mesh;
  31391. if (!mesh.rotationQuaternion) {
  31392. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  31393. }
  31394. // We need the bounding box/sphere info to compute the physics body
  31395. mesh.computeWorldMatrix(true);
  31396. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  31397. var bodyParameters = {
  31398. name: mesh.uniqueId,
  31399. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  31400. //A bug in Oimo (Body class) prevents us from using rot directly.
  31401. rot: [0, 0, 0],
  31402. //For future reference, if the bug will ever be fixed.
  31403. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  31404. };
  31405. var oldQuaternion = mesh.rotationQuaternion;
  31406. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31407. mesh.computeWorldMatrix(true);
  31408. switch (part.impostor) {
  31409. case BABYLON.PhysicsEngine.SphereImpostor:
  31410. var bbox = mesh.getBoundingInfo().boundingBox;
  31411. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31412. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31413. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31414. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  31415. bodyParameters.type = 'sphere';
  31416. bodyParameters.size = [size, size, size];
  31417. break;
  31418. case BABYLON.PhysicsEngine.PlaneImpostor:
  31419. case BABYLON.PhysicsEngine.CylinderImpostor:
  31420. case BABYLON.PhysicsEngine.BoxImpostor:
  31421. bbox = mesh.getBoundingInfo().boundingBox;
  31422. var min = bbox.minimumWorld;
  31423. var max = bbox.maximumWorld;
  31424. var box = max.subtract(min);
  31425. var sizeX = this._checkWithEpsilon(box.x);
  31426. var sizeY = this._checkWithEpsilon(box.y);
  31427. var sizeZ = this._checkWithEpsilon(box.z);
  31428. bodyParameters.type = 'box';
  31429. bodyParameters.size = [sizeX, sizeY, sizeZ];
  31430. break;
  31431. }
  31432. mesh.rotationQuaternion = oldQuaternion;
  31433. return bodyParameters;
  31434. };
  31435. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  31436. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31437. var registeredMesh = this._registeredMeshes[index];
  31438. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  31439. if (registeredMesh.body) {
  31440. this._world.removeRigidBody(registeredMesh.body.body);
  31441. this._unbindBody(registeredMesh.body);
  31442. }
  31443. this._registeredMeshes.splice(index, 1);
  31444. return;
  31445. }
  31446. }
  31447. };
  31448. OimoJSPlugin.prototype._unbindBody = function (body) {
  31449. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31450. var registeredMesh = this._registeredMeshes[index];
  31451. if (registeredMesh.body === body) {
  31452. registeredMesh.body = null;
  31453. }
  31454. }
  31455. };
  31456. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  31457. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31458. var registeredMesh = this._registeredMeshes[index];
  31459. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  31460. // Get object mass to have a behaviour similar to cannon.js
  31461. var mass = registeredMesh.body.body.massInfo.mass;
  31462. // The force is scaled with the mass of object
  31463. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31464. return;
  31465. }
  31466. }
  31467. };
  31468. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  31469. var body1 = null, body2 = null;
  31470. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31471. var registeredMesh = this._registeredMeshes[index];
  31472. if (registeredMesh.mesh === mesh1) {
  31473. body1 = registeredMesh.body.body;
  31474. }
  31475. else if (registeredMesh.mesh === mesh2) {
  31476. body2 = registeredMesh.body.body;
  31477. }
  31478. }
  31479. if (!body1 || !body2) {
  31480. return false;
  31481. }
  31482. if (!options) {
  31483. options = {};
  31484. }
  31485. new OIMO.Link({
  31486. type: options.type,
  31487. body1: body1,
  31488. body2: body2,
  31489. min: options.min,
  31490. max: options.max,
  31491. axe1: options.axe1,
  31492. axe2: options.axe2,
  31493. pos1: [pivot1.x, pivot1.y, pivot1.z],
  31494. pos2: [pivot2.x, pivot2.y, pivot2.z],
  31495. collision: options.collision,
  31496. spring: options.spring,
  31497. world: this._world
  31498. });
  31499. return true;
  31500. };
  31501. OimoJSPlugin.prototype.dispose = function () {
  31502. this._world.clear();
  31503. while (this._registeredMeshes.length) {
  31504. this.unregisterMesh(this._registeredMeshes[0].mesh);
  31505. }
  31506. };
  31507. OimoJSPlugin.prototype.isSupported = function () {
  31508. return OIMO !== undefined;
  31509. };
  31510. OimoJSPlugin.prototype.getWorldObject = function () {
  31511. return this._world;
  31512. };
  31513. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  31514. for (var index = 0; index < this._registeredMeshes.length; index++) {
  31515. var registeredMesh = this._registeredMeshes[index];
  31516. if (registeredMesh.mesh === mesh) {
  31517. return registeredMesh.body;
  31518. }
  31519. }
  31520. return null;
  31521. };
  31522. OimoJSPlugin.prototype._getLastShape = function (body) {
  31523. var lastShape = body.shapes;
  31524. while (lastShape.next) {
  31525. lastShape = lastShape.next;
  31526. }
  31527. return lastShape;
  31528. };
  31529. OimoJSPlugin.prototype.runOneStep = function (time) {
  31530. this._world.step();
  31531. // Update the position of all registered meshes
  31532. var i = this._registeredMeshes.length;
  31533. var m;
  31534. while (i--) {
  31535. var body = this._registeredMeshes[i].body.body;
  31536. var mesh = this._registeredMeshes[i].mesh;
  31537. if (!this._registeredMeshes[i].delta) {
  31538. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  31539. }
  31540. if (!body.sleeping) {
  31541. //TODO check that
  31542. if (body.shapes.next) {
  31543. var parentShape = this._getLastShape(body);
  31544. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31545. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31546. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31547. }
  31548. else {
  31549. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  31550. }
  31551. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  31552. mesh.computeWorldMatrix();
  31553. }
  31554. //check if the collide callback is set.
  31555. if (mesh.onPhysicsCollide) {
  31556. var meshUniqueName = mesh.uniqueId;
  31557. var contact = this._world.contacts;
  31558. while (contact !== null) {
  31559. //is this body colliding with any other?
  31560. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31561. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  31562. //get the mesh and execute the callback
  31563. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  31564. if (otherMesh)
  31565. mesh.onPhysicsCollide(otherMesh, contact);
  31566. }
  31567. contact = contact.next;
  31568. }
  31569. }
  31570. }
  31571. };
  31572. return OimoJSPlugin;
  31573. })();
  31574. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31575. })(BABYLON || (BABYLON = {}));
  31576. var BABYLON;
  31577. (function (BABYLON) {
  31578. var DisplayPassPostProcess = (function (_super) {
  31579. __extends(DisplayPassPostProcess, _super);
  31580. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31581. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31582. }
  31583. return DisplayPassPostProcess;
  31584. })(BABYLON.PostProcess);
  31585. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31586. })(BABYLON || (BABYLON = {}));
  31587. var BABYLON;
  31588. (function (BABYLON) {
  31589. var SimplificationSettings = (function () {
  31590. function SimplificationSettings(quality, distance, optimizeMesh) {
  31591. this.quality = quality;
  31592. this.distance = distance;
  31593. this.optimizeMesh = optimizeMesh;
  31594. }
  31595. return SimplificationSettings;
  31596. })();
  31597. BABYLON.SimplificationSettings = SimplificationSettings;
  31598. var SimplificationQueue = (function () {
  31599. function SimplificationQueue() {
  31600. this.running = false;
  31601. this._simplificationArray = [];
  31602. }
  31603. SimplificationQueue.prototype.addTask = function (task) {
  31604. this._simplificationArray.push(task);
  31605. };
  31606. SimplificationQueue.prototype.executeNext = function () {
  31607. var task = this._simplificationArray.pop();
  31608. if (task) {
  31609. this.running = true;
  31610. this.runSimplification(task);
  31611. }
  31612. else {
  31613. this.running = false;
  31614. }
  31615. };
  31616. SimplificationQueue.prototype.runSimplification = function (task) {
  31617. var _this = this;
  31618. if (task.parallelProcessing) {
  31619. //parallel simplifier
  31620. task.settings.forEach(function (setting) {
  31621. var simplifier = _this.getSimplifier(task);
  31622. simplifier.simplify(setting, function (newMesh) {
  31623. task.mesh.addLODLevel(setting.distance, newMesh);
  31624. newMesh.isVisible = true;
  31625. //check if it is the last
  31626. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31627. //all done, run the success callback.
  31628. task.successCallback();
  31629. }
  31630. _this.executeNext();
  31631. });
  31632. });
  31633. }
  31634. else {
  31635. //single simplifier.
  31636. var simplifier = this.getSimplifier(task);
  31637. var runDecimation = function (setting, callback) {
  31638. simplifier.simplify(setting, function (newMesh) {
  31639. task.mesh.addLODLevel(setting.distance, newMesh);
  31640. newMesh.isVisible = true;
  31641. //run the next quality level
  31642. callback();
  31643. });
  31644. };
  31645. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31646. runDecimation(task.settings[loop.index], function () {
  31647. loop.executeNext();
  31648. });
  31649. }, function () {
  31650. //execution ended, run the success callback.
  31651. if (task.successCallback) {
  31652. task.successCallback();
  31653. }
  31654. _this.executeNext();
  31655. });
  31656. }
  31657. };
  31658. SimplificationQueue.prototype.getSimplifier = function (task) {
  31659. switch (task.simplificationType) {
  31660. case SimplificationType.QUADRATIC:
  31661. default:
  31662. return new QuadraticErrorSimplification(task.mesh);
  31663. }
  31664. };
  31665. return SimplificationQueue;
  31666. })();
  31667. BABYLON.SimplificationQueue = SimplificationQueue;
  31668. /**
  31669. * The implemented types of simplification.
  31670. * At the moment only Quadratic Error Decimation is implemented.
  31671. */
  31672. (function (SimplificationType) {
  31673. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31674. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31675. var SimplificationType = BABYLON.SimplificationType;
  31676. var DecimationTriangle = (function () {
  31677. function DecimationTriangle(vertices) {
  31678. this.vertices = vertices;
  31679. this.error = new Array(4);
  31680. this.deleted = false;
  31681. this.isDirty = false;
  31682. this.deletePending = false;
  31683. this.borderFactor = 0;
  31684. }
  31685. return DecimationTriangle;
  31686. })();
  31687. BABYLON.DecimationTriangle = DecimationTriangle;
  31688. var DecimationVertex = (function () {
  31689. function DecimationVertex(position, id) {
  31690. this.position = position;
  31691. this.id = id;
  31692. this.isBorder = true;
  31693. this.q = new QuadraticMatrix();
  31694. this.triangleCount = 0;
  31695. this.triangleStart = 0;
  31696. this.originalOffsets = [];
  31697. }
  31698. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31699. this.position.copyFrom(newPosition);
  31700. };
  31701. return DecimationVertex;
  31702. })();
  31703. BABYLON.DecimationVertex = DecimationVertex;
  31704. var QuadraticMatrix = (function () {
  31705. function QuadraticMatrix(data) {
  31706. this.data = new Array(10);
  31707. for (var i = 0; i < 10; ++i) {
  31708. if (data && data[i]) {
  31709. this.data[i] = data[i];
  31710. }
  31711. else {
  31712. this.data[i] = 0;
  31713. }
  31714. }
  31715. }
  31716. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31717. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31718. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31719. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31720. return det;
  31721. };
  31722. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31723. for (var i = 0; i < 10; ++i) {
  31724. this.data[i] += matrix.data[i];
  31725. }
  31726. };
  31727. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31728. for (var i = 0; i < 10; ++i) {
  31729. this.data[i] += data[i];
  31730. }
  31731. };
  31732. QuadraticMatrix.prototype.add = function (matrix) {
  31733. var m = new QuadraticMatrix();
  31734. for (var i = 0; i < 10; ++i) {
  31735. m.data[i] = this.data[i] + matrix.data[i];
  31736. }
  31737. return m;
  31738. };
  31739. QuadraticMatrix.FromData = function (a, b, c, d) {
  31740. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31741. };
  31742. //returning an array to avoid garbage collection
  31743. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31744. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31745. };
  31746. return QuadraticMatrix;
  31747. })();
  31748. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31749. var Reference = (function () {
  31750. function Reference(vertexId, triangleId) {
  31751. this.vertexId = vertexId;
  31752. this.triangleId = triangleId;
  31753. }
  31754. return Reference;
  31755. })();
  31756. BABYLON.Reference = Reference;
  31757. /**
  31758. * An implementation of the Quadratic Error simplification algorithm.
  31759. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31760. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31761. * @author RaananW
  31762. */
  31763. var QuadraticErrorSimplification = (function () {
  31764. function QuadraticErrorSimplification(_mesh) {
  31765. this._mesh = _mesh;
  31766. this.initialized = false;
  31767. this.syncIterations = 5000;
  31768. this.aggressiveness = 7;
  31769. this.decimationIterations = 100;
  31770. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31771. }
  31772. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31773. var _this = this;
  31774. this.initDecimatedMesh();
  31775. //iterating through the submeshes array, one after the other.
  31776. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31777. _this.initWithMesh(loop.index, function () {
  31778. _this.runDecimation(settings, loop.index, function () {
  31779. loop.executeNext();
  31780. });
  31781. }, settings.optimizeMesh);
  31782. }, function () {
  31783. setTimeout(function () {
  31784. successCallback(_this._reconstructedMesh);
  31785. }, 0);
  31786. });
  31787. };
  31788. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31789. var _this = this;
  31790. var gCount = 0;
  31791. triangle.vertices.forEach(function (vertex) {
  31792. var count = 0;
  31793. var vPos = vertex.position;
  31794. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31795. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31796. ++count;
  31797. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31798. ++count;
  31799. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31800. ++count;
  31801. if (count > 1) {
  31802. ++gCount;
  31803. }
  31804. ;
  31805. });
  31806. if (gCount > 1) {
  31807. console.log(triangle, gCount);
  31808. }
  31809. return gCount > 1;
  31810. };
  31811. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31812. var _this = this;
  31813. var targetCount = ~~(this.triangles.length * settings.quality);
  31814. var deletedTriangles = 0;
  31815. var triangleCount = this.triangles.length;
  31816. var iterationFunction = function (iteration, callback) {
  31817. setTimeout(function () {
  31818. if (iteration % 5 === 0) {
  31819. _this.updateMesh(iteration === 0);
  31820. }
  31821. for (var i = 0; i < _this.triangles.length; ++i) {
  31822. _this.triangles[i].isDirty = false;
  31823. }
  31824. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31825. var trianglesIterator = function (i) {
  31826. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31827. var t = _this.triangles[tIdx];
  31828. if (!t)
  31829. return;
  31830. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31831. return;
  31832. }
  31833. for (var j = 0; j < 3; ++j) {
  31834. if (t.error[j] < threshold) {
  31835. var deleted0 = [];
  31836. var deleted1 = [];
  31837. var v0 = t.vertices[j];
  31838. var v1 = t.vertices[(j + 1) % 3];
  31839. if (v0.isBorder !== v1.isBorder)
  31840. continue;
  31841. var p = BABYLON.Vector3.Zero();
  31842. var n = BABYLON.Vector3.Zero();
  31843. var uv = BABYLON.Vector2.Zero();
  31844. var color = new BABYLON.Color4(0, 0, 0, 1);
  31845. _this.calculateError(v0, v1, p, n, uv, color);
  31846. var delTr = [];
  31847. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31848. continue;
  31849. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31850. continue;
  31851. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31852. continue;
  31853. var uniqueArray = [];
  31854. delTr.forEach(function (deletedT) {
  31855. if (uniqueArray.indexOf(deletedT) === -1) {
  31856. deletedT.deletePending = true;
  31857. uniqueArray.push(deletedT);
  31858. }
  31859. });
  31860. if (uniqueArray.length % 2 !== 0) {
  31861. continue;
  31862. }
  31863. v0.q = v1.q.add(v0.q);
  31864. v0.updatePosition(p);
  31865. var tStart = _this.references.length;
  31866. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31867. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31868. var tCount = _this.references.length - tStart;
  31869. if (tCount <= v0.triangleCount) {
  31870. if (tCount) {
  31871. for (var c = 0; c < tCount; c++) {
  31872. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31873. }
  31874. }
  31875. }
  31876. else {
  31877. v0.triangleStart = tStart;
  31878. }
  31879. v0.triangleCount = tCount;
  31880. break;
  31881. }
  31882. }
  31883. };
  31884. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31885. }, 0);
  31886. };
  31887. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31888. if (triangleCount - deletedTriangles <= targetCount)
  31889. loop.breakLoop();
  31890. else {
  31891. iterationFunction(loop.index, function () {
  31892. loop.executeNext();
  31893. });
  31894. }
  31895. }, function () {
  31896. setTimeout(function () {
  31897. //reconstruct this part of the mesh
  31898. _this.reconstructMesh(submeshIndex);
  31899. successCallback();
  31900. }, 0);
  31901. });
  31902. };
  31903. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31904. var _this = this;
  31905. this.vertices = [];
  31906. this.triangles = [];
  31907. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31908. var indices = this._mesh.getIndices();
  31909. var submesh = this._mesh.subMeshes[submeshIndex];
  31910. var findInVertices = function (positionToSearch) {
  31911. if (optimizeMesh) {
  31912. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31913. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31914. return _this.vertices[ii];
  31915. }
  31916. }
  31917. }
  31918. return null;
  31919. };
  31920. var vertexReferences = [];
  31921. var vertexInit = function (i) {
  31922. var offset = i + submesh.verticesStart;
  31923. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31924. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31925. vertex.originalOffsets.push(offset);
  31926. if (vertex.id === _this.vertices.length) {
  31927. _this.vertices.push(vertex);
  31928. }
  31929. vertexReferences.push(vertex.id);
  31930. };
  31931. //var totalVertices = mesh.getTotalVertices();
  31932. var totalVertices = submesh.verticesCount;
  31933. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31934. var indicesInit = function (i) {
  31935. var offset = (submesh.indexStart / 3) + i;
  31936. var pos = (offset * 3);
  31937. var i0 = indices[pos + 0];
  31938. var i1 = indices[pos + 1];
  31939. var i2 = indices[pos + 2];
  31940. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31941. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31942. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31943. var triangle = new DecimationTriangle([v0, v1, v2]);
  31944. triangle.originalOffset = pos;
  31945. _this.triangles.push(triangle);
  31946. };
  31947. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31948. _this.init(callback);
  31949. });
  31950. });
  31951. };
  31952. QuadraticErrorSimplification.prototype.init = function (callback) {
  31953. var _this = this;
  31954. var triangleInit1 = function (i) {
  31955. var t = _this.triangles[i];
  31956. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31957. for (var j = 0; j < 3; j++) {
  31958. 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))));
  31959. }
  31960. };
  31961. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31962. var triangleInit2 = function (i) {
  31963. var t = _this.triangles[i];
  31964. for (var j = 0; j < 3; ++j) {
  31965. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31966. }
  31967. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31968. };
  31969. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31970. _this.initialized = true;
  31971. callback();
  31972. });
  31973. });
  31974. };
  31975. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31976. var newTriangles = [];
  31977. var i;
  31978. for (i = 0; i < this.vertices.length; ++i) {
  31979. this.vertices[i].triangleCount = 0;
  31980. }
  31981. var t;
  31982. var j;
  31983. for (i = 0; i < this.triangles.length; ++i) {
  31984. if (!this.triangles[i].deleted) {
  31985. t = this.triangles[i];
  31986. for (j = 0; j < 3; ++j) {
  31987. t.vertices[j].triangleCount = 1;
  31988. }
  31989. newTriangles.push(t);
  31990. }
  31991. }
  31992. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31993. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31994. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31995. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31996. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31997. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31998. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31999. var vertexCount = 0;
  32000. for (i = 0; i < this.vertices.length; ++i) {
  32001. var vertex = this.vertices[i];
  32002. vertex.id = vertexCount;
  32003. if (vertex.triangleCount) {
  32004. vertex.originalOffsets.forEach(function (originalOffset) {
  32005. newPositionData.push(vertex.position.x);
  32006. newPositionData.push(vertex.position.y);
  32007. newPositionData.push(vertex.position.z);
  32008. newNormalData.push(normalData[originalOffset * 3]);
  32009. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32010. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32011. if (uvs && uvs.length) {
  32012. newUVsData.push(uvs[(originalOffset * 2)]);
  32013. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32014. }
  32015. else if (colorsData && colorsData.length) {
  32016. newColorsData.push(colorsData[(originalOffset * 4)]);
  32017. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32018. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32019. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32020. }
  32021. ++vertexCount;
  32022. });
  32023. }
  32024. }
  32025. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32026. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32027. var submeshesArray = this._reconstructedMesh.subMeshes;
  32028. this._reconstructedMesh.subMeshes = [];
  32029. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32030. var originalIndices = this._mesh.getIndices();
  32031. for (i = 0; i < newTriangles.length; ++i) {
  32032. t = newTriangles[i]; //now get the new referencing point for each vertex
  32033. [0, 1, 2].forEach(function (idx) {
  32034. var id = originalIndices[t.originalOffset + idx];
  32035. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32036. if (offset < 0)
  32037. offset = 0;
  32038. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32039. });
  32040. }
  32041. //overwriting the old vertex buffers and indices.
  32042. this._reconstructedMesh.setIndices(newIndicesArray);
  32043. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32044. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32045. if (newUVsData.length > 0)
  32046. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32047. if (newColorsData.length > 0)
  32048. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32049. //create submesh
  32050. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32051. if (submeshIndex > 0) {
  32052. this._reconstructedMesh.subMeshes = [];
  32053. submeshesArray.forEach(function (submesh) {
  32054. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32055. });
  32056. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32057. }
  32058. };
  32059. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32060. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32061. this._reconstructedMesh.material = this._mesh.material;
  32062. this._reconstructedMesh.parent = this._mesh.parent;
  32063. this._reconstructedMesh.isVisible = false;
  32064. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  32065. };
  32066. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32067. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32068. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32069. if (t.deleted)
  32070. continue;
  32071. var s = this.references[vertex1.triangleStart + i].vertexId;
  32072. var v1 = t.vertices[(s + 1) % 3];
  32073. var v2 = t.vertices[(s + 2) % 3];
  32074. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32075. deletedArray[i] = true;
  32076. delTr.push(t);
  32077. continue;
  32078. }
  32079. var d1 = v1.position.subtract(point);
  32080. d1 = d1.normalize();
  32081. var d2 = v2.position.subtract(point);
  32082. d2 = d2.normalize();
  32083. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32084. return true;
  32085. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32086. deletedArray[i] = false;
  32087. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32088. return true;
  32089. }
  32090. return false;
  32091. };
  32092. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32093. var newDeleted = deletedTriangles;
  32094. for (var i = 0; i < vertex.triangleCount; ++i) {
  32095. var ref = this.references[vertex.triangleStart + i];
  32096. var t = this.triangles[ref.triangleId];
  32097. if (t.deleted)
  32098. continue;
  32099. if (deletedArray[i] && t.deletePending) {
  32100. t.deleted = true;
  32101. newDeleted++;
  32102. continue;
  32103. }
  32104. t.vertices[ref.vertexId] = origVertex;
  32105. t.isDirty = true;
  32106. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32107. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32108. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32109. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32110. this.references.push(ref);
  32111. }
  32112. return newDeleted;
  32113. };
  32114. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32115. for (var i = 0; i < this.vertices.length; ++i) {
  32116. var vCount = [];
  32117. var vId = [];
  32118. var v = this.vertices[i];
  32119. var j;
  32120. for (j = 0; j < v.triangleCount; ++j) {
  32121. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32122. for (var ii = 0; ii < 3; ii++) {
  32123. var ofs = 0;
  32124. var vv = triangle.vertices[ii];
  32125. while (ofs < vCount.length) {
  32126. if (vId[ofs] === vv.id)
  32127. break;
  32128. ++ofs;
  32129. }
  32130. if (ofs === vCount.length) {
  32131. vCount.push(1);
  32132. vId.push(vv.id);
  32133. }
  32134. else {
  32135. vCount[ofs]++;
  32136. }
  32137. }
  32138. }
  32139. for (j = 0; j < vCount.length; ++j) {
  32140. if (vCount[j] === 1) {
  32141. this.vertices[vId[j]].isBorder = true;
  32142. }
  32143. else {
  32144. this.vertices[vId[j]].isBorder = false;
  32145. }
  32146. }
  32147. }
  32148. };
  32149. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32150. if (identifyBorders === void 0) { identifyBorders = false; }
  32151. var i;
  32152. if (!identifyBorders) {
  32153. var newTrianglesVector = [];
  32154. for (i = 0; i < this.triangles.length; ++i) {
  32155. if (!this.triangles[i].deleted) {
  32156. newTrianglesVector.push(this.triangles[i]);
  32157. }
  32158. }
  32159. this.triangles = newTrianglesVector;
  32160. }
  32161. for (i = 0; i < this.vertices.length; ++i) {
  32162. this.vertices[i].triangleCount = 0;
  32163. this.vertices[i].triangleStart = 0;
  32164. }
  32165. var t;
  32166. var j;
  32167. var v;
  32168. for (i = 0; i < this.triangles.length; ++i) {
  32169. t = this.triangles[i];
  32170. for (j = 0; j < 3; ++j) {
  32171. v = t.vertices[j];
  32172. v.triangleCount++;
  32173. }
  32174. }
  32175. var tStart = 0;
  32176. for (i = 0; i < this.vertices.length; ++i) {
  32177. this.vertices[i].triangleStart = tStart;
  32178. tStart += this.vertices[i].triangleCount;
  32179. this.vertices[i].triangleCount = 0;
  32180. }
  32181. var newReferences = new Array(this.triangles.length * 3);
  32182. for (i = 0; i < this.triangles.length; ++i) {
  32183. t = this.triangles[i];
  32184. for (j = 0; j < 3; ++j) {
  32185. v = t.vertices[j];
  32186. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32187. v.triangleCount++;
  32188. }
  32189. }
  32190. this.references = newReferences;
  32191. if (identifyBorders) {
  32192. this.identifyBorder();
  32193. }
  32194. };
  32195. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32196. var x = point.x;
  32197. var y = point.y;
  32198. var z = point.z;
  32199. 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
  32200. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32201. };
  32202. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32203. var q = vertex1.q.add(vertex2.q);
  32204. var border = vertex1.isBorder && vertex2.isBorder;
  32205. var error = 0;
  32206. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32207. if (qDet !== 0 && !border) {
  32208. if (!pointResult) {
  32209. pointResult = BABYLON.Vector3.Zero();
  32210. }
  32211. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32212. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32213. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32214. error = this.vertexError(q, pointResult);
  32215. }
  32216. else {
  32217. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32218. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32219. var error1 = this.vertexError(q, vertex1.position);
  32220. var error2 = this.vertexError(q, vertex2.position);
  32221. var error3 = this.vertexError(q, p3);
  32222. error = Math.min(error1, error2, error3);
  32223. if (error === error1) {
  32224. if (pointResult) {
  32225. pointResult.copyFrom(vertex1.position);
  32226. }
  32227. }
  32228. else if (error === error2) {
  32229. if (pointResult) {
  32230. pointResult.copyFrom(vertex2.position);
  32231. }
  32232. }
  32233. else {
  32234. if (pointResult) {
  32235. pointResult.copyFrom(p3);
  32236. }
  32237. }
  32238. }
  32239. return error;
  32240. };
  32241. return QuadraticErrorSimplification;
  32242. })();
  32243. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32244. })(BABYLON || (BABYLON = {}));
  32245. var BABYLON;
  32246. (function (BABYLON) {
  32247. var serializedGeometries = [];
  32248. var serializeGeometry = function (geometry, serializationGeometries) {
  32249. if (serializedGeometries[geometry.id]) {
  32250. return;
  32251. }
  32252. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32253. serializationGeometries.boxes.push(geometry.serialize());
  32254. }
  32255. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32256. serializationGeometries.spheres.push(geometry.serialize());
  32257. }
  32258. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32259. serializationGeometries.cylinders.push(geometry.serialize());
  32260. }
  32261. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32262. serializationGeometries.toruses.push(geometry.serialize());
  32263. }
  32264. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32265. serializationGeometries.grounds.push(geometry.serialize());
  32266. }
  32267. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32268. serializationGeometries.planes.push(geometry.serialize());
  32269. }
  32270. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32271. serializationGeometries.torusKnots.push(geometry.serialize());
  32272. }
  32273. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32274. throw new Error("Unknown primitive type");
  32275. }
  32276. else {
  32277. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32278. }
  32279. serializedGeometries[geometry.id] = true;
  32280. };
  32281. var serializeMesh = function (mesh, serializationScene) {
  32282. var serializationObject = {};
  32283. serializationObject.name = mesh.name;
  32284. serializationObject.id = mesh.id;
  32285. if (BABYLON.Tags.HasTags(mesh)) {
  32286. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32287. }
  32288. serializationObject.position = mesh.position.asArray();
  32289. if (mesh.rotationQuaternion) {
  32290. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32291. }
  32292. else if (mesh.rotation) {
  32293. serializationObject.rotation = mesh.rotation.asArray();
  32294. }
  32295. serializationObject.scaling = mesh.scaling.asArray();
  32296. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32297. serializationObject.isEnabled = mesh.isEnabled();
  32298. serializationObject.isVisible = mesh.isVisible;
  32299. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32300. serializationObject.pickable = mesh.isPickable;
  32301. serializationObject.receiveShadows = mesh.receiveShadows;
  32302. serializationObject.billboardMode = mesh.billboardMode;
  32303. serializationObject.visibility = mesh.visibility;
  32304. serializationObject.checkCollisions = mesh.checkCollisions;
  32305. // Parent
  32306. if (mesh.parent) {
  32307. serializationObject.parentId = mesh.parent.id;
  32308. }
  32309. // Geometry
  32310. var geometry = mesh._geometry;
  32311. if (geometry) {
  32312. var geometryId = geometry.id;
  32313. serializationObject.geometryId = geometryId;
  32314. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32315. // 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
  32316. serializeGeometry(geometry, serializationScene.geometries);
  32317. }
  32318. // SubMeshes
  32319. serializationObject.subMeshes = [];
  32320. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32321. var subMesh = mesh.subMeshes[subIndex];
  32322. serializationObject.subMeshes.push({
  32323. materialIndex: subMesh.materialIndex,
  32324. verticesStart: subMesh.verticesStart,
  32325. verticesCount: subMesh.verticesCount,
  32326. indexStart: subMesh.indexStart,
  32327. indexCount: subMesh.indexCount
  32328. });
  32329. }
  32330. }
  32331. // Material
  32332. if (mesh.material) {
  32333. serializationObject.materialId = mesh.material.id;
  32334. }
  32335. else {
  32336. mesh.material = null;
  32337. }
  32338. // Skeleton
  32339. if (mesh.skeleton) {
  32340. serializationObject.skeletonId = mesh.skeleton.id;
  32341. }
  32342. // Physics
  32343. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  32344. serializationObject.physicsMass = mesh.getPhysicsMass();
  32345. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32346. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32347. switch (mesh.getPhysicsImpostor()) {
  32348. case BABYLON.PhysicsEngine.BoxImpostor:
  32349. serializationObject.physicsImpostor = 1;
  32350. break;
  32351. case BABYLON.PhysicsEngine.SphereImpostor:
  32352. serializationObject.physicsImpostor = 2;
  32353. break;
  32354. }
  32355. }
  32356. // Instances
  32357. serializationObject.instances = [];
  32358. for (var index = 0; index < mesh.instances.length; index++) {
  32359. var instance = mesh.instances[index];
  32360. var serializationInstance = {
  32361. name: instance.name,
  32362. position: instance.position.asArray(),
  32363. scaling: instance.scaling.asArray()
  32364. };
  32365. if (instance.rotationQuaternion) {
  32366. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32367. }
  32368. else if (instance.rotation) {
  32369. serializationInstance.rotation = instance.rotation.asArray();
  32370. }
  32371. serializationObject.instances.push(serializationInstance);
  32372. // Animations
  32373. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32374. serializationInstance.ranges = instance.serializeAnimationRanges();
  32375. }
  32376. // Animations
  32377. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32378. serializationObject.ranges = mesh.serializeAnimationRanges();
  32379. // Layer mask
  32380. serializationObject.layerMask = mesh.layerMask;
  32381. return serializationObject;
  32382. };
  32383. var finalizeSingleMesh = function (mesh, serializationObject) {
  32384. //only works if the mesh is already loaded
  32385. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32386. //serialize material
  32387. if (mesh.material) {
  32388. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32389. serializationObject.materials = serializationObject.materials || [];
  32390. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32391. serializationObject.materials.push(mesh.material.serialize());
  32392. }
  32393. }
  32394. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32395. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32396. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32397. serializationObject.multiMaterials.push(mesh.material.serialize());
  32398. }
  32399. }
  32400. }
  32401. //serialize geometry
  32402. var geometry = mesh._geometry;
  32403. if (geometry) {
  32404. if (!serializationObject.geometries) {
  32405. serializationObject.geometries = {};
  32406. serializationObject.geometries.boxes = [];
  32407. serializationObject.geometries.spheres = [];
  32408. serializationObject.geometries.cylinders = [];
  32409. serializationObject.geometries.toruses = [];
  32410. serializationObject.geometries.grounds = [];
  32411. serializationObject.geometries.planes = [];
  32412. serializationObject.geometries.torusKnots = [];
  32413. serializationObject.geometries.vertexData = [];
  32414. }
  32415. serializeGeometry(geometry, serializationObject.geometries);
  32416. }
  32417. // Skeletons
  32418. if (mesh.skeleton) {
  32419. serializationObject.skeletons = serializationObject.skeletons || [];
  32420. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32421. }
  32422. //serialize the actual mesh
  32423. serializationObject.meshes = serializationObject.meshes || [];
  32424. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32425. }
  32426. };
  32427. var SceneSerializer = (function () {
  32428. function SceneSerializer() {
  32429. }
  32430. SceneSerializer.ClearCache = function () {
  32431. serializedGeometries = [];
  32432. };
  32433. SceneSerializer.Serialize = function (scene) {
  32434. var serializationObject = {};
  32435. // Scene
  32436. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32437. serializationObject.autoClear = scene.autoClear;
  32438. serializationObject.clearColor = scene.clearColor.asArray();
  32439. serializationObject.ambientColor = scene.ambientColor.asArray();
  32440. serializationObject.gravity = scene.gravity.asArray();
  32441. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32442. serializationObject.workerCollisions = scene.workerCollisions;
  32443. // Fog
  32444. if (scene.fogMode && scene.fogMode !== 0) {
  32445. serializationObject.fogMode = scene.fogMode;
  32446. serializationObject.fogColor = scene.fogColor.asArray();
  32447. serializationObject.fogStart = scene.fogStart;
  32448. serializationObject.fogEnd = scene.fogEnd;
  32449. serializationObject.fogDensity = scene.fogDensity;
  32450. }
  32451. //Physics
  32452. if (scene.isPhysicsEnabled()) {
  32453. serializationObject.physicsEnabled = true;
  32454. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  32455. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32456. }
  32457. // Lights
  32458. serializationObject.lights = [];
  32459. var index;
  32460. var light;
  32461. for (index = 0; index < scene.lights.length; index++) {
  32462. light = scene.lights[index];
  32463. serializationObject.lights.push(light.serialize());
  32464. }
  32465. // Cameras
  32466. serializationObject.cameras = [];
  32467. for (index = 0; index < scene.cameras.length; index++) {
  32468. var camera = scene.cameras[index];
  32469. serializationObject.cameras.push(camera.serialize());
  32470. }
  32471. if (scene.activeCamera) {
  32472. serializationObject.activeCameraID = scene.activeCamera.id;
  32473. }
  32474. // Animations
  32475. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32476. // Materials
  32477. serializationObject.materials = [];
  32478. serializationObject.multiMaterials = [];
  32479. var material;
  32480. for (index = 0; index < scene.materials.length; index++) {
  32481. material = scene.materials[index];
  32482. serializationObject.materials.push(material.serialize());
  32483. }
  32484. // MultiMaterials
  32485. serializationObject.multiMaterials = [];
  32486. for (index = 0; index < scene.multiMaterials.length; index++) {
  32487. var multiMaterial = scene.multiMaterials[index];
  32488. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32489. }
  32490. // Skeletons
  32491. serializationObject.skeletons = [];
  32492. for (index = 0; index < scene.skeletons.length; index++) {
  32493. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32494. }
  32495. // Geometries
  32496. serializationObject.geometries = {};
  32497. serializationObject.geometries.boxes = [];
  32498. serializationObject.geometries.spheres = [];
  32499. serializationObject.geometries.cylinders = [];
  32500. serializationObject.geometries.toruses = [];
  32501. serializationObject.geometries.grounds = [];
  32502. serializationObject.geometries.planes = [];
  32503. serializationObject.geometries.torusKnots = [];
  32504. serializationObject.geometries.vertexData = [];
  32505. serializedGeometries = [];
  32506. var geometries = scene.getGeometries();
  32507. for (index = 0; index < geometries.length; index++) {
  32508. var geometry = geometries[index];
  32509. if (geometry.isReady()) {
  32510. serializeGeometry(geometry, serializationObject.geometries);
  32511. }
  32512. }
  32513. // Meshes
  32514. serializationObject.meshes = [];
  32515. for (index = 0; index < scene.meshes.length; index++) {
  32516. var abstractMesh = scene.meshes[index];
  32517. if (abstractMesh instanceof BABYLON.Mesh) {
  32518. var mesh = abstractMesh;
  32519. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32520. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32521. }
  32522. }
  32523. }
  32524. // Particles Systems
  32525. serializationObject.particleSystems = [];
  32526. for (index = 0; index < scene.particleSystems.length; index++) {
  32527. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32528. }
  32529. // Lens flares
  32530. serializationObject.lensFlareSystems = [];
  32531. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32532. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32533. }
  32534. // Shadows
  32535. serializationObject.shadowGenerators = [];
  32536. for (index = 0; index < scene.lights.length; index++) {
  32537. light = scene.lights[index];
  32538. if (light.getShadowGenerator()) {
  32539. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32540. }
  32541. }
  32542. return serializationObject;
  32543. };
  32544. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32545. if (withParents === void 0) { withParents = false; }
  32546. if (withChildren === void 0) { withChildren = false; }
  32547. var serializationObject = {};
  32548. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32549. if (withParents || withChildren) {
  32550. //deliberate for loop! not for each, appended should be processed as well.
  32551. for (var i = 0; i < toSerialize.length; ++i) {
  32552. if (withChildren) {
  32553. toSerialize[i].getDescendants().forEach(function (node) {
  32554. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32555. toSerialize.push(node);
  32556. }
  32557. });
  32558. }
  32559. //make sure the array doesn't contain the object already
  32560. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32561. toSerialize.push(toSerialize[i].parent);
  32562. }
  32563. }
  32564. }
  32565. toSerialize.forEach(function (mesh) {
  32566. finalizeSingleMesh(mesh, serializationObject);
  32567. });
  32568. return serializationObject;
  32569. };
  32570. return SceneSerializer;
  32571. })();
  32572. BABYLON.SceneSerializer = SceneSerializer;
  32573. })(BABYLON || (BABYLON = {}));
  32574. var BABYLON;
  32575. (function (BABYLON) {
  32576. // Unique ID when we import meshes from Babylon to CSG
  32577. var currentCSGMeshId = 0;
  32578. // # class Vertex
  32579. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32580. // one to provide additional features like texture coordinates and vertex
  32581. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32582. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32583. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32584. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32585. // is not used anywhere else.
  32586. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32587. var Vertex = (function () {
  32588. function Vertex(pos, normal, uv) {
  32589. this.pos = pos;
  32590. this.normal = normal;
  32591. this.uv = uv;
  32592. }
  32593. Vertex.prototype.clone = function () {
  32594. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32595. };
  32596. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32597. // orientation of a polygon is flipped.
  32598. Vertex.prototype.flip = function () {
  32599. this.normal = this.normal.scale(-1);
  32600. };
  32601. // Create a new vertex between this vertex and `other` by linearly
  32602. // interpolating all properties using a parameter of `t`. Subclasses should
  32603. // override this to interpolate additional properties.
  32604. Vertex.prototype.interpolate = function (other, t) {
  32605. 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));
  32606. };
  32607. return Vertex;
  32608. })();
  32609. // # class Plane
  32610. // Represents a plane in 3D space.
  32611. var Plane = (function () {
  32612. function Plane(normal, w) {
  32613. this.normal = normal;
  32614. this.w = w;
  32615. }
  32616. Plane.FromPoints = function (a, b, c) {
  32617. var v0 = c.subtract(a);
  32618. var v1 = b.subtract(a);
  32619. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32620. return null;
  32621. }
  32622. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32623. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32624. };
  32625. Plane.prototype.clone = function () {
  32626. return new Plane(this.normal.clone(), this.w);
  32627. };
  32628. Plane.prototype.flip = function () {
  32629. this.normal.scaleInPlace(-1);
  32630. this.w = -this.w;
  32631. };
  32632. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32633. // fragments in the appropriate lists. Coplanar polygons go into either
  32634. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32635. // respect to this plane. Polygons in front or in back of this plane go into
  32636. // either `front` or `back`.
  32637. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32638. var COPLANAR = 0;
  32639. var FRONT = 1;
  32640. var BACK = 2;
  32641. var SPANNING = 3;
  32642. // Classify each point as well as the entire polygon into one of the above
  32643. // four classes.
  32644. var polygonType = 0;
  32645. var types = [];
  32646. var i;
  32647. var t;
  32648. for (i = 0; i < polygon.vertices.length; i++) {
  32649. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32650. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32651. polygonType |= type;
  32652. types.push(type);
  32653. }
  32654. // Put the polygon in the correct list, splitting it when necessary.
  32655. switch (polygonType) {
  32656. case COPLANAR:
  32657. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32658. break;
  32659. case FRONT:
  32660. front.push(polygon);
  32661. break;
  32662. case BACK:
  32663. back.push(polygon);
  32664. break;
  32665. case SPANNING:
  32666. var f = [], b = [];
  32667. for (i = 0; i < polygon.vertices.length; i++) {
  32668. var j = (i + 1) % polygon.vertices.length;
  32669. var ti = types[i], tj = types[j];
  32670. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32671. if (ti !== BACK)
  32672. f.push(vi);
  32673. if (ti !== FRONT)
  32674. b.push(ti !== BACK ? vi.clone() : vi);
  32675. if ((ti | tj) === SPANNING) {
  32676. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32677. var v = vi.interpolate(vj, t);
  32678. f.push(v);
  32679. b.push(v.clone());
  32680. }
  32681. }
  32682. var poly;
  32683. if (f.length >= 3) {
  32684. poly = new Polygon(f, polygon.shared);
  32685. if (poly.plane)
  32686. front.push(poly);
  32687. }
  32688. if (b.length >= 3) {
  32689. poly = new Polygon(b, polygon.shared);
  32690. if (poly.plane)
  32691. back.push(poly);
  32692. }
  32693. break;
  32694. }
  32695. };
  32696. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32697. // point is on the plane.
  32698. Plane.EPSILON = 1e-5;
  32699. return Plane;
  32700. })();
  32701. // # class Polygon
  32702. // Represents a convex polygon. The vertices used to initialize a polygon must
  32703. // be coplanar and form a convex loop.
  32704. //
  32705. // Each convex polygon has a `shared` property, which is shared between all
  32706. // polygons that are clones of each other or were split from the same polygon.
  32707. // This can be used to define per-polygon properties (such as surface color).
  32708. var Polygon = (function () {
  32709. function Polygon(vertices, shared) {
  32710. this.vertices = vertices;
  32711. this.shared = shared;
  32712. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32713. }
  32714. Polygon.prototype.clone = function () {
  32715. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32716. return new Polygon(vertices, this.shared);
  32717. };
  32718. Polygon.prototype.flip = function () {
  32719. this.vertices.reverse().map(function (v) { v.flip(); });
  32720. this.plane.flip();
  32721. };
  32722. return Polygon;
  32723. })();
  32724. // # class Node
  32725. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32726. // by picking a polygon to split along. That polygon (and all other coplanar
  32727. // polygons) are added directly to that node and the other polygons are added to
  32728. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32729. // no distinction between internal and leaf nodes.
  32730. var Node = (function () {
  32731. function Node(polygons) {
  32732. this.plane = null;
  32733. this.front = null;
  32734. this.back = null;
  32735. this.polygons = [];
  32736. if (polygons) {
  32737. this.build(polygons);
  32738. }
  32739. }
  32740. Node.prototype.clone = function () {
  32741. var node = new Node();
  32742. node.plane = this.plane && this.plane.clone();
  32743. node.front = this.front && this.front.clone();
  32744. node.back = this.back && this.back.clone();
  32745. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32746. return node;
  32747. };
  32748. // Convert solid space to empty space and empty space to solid space.
  32749. Node.prototype.invert = function () {
  32750. for (var i = 0; i < this.polygons.length; i++) {
  32751. this.polygons[i].flip();
  32752. }
  32753. if (this.plane) {
  32754. this.plane.flip();
  32755. }
  32756. if (this.front) {
  32757. this.front.invert();
  32758. }
  32759. if (this.back) {
  32760. this.back.invert();
  32761. }
  32762. var temp = this.front;
  32763. this.front = this.back;
  32764. this.back = temp;
  32765. };
  32766. // Recursively remove all polygons in `polygons` that are inside this BSP
  32767. // tree.
  32768. Node.prototype.clipPolygons = function (polygons) {
  32769. if (!this.plane)
  32770. return polygons.slice();
  32771. var front = [], back = [];
  32772. for (var i = 0; i < polygons.length; i++) {
  32773. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32774. }
  32775. if (this.front) {
  32776. front = this.front.clipPolygons(front);
  32777. }
  32778. if (this.back) {
  32779. back = this.back.clipPolygons(back);
  32780. }
  32781. else {
  32782. back = [];
  32783. }
  32784. return front.concat(back);
  32785. };
  32786. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32787. // `bsp`.
  32788. Node.prototype.clipTo = function (bsp) {
  32789. this.polygons = bsp.clipPolygons(this.polygons);
  32790. if (this.front)
  32791. this.front.clipTo(bsp);
  32792. if (this.back)
  32793. this.back.clipTo(bsp);
  32794. };
  32795. // Return a list of all polygons in this BSP tree.
  32796. Node.prototype.allPolygons = function () {
  32797. var polygons = this.polygons.slice();
  32798. if (this.front)
  32799. polygons = polygons.concat(this.front.allPolygons());
  32800. if (this.back)
  32801. polygons = polygons.concat(this.back.allPolygons());
  32802. return polygons;
  32803. };
  32804. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32805. // new polygons are filtered down to the bottom of the tree and become new
  32806. // nodes there. Each set of polygons is partitioned using the first polygon
  32807. // (no heuristic is used to pick a good split).
  32808. Node.prototype.build = function (polygons) {
  32809. if (!polygons.length)
  32810. return;
  32811. if (!this.plane)
  32812. this.plane = polygons[0].plane.clone();
  32813. var front = [], back = [];
  32814. for (var i = 0; i < polygons.length; i++) {
  32815. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32816. }
  32817. if (front.length) {
  32818. if (!this.front)
  32819. this.front = new Node();
  32820. this.front.build(front);
  32821. }
  32822. if (back.length) {
  32823. if (!this.back)
  32824. this.back = new Node();
  32825. this.back.build(back);
  32826. }
  32827. };
  32828. return Node;
  32829. })();
  32830. var CSG = (function () {
  32831. function CSG() {
  32832. this.polygons = new Array();
  32833. }
  32834. // Convert BABYLON.Mesh to BABYLON.CSG
  32835. CSG.FromMesh = function (mesh) {
  32836. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32837. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32838. if (mesh instanceof BABYLON.Mesh) {
  32839. mesh.computeWorldMatrix(true);
  32840. matrix = mesh.getWorldMatrix();
  32841. meshPosition = mesh.position.clone();
  32842. meshRotation = mesh.rotation.clone();
  32843. if (mesh.rotationQuaternion) {
  32844. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32845. }
  32846. meshScaling = mesh.scaling.clone();
  32847. }
  32848. else {
  32849. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32850. }
  32851. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32852. var subMeshes = mesh.subMeshes;
  32853. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32854. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32855. vertices = [];
  32856. for (var j = 0; j < 3; j++) {
  32857. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32858. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32859. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32860. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32861. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32862. vertex = new Vertex(position, normal, uv);
  32863. vertices.push(vertex);
  32864. }
  32865. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32866. // To handle the case of degenerated triangle
  32867. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32868. if (polygon.plane)
  32869. polygons.push(polygon);
  32870. }
  32871. }
  32872. var csg = CSG.FromPolygons(polygons);
  32873. csg.matrix = matrix;
  32874. csg.position = meshPosition;
  32875. csg.rotation = meshRotation;
  32876. csg.scaling = meshScaling;
  32877. csg.rotationQuaternion = meshRotationQuaternion;
  32878. currentCSGMeshId++;
  32879. return csg;
  32880. };
  32881. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32882. CSG.FromPolygons = function (polygons) {
  32883. var csg = new CSG();
  32884. csg.polygons = polygons;
  32885. return csg;
  32886. };
  32887. CSG.prototype.clone = function () {
  32888. var csg = new CSG();
  32889. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32890. csg.copyTransformAttributes(this);
  32891. return csg;
  32892. };
  32893. CSG.prototype.toPolygons = function () {
  32894. return this.polygons;
  32895. };
  32896. CSG.prototype.union = function (csg) {
  32897. var a = new Node(this.clone().polygons);
  32898. var b = new Node(csg.clone().polygons);
  32899. a.clipTo(b);
  32900. b.clipTo(a);
  32901. b.invert();
  32902. b.clipTo(a);
  32903. b.invert();
  32904. a.build(b.allPolygons());
  32905. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32906. };
  32907. CSG.prototype.unionInPlace = function (csg) {
  32908. var a = new Node(this.polygons);
  32909. var b = new Node(csg.polygons);
  32910. a.clipTo(b);
  32911. b.clipTo(a);
  32912. b.invert();
  32913. b.clipTo(a);
  32914. b.invert();
  32915. a.build(b.allPolygons());
  32916. this.polygons = a.allPolygons();
  32917. };
  32918. CSG.prototype.subtract = function (csg) {
  32919. var a = new Node(this.clone().polygons);
  32920. var b = new Node(csg.clone().polygons);
  32921. a.invert();
  32922. a.clipTo(b);
  32923. b.clipTo(a);
  32924. b.invert();
  32925. b.clipTo(a);
  32926. b.invert();
  32927. a.build(b.allPolygons());
  32928. a.invert();
  32929. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32930. };
  32931. CSG.prototype.subtractInPlace = function (csg) {
  32932. var a = new Node(this.polygons);
  32933. var b = new Node(csg.polygons);
  32934. a.invert();
  32935. a.clipTo(b);
  32936. b.clipTo(a);
  32937. b.invert();
  32938. b.clipTo(a);
  32939. b.invert();
  32940. a.build(b.allPolygons());
  32941. a.invert();
  32942. this.polygons = a.allPolygons();
  32943. };
  32944. CSG.prototype.intersect = function (csg) {
  32945. var a = new Node(this.clone().polygons);
  32946. var b = new Node(csg.clone().polygons);
  32947. a.invert();
  32948. b.clipTo(a);
  32949. b.invert();
  32950. a.clipTo(b);
  32951. b.clipTo(a);
  32952. a.build(b.allPolygons());
  32953. a.invert();
  32954. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32955. };
  32956. CSG.prototype.intersectInPlace = function (csg) {
  32957. var a = new Node(this.polygons);
  32958. var b = new Node(csg.polygons);
  32959. a.invert();
  32960. b.clipTo(a);
  32961. b.invert();
  32962. a.clipTo(b);
  32963. b.clipTo(a);
  32964. a.build(b.allPolygons());
  32965. a.invert();
  32966. this.polygons = a.allPolygons();
  32967. };
  32968. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32969. // not modified.
  32970. CSG.prototype.inverse = function () {
  32971. var csg = this.clone();
  32972. csg.inverseInPlace();
  32973. return csg;
  32974. };
  32975. CSG.prototype.inverseInPlace = function () {
  32976. this.polygons.map(function (p) { p.flip(); });
  32977. };
  32978. // This is used to keep meshes transformations so they can be restored
  32979. // when we build back a Babylon Mesh
  32980. // NB : All CSG operations are performed in world coordinates
  32981. CSG.prototype.copyTransformAttributes = function (csg) {
  32982. this.matrix = csg.matrix;
  32983. this.position = csg.position;
  32984. this.rotation = csg.rotation;
  32985. this.scaling = csg.scaling;
  32986. this.rotationQuaternion = csg.rotationQuaternion;
  32987. return this;
  32988. };
  32989. // Build Raw mesh from CSG
  32990. // Coordinates here are in world space
  32991. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32992. var matrix = this.matrix.clone();
  32993. matrix.invert();
  32994. 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;
  32995. if (keepSubMeshes) {
  32996. // Sort Polygons, since subMeshes are indices range
  32997. polygons.sort(function (a, b) {
  32998. if (a.shared.meshId === b.shared.meshId) {
  32999. return a.shared.subMeshId - b.shared.subMeshId;
  33000. }
  33001. else {
  33002. return a.shared.meshId - b.shared.meshId;
  33003. }
  33004. });
  33005. }
  33006. for (var i = 0, il = polygons.length; i < il; i++) {
  33007. polygon = polygons[i];
  33008. // Building SubMeshes
  33009. if (!subMesh_dict[polygon.shared.meshId]) {
  33010. subMesh_dict[polygon.shared.meshId] = {};
  33011. }
  33012. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  33013. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  33014. indexStart: +Infinity,
  33015. indexEnd: -Infinity,
  33016. materialIndex: polygon.shared.materialIndex
  33017. };
  33018. }
  33019. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  33020. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  33021. polygonIndices[0] = 0;
  33022. polygonIndices[1] = j - 1;
  33023. polygonIndices[2] = j;
  33024. for (var k = 0; k < 3; k++) {
  33025. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  33026. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  33027. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  33028. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  33029. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  33030. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  33031. // Check if 2 points can be merged
  33032. if (!(typeof vertex_idx !== 'undefined' &&
  33033. normals[vertex_idx * 3] === localNormal.x &&
  33034. normals[vertex_idx * 3 + 1] === localNormal.y &&
  33035. normals[vertex_idx * 3 + 2] === localNormal.z &&
  33036. uvs[vertex_idx * 2] === uv.x &&
  33037. uvs[vertex_idx * 2 + 1] === uv.y)) {
  33038. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  33039. uvs.push(uv.x, uv.y);
  33040. normals.push(normal.x, normal.y, normal.z);
  33041. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  33042. }
  33043. indices.push(vertex_idx);
  33044. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  33045. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  33046. currentIndex++;
  33047. }
  33048. }
  33049. }
  33050. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  33051. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33052. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  33053. mesh.setIndices(indices);
  33054. if (keepSubMeshes) {
  33055. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  33056. var materialIndexOffset = 0, materialMaxIndex;
  33057. mesh.subMeshes = new Array();
  33058. for (var m in subMesh_dict) {
  33059. materialMaxIndex = -1;
  33060. for (var sm in subMesh_dict[m]) {
  33061. subMesh_obj = subMesh_dict[m][sm];
  33062. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  33063. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  33064. }
  33065. materialIndexOffset += ++materialMaxIndex;
  33066. }
  33067. }
  33068. return mesh;
  33069. };
  33070. // Build Mesh from CSG taking material and transforms into account
  33071. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  33072. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  33073. mesh.material = material;
  33074. mesh.position.copyFrom(this.position);
  33075. mesh.rotation.copyFrom(this.rotation);
  33076. if (this.rotationQuaternion) {
  33077. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  33078. }
  33079. mesh.scaling.copyFrom(this.scaling);
  33080. mesh.computeWorldMatrix(true);
  33081. return mesh;
  33082. };
  33083. return CSG;
  33084. })();
  33085. BABYLON.CSG = CSG;
  33086. })(BABYLON || (BABYLON = {}));
  33087. var BABYLON;
  33088. (function (BABYLON) {
  33089. var VRDistortionCorrectionPostProcess = (function (_super) {
  33090. __extends(VRDistortionCorrectionPostProcess, _super);
  33091. //ANY
  33092. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  33093. var _this = this;
  33094. _super.call(this, name, "vrDistortionCorrection", [
  33095. 'LensCenter',
  33096. 'Scale',
  33097. 'ScaleIn',
  33098. 'HmdWarpParam'
  33099. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  33100. this._isRightEye = isRightEye;
  33101. this._distortionFactors = vrMetrics.distortionK;
  33102. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  33103. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  33104. this.onSizeChanged = function () {
  33105. _this.aspectRatio = _this.width * .5 / _this.height;
  33106. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  33107. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  33108. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  33109. };
  33110. this.onApply = function (effect) {
  33111. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  33112. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  33113. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  33114. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  33115. };
  33116. }
  33117. return VRDistortionCorrectionPostProcess;
  33118. })(BABYLON.PostProcess);
  33119. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  33120. })(BABYLON || (BABYLON = {}));
  33121. // Mainly based on these 2 articles :
  33122. // 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
  33123. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  33124. var BABYLON;
  33125. (function (BABYLON) {
  33126. (function (JoystickAxis) {
  33127. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  33128. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  33129. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  33130. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  33131. var JoystickAxis = BABYLON.JoystickAxis;
  33132. var VirtualJoystick = (function () {
  33133. function VirtualJoystick(leftJoystick) {
  33134. var _this = this;
  33135. if (leftJoystick) {
  33136. this._leftJoystick = true;
  33137. }
  33138. else {
  33139. this._leftJoystick = false;
  33140. }
  33141. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  33142. VirtualJoystick._globalJoystickIndex++;
  33143. // By default left & right arrow keys are moving the X
  33144. // and up & down keys are moving the Y
  33145. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33146. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33147. this.reverseLeftRight = false;
  33148. this.reverseUpDown = false;
  33149. // collections of pointers
  33150. this._touches = new BABYLON.SmartCollection();
  33151. this.deltaPosition = BABYLON.Vector3.Zero();
  33152. this._joystickSensibility = 25;
  33153. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33154. this._rotationSpeed = 25;
  33155. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  33156. this._rotateOnAxisRelativeToMesh = false;
  33157. this._onResize = function (evt) {
  33158. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33159. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33160. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  33161. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  33162. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  33163. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  33164. };
  33165. // injecting a canvas element on top of the canvas 3D game
  33166. if (!VirtualJoystick.vjCanvas) {
  33167. window.addEventListener("resize", this._onResize, false);
  33168. VirtualJoystick.vjCanvas = document.createElement("canvas");
  33169. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33170. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33171. VirtualJoystick.vjCanvas.width = window.innerWidth;
  33172. VirtualJoystick.vjCanvas.height = window.innerHeight;
  33173. VirtualJoystick.vjCanvas.style.width = "100%";
  33174. VirtualJoystick.vjCanvas.style.height = "100%";
  33175. VirtualJoystick.vjCanvas.style.position = "absolute";
  33176. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  33177. VirtualJoystick.vjCanvas.style.top = "0px";
  33178. VirtualJoystick.vjCanvas.style.left = "0px";
  33179. VirtualJoystick.vjCanvas.style.zIndex = "5";
  33180. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  33181. // Support for jQuery PEP polyfill
  33182. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  33183. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  33184. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  33185. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33186. document.body.appendChild(VirtualJoystick.vjCanvas);
  33187. }
  33188. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  33189. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  33190. this.pressed = false;
  33191. // default joystick color
  33192. this._joystickColor = "cyan";
  33193. this._joystickPointerID = -1;
  33194. // current joystick position
  33195. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  33196. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  33197. // origin joystick position
  33198. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  33199. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  33200. this._onPointerDownHandlerRef = function (evt) {
  33201. _this._onPointerDown(evt);
  33202. };
  33203. this._onPointerMoveHandlerRef = function (evt) {
  33204. _this._onPointerMove(evt);
  33205. };
  33206. this._onPointerOutHandlerRef = function (evt) {
  33207. _this._onPointerUp(evt);
  33208. };
  33209. this._onPointerUpHandlerRef = function (evt) {
  33210. _this._onPointerUp(evt);
  33211. };
  33212. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  33213. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  33214. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  33215. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  33216. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  33217. evt.preventDefault(); // Disables system menu
  33218. }, false);
  33219. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33220. }
  33221. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  33222. this._joystickSensibility = newJoystickSensibility;
  33223. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33224. };
  33225. VirtualJoystick.prototype._onPointerDown = function (e) {
  33226. var positionOnScreenCondition;
  33227. e.preventDefault();
  33228. if (this._leftJoystick === true) {
  33229. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  33230. }
  33231. else {
  33232. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  33233. }
  33234. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33235. // First contact will be dedicated to the virtual joystick
  33236. this._joystickPointerID = e.pointerId;
  33237. this._joystickPointerStartPos.x = e.clientX;
  33238. this._joystickPointerStartPos.y = e.clientY;
  33239. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33240. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33241. this._deltaJoystickVector.x = 0;
  33242. this._deltaJoystickVector.y = 0;
  33243. this.pressed = true;
  33244. this._touches.add(e.pointerId.toString(), e);
  33245. }
  33246. else {
  33247. // You can only trigger the action buttons with a joystick declared
  33248. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33249. this._action();
  33250. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33251. }
  33252. }
  33253. };
  33254. VirtualJoystick.prototype._onPointerMove = function (e) {
  33255. // If the current pointer is the one associated to the joystick (first touch contact)
  33256. if (this._joystickPointerID == e.pointerId) {
  33257. this._joystickPointerPos.x = e.clientX;
  33258. this._joystickPointerPos.y = e.clientY;
  33259. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33260. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33261. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33262. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33263. switch (this._axisTargetedByLeftAndRight) {
  33264. case JoystickAxis.X:
  33265. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33266. break;
  33267. case JoystickAxis.Y:
  33268. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33269. break;
  33270. case JoystickAxis.Z:
  33271. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33272. break;
  33273. }
  33274. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33275. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33276. switch (this._axisTargetedByUpAndDown) {
  33277. case JoystickAxis.X:
  33278. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33279. break;
  33280. case JoystickAxis.Y:
  33281. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33282. break;
  33283. case JoystickAxis.Z:
  33284. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33285. break;
  33286. }
  33287. }
  33288. else {
  33289. if (this._touches.item(e.pointerId.toString())) {
  33290. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33291. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33292. }
  33293. }
  33294. };
  33295. VirtualJoystick.prototype._onPointerUp = function (e) {
  33296. if (this._joystickPointerID == e.pointerId) {
  33297. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33298. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33299. this._joystickPointerID = -1;
  33300. this.pressed = false;
  33301. }
  33302. else {
  33303. var touch = this._touches.item(e.pointerId.toString());
  33304. if (touch) {
  33305. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33306. }
  33307. }
  33308. this._deltaJoystickVector.x = 0;
  33309. this._deltaJoystickVector.y = 0;
  33310. this._touches.remove(e.pointerId.toString());
  33311. };
  33312. /**
  33313. * Change the color of the virtual joystick
  33314. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33315. */
  33316. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33317. this._joystickColor = newColor;
  33318. };
  33319. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33320. this._action = action;
  33321. };
  33322. // Define which axis you'd like to control for left & right
  33323. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33324. switch (axis) {
  33325. case JoystickAxis.X:
  33326. case JoystickAxis.Y:
  33327. case JoystickAxis.Z:
  33328. this._axisTargetedByLeftAndRight = axis;
  33329. break;
  33330. default:
  33331. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33332. break;
  33333. }
  33334. };
  33335. // Define which axis you'd like to control for up & down
  33336. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33337. switch (axis) {
  33338. case JoystickAxis.X:
  33339. case JoystickAxis.Y:
  33340. case JoystickAxis.Z:
  33341. this._axisTargetedByUpAndDown = axis;
  33342. break;
  33343. default:
  33344. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33345. break;
  33346. }
  33347. };
  33348. VirtualJoystick.prototype._clearCanvas = function () {
  33349. if (this._leftJoystick) {
  33350. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33351. }
  33352. else {
  33353. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33354. }
  33355. };
  33356. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33357. var _this = this;
  33358. if (this.pressed) {
  33359. this._touches.forEach(function (touch) {
  33360. if (touch.pointerId === _this._joystickPointerID) {
  33361. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33362. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33363. VirtualJoystick.vjCanvasContext.beginPath();
  33364. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33365. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33366. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33367. VirtualJoystick.vjCanvasContext.stroke();
  33368. VirtualJoystick.vjCanvasContext.closePath();
  33369. VirtualJoystick.vjCanvasContext.beginPath();
  33370. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33371. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33372. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33373. VirtualJoystick.vjCanvasContext.stroke();
  33374. VirtualJoystick.vjCanvasContext.closePath();
  33375. VirtualJoystick.vjCanvasContext.beginPath();
  33376. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33377. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33378. VirtualJoystick.vjCanvasContext.stroke();
  33379. VirtualJoystick.vjCanvasContext.closePath();
  33380. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33381. }
  33382. else {
  33383. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33384. VirtualJoystick.vjCanvasContext.beginPath();
  33385. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33386. VirtualJoystick.vjCanvasContext.beginPath();
  33387. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33388. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33389. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33390. VirtualJoystick.vjCanvasContext.stroke();
  33391. VirtualJoystick.vjCanvasContext.closePath();
  33392. touch.prevX = touch.x;
  33393. touch.prevY = touch.y;
  33394. }
  33395. ;
  33396. });
  33397. }
  33398. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33399. };
  33400. VirtualJoystick.prototype.releaseCanvas = function () {
  33401. if (VirtualJoystick.vjCanvas) {
  33402. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33403. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33404. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33405. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33406. window.removeEventListener("resize", this._onResize);
  33407. document.body.removeChild(VirtualJoystick.vjCanvas);
  33408. VirtualJoystick.vjCanvas = null;
  33409. }
  33410. };
  33411. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33412. VirtualJoystick._globalJoystickIndex = 0;
  33413. return VirtualJoystick;
  33414. })();
  33415. BABYLON.VirtualJoystick = VirtualJoystick;
  33416. })(BABYLON || (BABYLON = {}));
  33417. var BABYLON;
  33418. (function (BABYLON) {
  33419. // We're mainly based on the logic defined into the FreeCamera code
  33420. var VirtualJoysticksCamera = (function (_super) {
  33421. __extends(VirtualJoysticksCamera, _super);
  33422. function VirtualJoysticksCamera(name, position, scene) {
  33423. _super.call(this, name, position, scene);
  33424. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33425. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33426. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33427. this._leftjoystick.setJoystickSensibility(0.15);
  33428. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33429. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33430. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33431. this._rightjoystick.reverseUpDown = true;
  33432. this._rightjoystick.setJoystickSensibility(0.05);
  33433. this._rightjoystick.setJoystickColor("yellow");
  33434. }
  33435. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33436. return this._leftjoystick;
  33437. };
  33438. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33439. return this._rightjoystick;
  33440. };
  33441. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33442. var speed = this._computeLocalCameraSpeed() * 50;
  33443. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33444. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33445. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33446. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33447. if (!this._leftjoystick.pressed) {
  33448. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33449. }
  33450. if (!this._rightjoystick.pressed) {
  33451. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33452. }
  33453. _super.prototype._checkInputs.call(this);
  33454. };
  33455. VirtualJoysticksCamera.prototype.dispose = function () {
  33456. this._leftjoystick.releaseCanvas();
  33457. _super.prototype.dispose.call(this);
  33458. };
  33459. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33460. return "VirtualJoysticksCamera";
  33461. };
  33462. return VirtualJoysticksCamera;
  33463. })(BABYLON.FreeCamera);
  33464. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33465. })(BABYLON || (BABYLON = {}));
  33466. var BABYLON;
  33467. (function (BABYLON) {
  33468. var AnaglyphPostProcess = (function (_super) {
  33469. __extends(AnaglyphPostProcess, _super);
  33470. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33471. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33472. }
  33473. return AnaglyphPostProcess;
  33474. })(BABYLON.PostProcess);
  33475. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33476. })(BABYLON || (BABYLON = {}));
  33477. var BABYLON;
  33478. (function (BABYLON) {
  33479. var OutlineRenderer = (function () {
  33480. function OutlineRenderer(scene) {
  33481. this._scene = scene;
  33482. }
  33483. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33484. var _this = this;
  33485. if (useOverlay === void 0) { useOverlay = false; }
  33486. var scene = this._scene;
  33487. var engine = this._scene.getEngine();
  33488. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33489. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33490. return;
  33491. }
  33492. var mesh = subMesh.getRenderingMesh();
  33493. var material = subMesh.getMaterial();
  33494. engine.enableEffect(this._effect);
  33495. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33496. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33497. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33498. // Bones
  33499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33500. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33501. }
  33502. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33503. // Alpha test
  33504. if (material && material.needAlphaTesting()) {
  33505. var alphaTexture = material.getAlphaTestTexture();
  33506. this._effect.setTexture("diffuseSampler", alphaTexture);
  33507. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33508. }
  33509. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33510. };
  33511. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33512. var defines = [];
  33513. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33514. var mesh = subMesh.getMesh();
  33515. var material = subMesh.getMaterial();
  33516. // Alpha test
  33517. if (material && material.needAlphaTesting()) {
  33518. defines.push("#define ALPHATEST");
  33519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33520. attribs.push(BABYLON.VertexBuffer.UVKind);
  33521. defines.push("#define UV1");
  33522. }
  33523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33525. defines.push("#define UV2");
  33526. }
  33527. }
  33528. // Bones
  33529. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33530. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33531. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33532. if (mesh.numBoneInfluencers > 4) {
  33533. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33534. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33535. }
  33536. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33537. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33538. }
  33539. else {
  33540. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33541. }
  33542. // Instances
  33543. if (useInstances) {
  33544. defines.push("#define INSTANCES");
  33545. attribs.push("world0");
  33546. attribs.push("world1");
  33547. attribs.push("world2");
  33548. attribs.push("world3");
  33549. }
  33550. // Get correct effect
  33551. var join = defines.join("\n");
  33552. if (this._cachedDefines !== join) {
  33553. this._cachedDefines = join;
  33554. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33555. }
  33556. return this._effect.isReady();
  33557. };
  33558. return OutlineRenderer;
  33559. })();
  33560. BABYLON.OutlineRenderer = OutlineRenderer;
  33561. })(BABYLON || (BABYLON = {}));
  33562. var BABYLON;
  33563. (function (BABYLON) {
  33564. var MeshAssetTask = (function () {
  33565. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33566. this.name = name;
  33567. this.meshesNames = meshesNames;
  33568. this.rootUrl = rootUrl;
  33569. this.sceneFilename = sceneFilename;
  33570. this.isCompleted = false;
  33571. }
  33572. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33573. var _this = this;
  33574. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33575. _this.loadedMeshes = meshes;
  33576. _this.loadedParticleSystems = particleSystems;
  33577. _this.loadedSkeletons = skeletons;
  33578. _this.isCompleted = true;
  33579. if (_this.onSuccess) {
  33580. _this.onSuccess(_this);
  33581. }
  33582. onSuccess();
  33583. }, null, function () {
  33584. if (_this.onError) {
  33585. _this.onError(_this);
  33586. }
  33587. onError();
  33588. });
  33589. };
  33590. return MeshAssetTask;
  33591. })();
  33592. BABYLON.MeshAssetTask = MeshAssetTask;
  33593. var TextFileAssetTask = (function () {
  33594. function TextFileAssetTask(name, url) {
  33595. this.name = name;
  33596. this.url = url;
  33597. this.isCompleted = false;
  33598. }
  33599. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33600. var _this = this;
  33601. BABYLON.Tools.LoadFile(this.url, function (data) {
  33602. _this.text = data;
  33603. _this.isCompleted = true;
  33604. if (_this.onSuccess) {
  33605. _this.onSuccess(_this);
  33606. }
  33607. onSuccess();
  33608. }, null, scene.database, false, function () {
  33609. if (_this.onError) {
  33610. _this.onError(_this);
  33611. }
  33612. onError();
  33613. });
  33614. };
  33615. return TextFileAssetTask;
  33616. })();
  33617. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33618. var BinaryFileAssetTask = (function () {
  33619. function BinaryFileAssetTask(name, url) {
  33620. this.name = name;
  33621. this.url = url;
  33622. this.isCompleted = false;
  33623. }
  33624. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33625. var _this = this;
  33626. BABYLON.Tools.LoadFile(this.url, function (data) {
  33627. _this.data = data;
  33628. _this.isCompleted = true;
  33629. if (_this.onSuccess) {
  33630. _this.onSuccess(_this);
  33631. }
  33632. onSuccess();
  33633. }, null, scene.database, true, function () {
  33634. if (_this.onError) {
  33635. _this.onError(_this);
  33636. }
  33637. onError();
  33638. });
  33639. };
  33640. return BinaryFileAssetTask;
  33641. })();
  33642. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33643. var ImageAssetTask = (function () {
  33644. function ImageAssetTask(name, url) {
  33645. this.name = name;
  33646. this.url = url;
  33647. this.isCompleted = false;
  33648. }
  33649. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33650. var _this = this;
  33651. var img = new Image();
  33652. img.onload = function () {
  33653. _this.image = img;
  33654. _this.isCompleted = true;
  33655. if (_this.onSuccess) {
  33656. _this.onSuccess(_this);
  33657. }
  33658. onSuccess();
  33659. };
  33660. img.onerror = function () {
  33661. if (_this.onError) {
  33662. _this.onError(_this);
  33663. }
  33664. onError();
  33665. };
  33666. img.src = this.url;
  33667. };
  33668. return ImageAssetTask;
  33669. })();
  33670. BABYLON.ImageAssetTask = ImageAssetTask;
  33671. var TextureAssetTask = (function () {
  33672. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33674. this.name = name;
  33675. this.url = url;
  33676. this.noMipmap = noMipmap;
  33677. this.invertY = invertY;
  33678. this.samplingMode = samplingMode;
  33679. this.isCompleted = false;
  33680. }
  33681. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33682. var _this = this;
  33683. var onload = function () {
  33684. _this.isCompleted = true;
  33685. if (_this.onSuccess) {
  33686. _this.onSuccess(_this);
  33687. }
  33688. onSuccess();
  33689. };
  33690. var onerror = function () {
  33691. if (_this.onError) {
  33692. _this.onError(_this);
  33693. }
  33694. onError();
  33695. };
  33696. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33697. };
  33698. return TextureAssetTask;
  33699. })();
  33700. BABYLON.TextureAssetTask = TextureAssetTask;
  33701. var AssetsManager = (function () {
  33702. function AssetsManager(scene) {
  33703. this._tasks = new Array();
  33704. this._waitingTasksCount = 0;
  33705. this.useDefaultLoadingScreen = true;
  33706. this._scene = scene;
  33707. }
  33708. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33709. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33710. this._tasks.push(task);
  33711. return task;
  33712. };
  33713. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33714. var task = new TextFileAssetTask(taskName, url);
  33715. this._tasks.push(task);
  33716. return task;
  33717. };
  33718. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33719. var task = new BinaryFileAssetTask(taskName, url);
  33720. this._tasks.push(task);
  33721. return task;
  33722. };
  33723. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33724. var task = new ImageAssetTask(taskName, url);
  33725. this._tasks.push(task);
  33726. return task;
  33727. };
  33728. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33730. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33731. this._tasks.push(task);
  33732. return task;
  33733. };
  33734. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33735. this._waitingTasksCount--;
  33736. if (this._waitingTasksCount === 0) {
  33737. if (this.onFinish) {
  33738. this.onFinish(this._tasks);
  33739. }
  33740. this._scene.getEngine().hideLoadingUI();
  33741. }
  33742. };
  33743. AssetsManager.prototype._runTask = function (task) {
  33744. var _this = this;
  33745. task.run(this._scene, function () {
  33746. if (_this.onTaskSuccess) {
  33747. _this.onTaskSuccess(task);
  33748. }
  33749. _this._decreaseWaitingTasksCount();
  33750. }, function () {
  33751. if (_this.onTaskError) {
  33752. _this.onTaskError(task);
  33753. }
  33754. _this._decreaseWaitingTasksCount();
  33755. });
  33756. };
  33757. AssetsManager.prototype.reset = function () {
  33758. this._tasks = new Array();
  33759. return this;
  33760. };
  33761. AssetsManager.prototype.load = function () {
  33762. this._waitingTasksCount = this._tasks.length;
  33763. if (this._waitingTasksCount === 0) {
  33764. if (this.onFinish) {
  33765. this.onFinish(this._tasks);
  33766. }
  33767. return this;
  33768. }
  33769. if (this.useDefaultLoadingScreen) {
  33770. this._scene.getEngine().displayLoadingUI();
  33771. }
  33772. for (var index = 0; index < this._tasks.length; index++) {
  33773. var task = this._tasks[index];
  33774. this._runTask(task);
  33775. }
  33776. return this;
  33777. };
  33778. return AssetsManager;
  33779. })();
  33780. BABYLON.AssetsManager = AssetsManager;
  33781. })(BABYLON || (BABYLON = {}));
  33782. var BABYLON;
  33783. (function (BABYLON) {
  33784. var VRCameraMetrics = (function () {
  33785. function VRCameraMetrics() {
  33786. this.compensateDistortion = true;
  33787. }
  33788. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33789. get: function () {
  33790. return this.hResolution / (2 * this.vResolution);
  33791. },
  33792. enumerable: true,
  33793. configurable: true
  33794. });
  33795. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33796. get: function () {
  33797. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33798. },
  33799. enumerable: true,
  33800. configurable: true
  33801. });
  33802. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33803. get: function () {
  33804. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33805. var h = (4 * meters) / this.hScreenSize;
  33806. return BABYLON.Matrix.Translation(h, 0, 0);
  33807. },
  33808. enumerable: true,
  33809. configurable: true
  33810. });
  33811. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33812. get: function () {
  33813. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33814. var h = (4 * meters) / this.hScreenSize;
  33815. return BABYLON.Matrix.Translation(-h, 0, 0);
  33816. },
  33817. enumerable: true,
  33818. configurable: true
  33819. });
  33820. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33821. get: function () {
  33822. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33823. },
  33824. enumerable: true,
  33825. configurable: true
  33826. });
  33827. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33828. get: function () {
  33829. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33830. },
  33831. enumerable: true,
  33832. configurable: true
  33833. });
  33834. VRCameraMetrics.GetDefault = function () {
  33835. var result = new VRCameraMetrics();
  33836. result.hResolution = 1280;
  33837. result.vResolution = 800;
  33838. result.hScreenSize = 0.149759993;
  33839. result.vScreenSize = 0.0935999975;
  33840. result.vScreenCenter = 0.0467999987,
  33841. result.eyeToScreenDistance = 0.0410000011;
  33842. result.lensSeparationDistance = 0.0635000020;
  33843. result.interpupillaryDistance = 0.0640000030;
  33844. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33845. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33846. result.postProcessScaleFactor = 1.714605507808412;
  33847. result.lensCenterOffset = 0.151976421;
  33848. return result;
  33849. };
  33850. return VRCameraMetrics;
  33851. })();
  33852. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33853. })(BABYLON || (BABYLON = {}));
  33854. var BABYLON;
  33855. (function (BABYLON) {
  33856. var VRDeviceOrientationFreeCamera = (function (_super) {
  33857. __extends(VRDeviceOrientationFreeCamera, _super);
  33858. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33859. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33860. _super.call(this, name, position, scene);
  33861. this._alpha = 0;
  33862. this._beta = 0;
  33863. this._gamma = 0;
  33864. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33865. metrics.compensateDistortion = compensateDistortion;
  33866. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33867. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33868. }
  33869. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33870. this._alpha = +evt.alpha | 0;
  33871. this._beta = +evt.beta | 0;
  33872. this._gamma = +evt.gamma | 0;
  33873. if (this._gamma < 0) {
  33874. this._gamma = 90 + this._gamma;
  33875. }
  33876. else {
  33877. // Incline it in the correct angle.
  33878. this._gamma = 270 - this._gamma;
  33879. }
  33880. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33881. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33882. this.rotation.z = this._beta / 180.0 * Math.PI;
  33883. };
  33884. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33885. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33886. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33887. };
  33888. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33889. _super.prototype.detachControl.call(this, element);
  33890. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33891. };
  33892. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33893. return "VRDeviceOrientationFreeCamera";
  33894. };
  33895. return VRDeviceOrientationFreeCamera;
  33896. })(BABYLON.FreeCamera);
  33897. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33898. })(BABYLON || (BABYLON = {}));
  33899. var BABYLON;
  33900. (function (BABYLON) {
  33901. var WebVRFreeCamera = (function (_super) {
  33902. __extends(WebVRFreeCamera, _super);
  33903. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33904. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33905. _super.call(this, name, position, scene);
  33906. this._hmdDevice = null;
  33907. this._sensorDevice = null;
  33908. this._cacheState = null;
  33909. this._cacheQuaternion = new BABYLON.Quaternion();
  33910. this._cacheRotation = BABYLON.Vector3.Zero();
  33911. this._vrEnabled = false;
  33912. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33913. metrics.compensateDistortion = compensateDistortion;
  33914. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33915. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33916. }
  33917. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33918. var size = devices.length;
  33919. var i = 0;
  33920. // Reset devices.
  33921. this._sensorDevice = null;
  33922. this._hmdDevice = null;
  33923. // Search for a HmdDevice.
  33924. while (i < size && this._hmdDevice === null) {
  33925. if (devices[i] instanceof HMDVRDevice) {
  33926. this._hmdDevice = devices[i];
  33927. }
  33928. i++;
  33929. }
  33930. i = 0;
  33931. while (i < size && this._sensorDevice === null) {
  33932. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33933. this._sensorDevice = devices[i];
  33934. }
  33935. i++;
  33936. }
  33937. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33938. };
  33939. WebVRFreeCamera.prototype._checkInputs = function () {
  33940. if (this._vrEnabled) {
  33941. this._cacheState = this._sensorDevice.getState();
  33942. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33943. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33944. this.rotation.x = -this._cacheRotation.z;
  33945. this.rotation.y = -this._cacheRotation.y;
  33946. this.rotation.z = this._cacheRotation.x;
  33947. }
  33948. _super.prototype._checkInputs.call(this);
  33949. };
  33950. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33951. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33952. if (navigator.getVRDevices) {
  33953. navigator.getVRDevices().then(this._getWebVRDevices);
  33954. }
  33955. else if (navigator.mozGetVRDevices) {
  33956. navigator.mozGetVRDevices(this._getWebVRDevices);
  33957. }
  33958. };
  33959. WebVRFreeCamera.prototype.detachControl = function (element) {
  33960. _super.prototype.detachControl.call(this, element);
  33961. this._vrEnabled = false;
  33962. };
  33963. WebVRFreeCamera.prototype.getTypeName = function () {
  33964. return "WebVRFreeCamera";
  33965. };
  33966. return WebVRFreeCamera;
  33967. })(BABYLON.FreeCamera);
  33968. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33969. })(BABYLON || (BABYLON = {}));
  33970. var BABYLON;
  33971. (function (BABYLON) {
  33972. // Standard optimizations
  33973. var SceneOptimization = (function () {
  33974. function SceneOptimization(priority) {
  33975. if (priority === void 0) { priority = 0; }
  33976. this.priority = priority;
  33977. this.apply = function (scene) {
  33978. return true; // Return true if everything that can be done was applied
  33979. };
  33980. }
  33981. return SceneOptimization;
  33982. })();
  33983. BABYLON.SceneOptimization = SceneOptimization;
  33984. var TextureOptimization = (function (_super) {
  33985. __extends(TextureOptimization, _super);
  33986. function TextureOptimization(priority, maximumSize) {
  33987. var _this = this;
  33988. if (priority === void 0) { priority = 0; }
  33989. if (maximumSize === void 0) { maximumSize = 1024; }
  33990. _super.call(this, priority);
  33991. this.priority = priority;
  33992. this.maximumSize = maximumSize;
  33993. this.apply = function (scene) {
  33994. var allDone = true;
  33995. for (var index = 0; index < scene.textures.length; index++) {
  33996. var texture = scene.textures[index];
  33997. if (!texture.canRescale) {
  33998. continue;
  33999. }
  34000. var currentSize = texture.getSize();
  34001. var maxDimension = Math.max(currentSize.width, currentSize.height);
  34002. if (maxDimension > _this.maximumSize) {
  34003. texture.scale(0.5);
  34004. allDone = false;
  34005. }
  34006. }
  34007. return allDone;
  34008. };
  34009. }
  34010. return TextureOptimization;
  34011. })(SceneOptimization);
  34012. BABYLON.TextureOptimization = TextureOptimization;
  34013. var HardwareScalingOptimization = (function (_super) {
  34014. __extends(HardwareScalingOptimization, _super);
  34015. function HardwareScalingOptimization(priority, maximumScale) {
  34016. var _this = this;
  34017. if (priority === void 0) { priority = 0; }
  34018. if (maximumScale === void 0) { maximumScale = 2; }
  34019. _super.call(this, priority);
  34020. this.priority = priority;
  34021. this.maximumScale = maximumScale;
  34022. this._currentScale = 1;
  34023. this.apply = function (scene) {
  34024. _this._currentScale++;
  34025. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  34026. return _this._currentScale >= _this.maximumScale;
  34027. };
  34028. }
  34029. return HardwareScalingOptimization;
  34030. })(SceneOptimization);
  34031. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  34032. var ShadowsOptimization = (function (_super) {
  34033. __extends(ShadowsOptimization, _super);
  34034. function ShadowsOptimization() {
  34035. _super.apply(this, arguments);
  34036. this.apply = function (scene) {
  34037. scene.shadowsEnabled = false;
  34038. return true;
  34039. };
  34040. }
  34041. return ShadowsOptimization;
  34042. })(SceneOptimization);
  34043. BABYLON.ShadowsOptimization = ShadowsOptimization;
  34044. var PostProcessesOptimization = (function (_super) {
  34045. __extends(PostProcessesOptimization, _super);
  34046. function PostProcessesOptimization() {
  34047. _super.apply(this, arguments);
  34048. this.apply = function (scene) {
  34049. scene.postProcessesEnabled = false;
  34050. return true;
  34051. };
  34052. }
  34053. return PostProcessesOptimization;
  34054. })(SceneOptimization);
  34055. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  34056. var LensFlaresOptimization = (function (_super) {
  34057. __extends(LensFlaresOptimization, _super);
  34058. function LensFlaresOptimization() {
  34059. _super.apply(this, arguments);
  34060. this.apply = function (scene) {
  34061. scene.lensFlaresEnabled = false;
  34062. return true;
  34063. };
  34064. }
  34065. return LensFlaresOptimization;
  34066. })(SceneOptimization);
  34067. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  34068. var ParticlesOptimization = (function (_super) {
  34069. __extends(ParticlesOptimization, _super);
  34070. function ParticlesOptimization() {
  34071. _super.apply(this, arguments);
  34072. this.apply = function (scene) {
  34073. scene.particlesEnabled = false;
  34074. return true;
  34075. };
  34076. }
  34077. return ParticlesOptimization;
  34078. })(SceneOptimization);
  34079. BABYLON.ParticlesOptimization = ParticlesOptimization;
  34080. var RenderTargetsOptimization = (function (_super) {
  34081. __extends(RenderTargetsOptimization, _super);
  34082. function RenderTargetsOptimization() {
  34083. _super.apply(this, arguments);
  34084. this.apply = function (scene) {
  34085. scene.renderTargetsEnabled = false;
  34086. return true;
  34087. };
  34088. }
  34089. return RenderTargetsOptimization;
  34090. })(SceneOptimization);
  34091. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  34092. var MergeMeshesOptimization = (function (_super) {
  34093. __extends(MergeMeshesOptimization, _super);
  34094. function MergeMeshesOptimization() {
  34095. var _this = this;
  34096. _super.apply(this, arguments);
  34097. this._canBeMerged = function (abstractMesh) {
  34098. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  34099. return false;
  34100. }
  34101. var mesh = abstractMesh;
  34102. if (!mesh.isVisible || !mesh.isEnabled()) {
  34103. return false;
  34104. }
  34105. if (mesh.instances.length > 0) {
  34106. return false;
  34107. }
  34108. if (mesh.skeleton || mesh.hasLODLevels) {
  34109. return false;
  34110. }
  34111. if (mesh.parent) {
  34112. return false;
  34113. }
  34114. return true;
  34115. };
  34116. this.apply = function (scene, updateSelectionTree) {
  34117. var globalPool = scene.meshes.slice(0);
  34118. var globalLength = globalPool.length;
  34119. for (var index = 0; index < globalLength; index++) {
  34120. var currentPool = new Array();
  34121. var current = globalPool[index];
  34122. // Checks
  34123. if (!_this._canBeMerged(current)) {
  34124. continue;
  34125. }
  34126. currentPool.push(current);
  34127. // Find compatible meshes
  34128. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  34129. var otherMesh = globalPool[subIndex];
  34130. if (!_this._canBeMerged(otherMesh)) {
  34131. continue;
  34132. }
  34133. if (otherMesh.material !== current.material) {
  34134. continue;
  34135. }
  34136. if (otherMesh.checkCollisions !== current.checkCollisions) {
  34137. continue;
  34138. }
  34139. currentPool.push(otherMesh);
  34140. globalLength--;
  34141. globalPool.splice(subIndex, 1);
  34142. subIndex--;
  34143. }
  34144. if (currentPool.length < 2) {
  34145. continue;
  34146. }
  34147. // Merge meshes
  34148. BABYLON.Mesh.MergeMeshes(currentPool);
  34149. }
  34150. if (updateSelectionTree != undefined) {
  34151. if (updateSelectionTree) {
  34152. scene.createOrUpdateSelectionOctree();
  34153. }
  34154. }
  34155. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  34156. scene.createOrUpdateSelectionOctree();
  34157. }
  34158. return true;
  34159. };
  34160. }
  34161. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  34162. get: function () {
  34163. return MergeMeshesOptimization._UpdateSelectionTree;
  34164. },
  34165. set: function (value) {
  34166. MergeMeshesOptimization._UpdateSelectionTree = value;
  34167. },
  34168. enumerable: true,
  34169. configurable: true
  34170. });
  34171. MergeMeshesOptimization._UpdateSelectionTree = false;
  34172. return MergeMeshesOptimization;
  34173. })(SceneOptimization);
  34174. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  34175. // Options
  34176. var SceneOptimizerOptions = (function () {
  34177. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  34178. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  34179. if (trackerDuration === void 0) { trackerDuration = 2000; }
  34180. this.targetFrameRate = targetFrameRate;
  34181. this.trackerDuration = trackerDuration;
  34182. this.optimizations = new Array();
  34183. }
  34184. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  34185. var result = new SceneOptimizerOptions(targetFrameRate);
  34186. var priority = 0;
  34187. result.optimizations.push(new MergeMeshesOptimization(priority));
  34188. result.optimizations.push(new ShadowsOptimization(priority));
  34189. result.optimizations.push(new LensFlaresOptimization(priority));
  34190. // Next priority
  34191. priority++;
  34192. result.optimizations.push(new PostProcessesOptimization(priority));
  34193. result.optimizations.push(new ParticlesOptimization(priority));
  34194. // Next priority
  34195. priority++;
  34196. result.optimizations.push(new TextureOptimization(priority, 1024));
  34197. return result;
  34198. };
  34199. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  34200. var result = new SceneOptimizerOptions(targetFrameRate);
  34201. var priority = 0;
  34202. result.optimizations.push(new MergeMeshesOptimization(priority));
  34203. result.optimizations.push(new ShadowsOptimization(priority));
  34204. result.optimizations.push(new LensFlaresOptimization(priority));
  34205. // Next priority
  34206. priority++;
  34207. result.optimizations.push(new PostProcessesOptimization(priority));
  34208. result.optimizations.push(new ParticlesOptimization(priority));
  34209. // Next priority
  34210. priority++;
  34211. result.optimizations.push(new TextureOptimization(priority, 512));
  34212. // Next priority
  34213. priority++;
  34214. result.optimizations.push(new RenderTargetsOptimization(priority));
  34215. // Next priority
  34216. priority++;
  34217. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  34218. return result;
  34219. };
  34220. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  34221. var result = new SceneOptimizerOptions(targetFrameRate);
  34222. var priority = 0;
  34223. result.optimizations.push(new MergeMeshesOptimization(priority));
  34224. result.optimizations.push(new ShadowsOptimization(priority));
  34225. result.optimizations.push(new LensFlaresOptimization(priority));
  34226. // Next priority
  34227. priority++;
  34228. result.optimizations.push(new PostProcessesOptimization(priority));
  34229. result.optimizations.push(new ParticlesOptimization(priority));
  34230. // Next priority
  34231. priority++;
  34232. result.optimizations.push(new TextureOptimization(priority, 256));
  34233. // Next priority
  34234. priority++;
  34235. result.optimizations.push(new RenderTargetsOptimization(priority));
  34236. // Next priority
  34237. priority++;
  34238. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34239. return result;
  34240. };
  34241. return SceneOptimizerOptions;
  34242. })();
  34243. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34244. // Scene optimizer tool
  34245. var SceneOptimizer = (function () {
  34246. function SceneOptimizer() {
  34247. }
  34248. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34249. // TODO: add an epsilon
  34250. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34251. if (onSuccess) {
  34252. onSuccess();
  34253. }
  34254. return;
  34255. }
  34256. // Apply current level of optimizations
  34257. var allDone = true;
  34258. var noOptimizationApplied = true;
  34259. for (var index = 0; index < options.optimizations.length; index++) {
  34260. var optimization = options.optimizations[index];
  34261. if (optimization.priority === currentPriorityLevel) {
  34262. noOptimizationApplied = false;
  34263. allDone = allDone && optimization.apply(scene);
  34264. }
  34265. }
  34266. // If no optimization was applied, this is a failure :(
  34267. if (noOptimizationApplied) {
  34268. if (onFailure) {
  34269. onFailure();
  34270. }
  34271. return;
  34272. }
  34273. // If all optimizations were done, move to next level
  34274. if (allDone) {
  34275. currentPriorityLevel++;
  34276. }
  34277. // Let's the system running for a specific amount of time before checking FPS
  34278. scene.executeWhenReady(function () {
  34279. setTimeout(function () {
  34280. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34281. }, options.trackerDuration);
  34282. });
  34283. };
  34284. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34285. if (!options) {
  34286. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34287. }
  34288. // Let's the system running for a specific amount of time before checking FPS
  34289. scene.executeWhenReady(function () {
  34290. setTimeout(function () {
  34291. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34292. }, options.trackerDuration);
  34293. });
  34294. };
  34295. return SceneOptimizer;
  34296. })();
  34297. BABYLON.SceneOptimizer = SceneOptimizer;
  34298. })(BABYLON || (BABYLON = {}));
  34299. var BABYLON;
  34300. (function (BABYLON) {
  34301. var Internals;
  34302. (function (Internals) {
  34303. var MeshLODLevel = (function () {
  34304. function MeshLODLevel(distance, mesh) {
  34305. this.distance = distance;
  34306. this.mesh = mesh;
  34307. }
  34308. return MeshLODLevel;
  34309. })();
  34310. Internals.MeshLODLevel = MeshLODLevel;
  34311. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34312. })(BABYLON || (BABYLON = {}));
  34313. var BABYLON;
  34314. (function (BABYLON) {
  34315. var RawTexture = (function (_super) {
  34316. __extends(RawTexture, _super);
  34317. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34319. if (invertY === void 0) { invertY = false; }
  34320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34321. _super.call(this, null, scene, !generateMipMaps, invertY);
  34322. this.format = format;
  34323. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34324. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34325. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34326. }
  34327. RawTexture.prototype.update = function (data) {
  34328. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34329. };
  34330. // Statics
  34331. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34332. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34333. if (invertY === void 0) { invertY = false; }
  34334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34335. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34336. };
  34337. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34338. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34339. if (invertY === void 0) { invertY = false; }
  34340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34341. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34342. };
  34343. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34344. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34345. if (invertY === void 0) { invertY = false; }
  34346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34347. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34348. };
  34349. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34350. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34351. if (invertY === void 0) { invertY = false; }
  34352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34353. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34354. };
  34355. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34356. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34357. if (invertY === void 0) { invertY = false; }
  34358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34359. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34360. };
  34361. return RawTexture;
  34362. })(BABYLON.Texture);
  34363. BABYLON.RawTexture = RawTexture;
  34364. })(BABYLON || (BABYLON = {}));
  34365. var BABYLON;
  34366. (function (BABYLON) {
  34367. var IndexedVector2 = (function (_super) {
  34368. __extends(IndexedVector2, _super);
  34369. function IndexedVector2(original, index) {
  34370. _super.call(this, original.x, original.y);
  34371. this.index = index;
  34372. }
  34373. return IndexedVector2;
  34374. })(BABYLON.Vector2);
  34375. var PolygonPoints = (function () {
  34376. function PolygonPoints() {
  34377. this.elements = new Array();
  34378. }
  34379. PolygonPoints.prototype.add = function (originalPoints) {
  34380. var _this = this;
  34381. var result = new Array();
  34382. originalPoints.forEach(function (point) {
  34383. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34384. var newPoint = new IndexedVector2(point, _this.elements.length);
  34385. result.push(newPoint);
  34386. _this.elements.push(newPoint);
  34387. }
  34388. });
  34389. return result;
  34390. };
  34391. PolygonPoints.prototype.computeBounds = function () {
  34392. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34393. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34394. this.elements.forEach(function (point) {
  34395. // x
  34396. if (point.x < lmin.x) {
  34397. lmin.x = point.x;
  34398. }
  34399. else if (point.x > lmax.x) {
  34400. lmax.x = point.x;
  34401. }
  34402. // y
  34403. if (point.y < lmin.y) {
  34404. lmin.y = point.y;
  34405. }
  34406. else if (point.y > lmax.y) {
  34407. lmax.y = point.y;
  34408. }
  34409. });
  34410. return {
  34411. min: lmin,
  34412. max: lmax,
  34413. width: lmax.x - lmin.x,
  34414. height: lmax.y - lmin.y
  34415. };
  34416. };
  34417. return PolygonPoints;
  34418. })();
  34419. var Polygon = (function () {
  34420. function Polygon() {
  34421. }
  34422. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34423. return [
  34424. new BABYLON.Vector2(xmin, ymin),
  34425. new BABYLON.Vector2(xmax, ymin),
  34426. new BABYLON.Vector2(xmax, ymax),
  34427. new BABYLON.Vector2(xmin, ymax)
  34428. ];
  34429. };
  34430. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34431. if (cx === void 0) { cx = 0; }
  34432. if (cy === void 0) { cy = 0; }
  34433. if (numberOfSides === void 0) { numberOfSides = 32; }
  34434. var result = new Array();
  34435. var angle = 0;
  34436. var increment = (Math.PI * 2) / numberOfSides;
  34437. for (var i = 0; i < numberOfSides; i++) {
  34438. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34439. angle -= increment;
  34440. }
  34441. return result;
  34442. };
  34443. Polygon.Parse = function (input) {
  34444. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34445. var i, result = [];
  34446. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34447. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34448. }
  34449. return result;
  34450. };
  34451. Polygon.StartingAt = function (x, y) {
  34452. return BABYLON.Path2.StartingAt(x, y);
  34453. };
  34454. return Polygon;
  34455. })();
  34456. BABYLON.Polygon = Polygon;
  34457. var PolygonMeshBuilder = (function () {
  34458. function PolygonMeshBuilder(name, contours, scene) {
  34459. this._points = new PolygonPoints();
  34460. this._outlinepoints = new PolygonPoints();
  34461. this._holes = [];
  34462. if (!("poly2tri" in window)) {
  34463. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34464. }
  34465. this._name = name;
  34466. this._scene = scene;
  34467. var points;
  34468. if (contours instanceof BABYLON.Path2) {
  34469. points = contours.getPoints();
  34470. }
  34471. else {
  34472. points = contours;
  34473. }
  34474. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34475. this._outlinepoints.add(points);
  34476. }
  34477. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34478. this._swctx.addHole(this._points.add(hole));
  34479. var holepoints = new PolygonPoints();
  34480. holepoints.add(hole);
  34481. this._holes.push(holepoints);
  34482. return this;
  34483. };
  34484. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34485. var _this = this;
  34486. if (updatable === void 0) { updatable = false; }
  34487. var result = new BABYLON.Mesh(this._name, this._scene);
  34488. var normals = [];
  34489. var positions = [];
  34490. var uvs = [];
  34491. var bounds = this._points.computeBounds();
  34492. this._points.elements.forEach(function (p) {
  34493. normals.push(0, 1.0, 0);
  34494. positions.push(p.x, 0, p.y);
  34495. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34496. });
  34497. var indices = [];
  34498. this._swctx.triangulate();
  34499. this._swctx.getTriangles().forEach(function (triangle) {
  34500. triangle.getPoints().forEach(function (point) {
  34501. indices.push(point.index);
  34502. });
  34503. });
  34504. if (depth > 0) {
  34505. var positionscount = (positions.length / 3); //get the current pointcount
  34506. this._points.elements.forEach(function (p) {
  34507. normals.push(0, -1.0, 0);
  34508. positions.push(p.x, -depth, p.y);
  34509. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34510. });
  34511. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34512. var p2;
  34513. var poscounter = 0;
  34514. this._swctx.getTriangles().forEach(function (triangle) {
  34515. triangle.getPoints().forEach(function (point) {
  34516. switch (poscounter) {
  34517. case 0:
  34518. p1 = point;
  34519. break;
  34520. case 1:
  34521. p2 = point;
  34522. break;
  34523. case 2:
  34524. indices.push(point.index + positionscount);
  34525. indices.push(p2.index + positionscount);
  34526. indices.push(p1.index + positionscount);
  34527. poscounter = -1;
  34528. break;
  34529. }
  34530. poscounter++;
  34531. //indices.push((<IndexedVector2>point).index + positionscount);
  34532. });
  34533. });
  34534. //Add the sides
  34535. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34536. this._holes.forEach(function (hole) {
  34537. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34538. });
  34539. }
  34540. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34541. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34542. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34543. result.setIndices(indices);
  34544. return result;
  34545. };
  34546. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34547. var StartIndex = positions.length / 3;
  34548. var ulength = 0;
  34549. for (var i = 0; i < points.elements.length; i++) {
  34550. var p = points.elements[i];
  34551. var p1;
  34552. if ((i + 1) > points.elements.length - 1) {
  34553. p1 = points.elements[0];
  34554. }
  34555. else {
  34556. p1 = points.elements[i + 1];
  34557. }
  34558. positions.push(p.x, 0, p.y);
  34559. positions.push(p.x, -depth, p.y);
  34560. positions.push(p1.x, 0, p1.y);
  34561. positions.push(p1.x, -depth, p1.y);
  34562. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34563. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34564. var v3 = v2.subtract(v1);
  34565. var v4 = new BABYLON.Vector3(0, 1, 0);
  34566. var vn = BABYLON.Vector3.Cross(v3, v4);
  34567. vn = vn.normalize();
  34568. uvs.push(ulength / bounds.width, 0);
  34569. uvs.push(ulength / bounds.width, 1);
  34570. ulength += v3.length();
  34571. uvs.push((ulength / bounds.width), 0);
  34572. uvs.push((ulength / bounds.width), 1);
  34573. if (!flip) {
  34574. normals.push(-vn.x, -vn.y, -vn.z);
  34575. normals.push(-vn.x, -vn.y, -vn.z);
  34576. normals.push(-vn.x, -vn.y, -vn.z);
  34577. normals.push(-vn.x, -vn.y, -vn.z);
  34578. indices.push(StartIndex);
  34579. indices.push(StartIndex + 1);
  34580. indices.push(StartIndex + 2);
  34581. indices.push(StartIndex + 1);
  34582. indices.push(StartIndex + 3);
  34583. indices.push(StartIndex + 2);
  34584. }
  34585. else {
  34586. normals.push(vn.x, vn.y, vn.z);
  34587. normals.push(vn.x, vn.y, vn.z);
  34588. normals.push(vn.x, vn.y, vn.z);
  34589. normals.push(vn.x, vn.y, vn.z);
  34590. indices.push(StartIndex);
  34591. indices.push(StartIndex + 2);
  34592. indices.push(StartIndex + 1);
  34593. indices.push(StartIndex + 1);
  34594. indices.push(StartIndex + 2);
  34595. indices.push(StartIndex + 3);
  34596. }
  34597. StartIndex += 4;
  34598. }
  34599. ;
  34600. };
  34601. return PolygonMeshBuilder;
  34602. })();
  34603. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34604. })(BABYLON || (BABYLON = {}));
  34605. var BABYLON;
  34606. (function (BABYLON) {
  34607. var Octree = (function () {
  34608. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34609. if (maxDepth === void 0) { maxDepth = 2; }
  34610. this.maxDepth = maxDepth;
  34611. this.dynamicContent = new Array();
  34612. this._maxBlockCapacity = maxBlockCapacity || 64;
  34613. this._selectionContent = new BABYLON.SmartArray(1024);
  34614. this._creationFunc = creationFunc;
  34615. }
  34616. // Methods
  34617. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34618. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34619. };
  34620. Octree.prototype.addMesh = function (entry) {
  34621. for (var index = 0; index < this.blocks.length; index++) {
  34622. var block = this.blocks[index];
  34623. block.addEntry(entry);
  34624. }
  34625. };
  34626. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34627. this._selectionContent.reset();
  34628. for (var index = 0; index < this.blocks.length; index++) {
  34629. var block = this.blocks[index];
  34630. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34631. }
  34632. if (allowDuplicate) {
  34633. this._selectionContent.concat(this.dynamicContent);
  34634. }
  34635. else {
  34636. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34637. }
  34638. return this._selectionContent;
  34639. };
  34640. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34641. this._selectionContent.reset();
  34642. for (var index = 0; index < this.blocks.length; index++) {
  34643. var block = this.blocks[index];
  34644. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34645. }
  34646. if (allowDuplicate) {
  34647. this._selectionContent.concat(this.dynamicContent);
  34648. }
  34649. else {
  34650. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34651. }
  34652. return this._selectionContent;
  34653. };
  34654. Octree.prototype.intersectsRay = function (ray) {
  34655. this._selectionContent.reset();
  34656. for (var index = 0; index < this.blocks.length; index++) {
  34657. var block = this.blocks[index];
  34658. block.intersectsRay(ray, this._selectionContent);
  34659. }
  34660. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34661. return this._selectionContent;
  34662. };
  34663. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34664. target.blocks = new Array();
  34665. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34666. // Segmenting space
  34667. for (var x = 0; x < 2; x++) {
  34668. for (var y = 0; y < 2; y++) {
  34669. for (var z = 0; z < 2; z++) {
  34670. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34671. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34672. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34673. block.addEntries(entries);
  34674. target.blocks.push(block);
  34675. }
  34676. }
  34677. }
  34678. };
  34679. Octree.CreationFuncForMeshes = function (entry, block) {
  34680. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34681. block.entries.push(entry);
  34682. }
  34683. };
  34684. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34685. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34686. block.entries.push(entry);
  34687. }
  34688. };
  34689. return Octree;
  34690. })();
  34691. BABYLON.Octree = Octree;
  34692. })(BABYLON || (BABYLON = {}));
  34693. var BABYLON;
  34694. (function (BABYLON) {
  34695. var OctreeBlock = (function () {
  34696. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34697. this.entries = new Array();
  34698. this._boundingVectors = new Array();
  34699. this._capacity = capacity;
  34700. this._depth = depth;
  34701. this._maxDepth = maxDepth;
  34702. this._creationFunc = creationFunc;
  34703. this._minPoint = minPoint;
  34704. this._maxPoint = maxPoint;
  34705. this._boundingVectors.push(minPoint.clone());
  34706. this._boundingVectors.push(maxPoint.clone());
  34707. this._boundingVectors.push(minPoint.clone());
  34708. this._boundingVectors[2].x = maxPoint.x;
  34709. this._boundingVectors.push(minPoint.clone());
  34710. this._boundingVectors[3].y = maxPoint.y;
  34711. this._boundingVectors.push(minPoint.clone());
  34712. this._boundingVectors[4].z = maxPoint.z;
  34713. this._boundingVectors.push(maxPoint.clone());
  34714. this._boundingVectors[5].z = minPoint.z;
  34715. this._boundingVectors.push(maxPoint.clone());
  34716. this._boundingVectors[6].x = minPoint.x;
  34717. this._boundingVectors.push(maxPoint.clone());
  34718. this._boundingVectors[7].y = minPoint.y;
  34719. }
  34720. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34721. // Property
  34722. get: function () {
  34723. return this._capacity;
  34724. },
  34725. enumerable: true,
  34726. configurable: true
  34727. });
  34728. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34729. get: function () {
  34730. return this._minPoint;
  34731. },
  34732. enumerable: true,
  34733. configurable: true
  34734. });
  34735. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34736. get: function () {
  34737. return this._maxPoint;
  34738. },
  34739. enumerable: true,
  34740. configurable: true
  34741. });
  34742. // Methods
  34743. OctreeBlock.prototype.addEntry = function (entry) {
  34744. if (this.blocks) {
  34745. for (var index = 0; index < this.blocks.length; index++) {
  34746. var block = this.blocks[index];
  34747. block.addEntry(entry);
  34748. }
  34749. return;
  34750. }
  34751. this._creationFunc(entry, this);
  34752. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34753. this.createInnerBlocks();
  34754. }
  34755. };
  34756. OctreeBlock.prototype.addEntries = function (entries) {
  34757. for (var index = 0; index < entries.length; index++) {
  34758. var mesh = entries[index];
  34759. this.addEntry(mesh);
  34760. }
  34761. };
  34762. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34763. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34764. if (this.blocks) {
  34765. for (var index = 0; index < this.blocks.length; index++) {
  34766. var block = this.blocks[index];
  34767. block.select(frustumPlanes, selection, allowDuplicate);
  34768. }
  34769. return;
  34770. }
  34771. if (allowDuplicate) {
  34772. selection.concat(this.entries);
  34773. }
  34774. else {
  34775. selection.concatWithNoDuplicate(this.entries);
  34776. }
  34777. }
  34778. };
  34779. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34780. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34781. if (this.blocks) {
  34782. for (var index = 0; index < this.blocks.length; index++) {
  34783. var block = this.blocks[index];
  34784. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34785. }
  34786. return;
  34787. }
  34788. if (allowDuplicate) {
  34789. selection.concat(this.entries);
  34790. }
  34791. else {
  34792. selection.concatWithNoDuplicate(this.entries);
  34793. }
  34794. }
  34795. };
  34796. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34797. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34798. if (this.blocks) {
  34799. for (var index = 0; index < this.blocks.length; index++) {
  34800. var block = this.blocks[index];
  34801. block.intersectsRay(ray, selection);
  34802. }
  34803. return;
  34804. }
  34805. selection.concatWithNoDuplicate(this.entries);
  34806. }
  34807. };
  34808. OctreeBlock.prototype.createInnerBlocks = function () {
  34809. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34810. };
  34811. return OctreeBlock;
  34812. })();
  34813. BABYLON.OctreeBlock = OctreeBlock;
  34814. })(BABYLON || (BABYLON = {}));
  34815. var BABYLON;
  34816. (function (BABYLON) {
  34817. var BlurPostProcess = (function (_super) {
  34818. __extends(BlurPostProcess, _super);
  34819. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34820. var _this = this;
  34821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34822. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34823. this.direction = direction;
  34824. this.blurWidth = blurWidth;
  34825. this.onApply = function (effect) {
  34826. effect.setFloat2("screenSize", _this.width, _this.height);
  34827. effect.setVector2("direction", _this.direction);
  34828. effect.setFloat("blurWidth", _this.blurWidth);
  34829. };
  34830. }
  34831. return BlurPostProcess;
  34832. })(BABYLON.PostProcess);
  34833. BABYLON.BlurPostProcess = BlurPostProcess;
  34834. })(BABYLON || (BABYLON = {}));
  34835. var BABYLON;
  34836. (function (BABYLON) {
  34837. var RefractionPostProcess = (function (_super) {
  34838. __extends(RefractionPostProcess, _super);
  34839. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34840. var _this = this;
  34841. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34842. this.color = color;
  34843. this.depth = depth;
  34844. this.colorLevel = colorLevel;
  34845. this.onActivate = function (cam) {
  34846. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34847. };
  34848. this.onApply = function (effect) {
  34849. effect.setColor3("baseColor", _this.color);
  34850. effect.setFloat("depth", _this.depth);
  34851. effect.setFloat("colorLevel", _this.colorLevel);
  34852. effect.setTexture("refractionSampler", _this._refRexture);
  34853. };
  34854. }
  34855. // Methods
  34856. RefractionPostProcess.prototype.dispose = function (camera) {
  34857. if (this._refRexture) {
  34858. this._refRexture.dispose();
  34859. }
  34860. _super.prototype.dispose.call(this, camera);
  34861. };
  34862. return RefractionPostProcess;
  34863. })(BABYLON.PostProcess);
  34864. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34865. })(BABYLON || (BABYLON = {}));
  34866. var BABYLON;
  34867. (function (BABYLON) {
  34868. var BlackAndWhitePostProcess = (function (_super) {
  34869. __extends(BlackAndWhitePostProcess, _super);
  34870. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34871. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34872. }
  34873. return BlackAndWhitePostProcess;
  34874. })(BABYLON.PostProcess);
  34875. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34876. })(BABYLON || (BABYLON = {}));
  34877. var BABYLON;
  34878. (function (BABYLON) {
  34879. var ConvolutionPostProcess = (function (_super) {
  34880. __extends(ConvolutionPostProcess, _super);
  34881. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34882. var _this = this;
  34883. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34884. this.kernel = kernel;
  34885. this.onApply = function (effect) {
  34886. effect.setFloat2("screenSize", _this.width, _this.height);
  34887. effect.setArray("kernel", _this.kernel);
  34888. };
  34889. }
  34890. // Statics
  34891. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34892. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34893. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34894. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34895. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34896. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34897. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34898. return ConvolutionPostProcess;
  34899. })(BABYLON.PostProcess);
  34900. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34901. })(BABYLON || (BABYLON = {}));
  34902. var BABYLON;
  34903. (function (BABYLON) {
  34904. var FilterPostProcess = (function (_super) {
  34905. __extends(FilterPostProcess, _super);
  34906. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34907. var _this = this;
  34908. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34909. this.kernelMatrix = kernelMatrix;
  34910. this.onApply = function (effect) {
  34911. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34912. };
  34913. }
  34914. return FilterPostProcess;
  34915. })(BABYLON.PostProcess);
  34916. BABYLON.FilterPostProcess = FilterPostProcess;
  34917. })(BABYLON || (BABYLON = {}));
  34918. var BABYLON;
  34919. (function (BABYLON) {
  34920. var FxaaPostProcess = (function (_super) {
  34921. __extends(FxaaPostProcess, _super);
  34922. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34923. var _this = this;
  34924. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34925. this.onSizeChanged = function () {
  34926. _this.texelWidth = 1.0 / _this.width;
  34927. _this.texelHeight = 1.0 / _this.height;
  34928. };
  34929. this.onApply = function (effect) {
  34930. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34931. };
  34932. }
  34933. return FxaaPostProcess;
  34934. })(BABYLON.PostProcess);
  34935. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34936. })(BABYLON || (BABYLON = {}));
  34937. var BABYLON;
  34938. (function (BABYLON) {
  34939. var StereoscopicInterlacePostProcess = (function (_super) {
  34940. __extends(StereoscopicInterlacePostProcess, _super);
  34941. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34942. var _this = this;
  34943. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34944. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34945. this.onSizeChanged = function () {
  34946. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34947. };
  34948. this.onApply = function (effect) {
  34949. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34950. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34951. };
  34952. }
  34953. return StereoscopicInterlacePostProcess;
  34954. })(BABYLON.PostProcess);
  34955. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34956. })(BABYLON || (BABYLON = {}));
  34957. var BABYLON;
  34958. (function (BABYLON) {
  34959. var LensFlare = (function () {
  34960. function LensFlare(size, position, color, imgUrl, system) {
  34961. this.size = size;
  34962. this.position = position;
  34963. this.dispose = function () {
  34964. if (this.texture) {
  34965. this.texture.dispose();
  34966. }
  34967. // Remove from scene
  34968. var index = this._system.lensFlares.indexOf(this);
  34969. this._system.lensFlares.splice(index, 1);
  34970. };
  34971. this.color = color || new BABYLON.Color3(1, 1, 1);
  34972. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34973. this._system = system;
  34974. system.lensFlares.push(this);
  34975. }
  34976. return LensFlare;
  34977. })();
  34978. BABYLON.LensFlare = LensFlare;
  34979. })(BABYLON || (BABYLON = {}));
  34980. var BABYLON;
  34981. (function (BABYLON) {
  34982. var LensFlareSystem = (function () {
  34983. function LensFlareSystem(name, emitter, scene) {
  34984. this.name = name;
  34985. this.lensFlares = new Array();
  34986. this.borderLimit = 300;
  34987. this.layerMask = 0x0FFFFFFF;
  34988. this._vertexDeclaration = [2];
  34989. this._vertexStrideSize = 2 * 4;
  34990. this._isEnabled = true;
  34991. this._scene = scene;
  34992. this._emitter = emitter;
  34993. scene.lensFlareSystems.push(this);
  34994. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34995. // VBO
  34996. var vertices = [];
  34997. vertices.push(1, 1);
  34998. vertices.push(-1, 1);
  34999. vertices.push(-1, -1);
  35000. vertices.push(1, -1);
  35001. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  35002. // Indices
  35003. var indices = [];
  35004. indices.push(0);
  35005. indices.push(1);
  35006. indices.push(2);
  35007. indices.push(0);
  35008. indices.push(2);
  35009. indices.push(3);
  35010. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  35011. // Effects
  35012. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  35013. }
  35014. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  35015. get: function () {
  35016. return this._isEnabled;
  35017. },
  35018. set: function (value) {
  35019. this._isEnabled = value;
  35020. },
  35021. enumerable: true,
  35022. configurable: true
  35023. });
  35024. LensFlareSystem.prototype.getScene = function () {
  35025. return this._scene;
  35026. };
  35027. LensFlareSystem.prototype.getEmitter = function () {
  35028. return this._emitter;
  35029. };
  35030. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  35031. this._emitter = newEmitter;
  35032. };
  35033. LensFlareSystem.prototype.getEmitterPosition = function () {
  35034. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  35035. };
  35036. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  35037. var position = this.getEmitterPosition();
  35038. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  35039. this._positionX = position.x;
  35040. this._positionY = position.y;
  35041. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  35042. if (position.z > 0) {
  35043. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  35044. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  35045. return true;
  35046. }
  35047. }
  35048. return false;
  35049. };
  35050. LensFlareSystem.prototype._isVisible = function () {
  35051. if (!this._isEnabled) {
  35052. return false;
  35053. }
  35054. var emitterPosition = this.getEmitterPosition();
  35055. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  35056. var distance = direction.length();
  35057. direction.normalize();
  35058. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  35059. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  35060. return !pickInfo.hit || pickInfo.distance > distance;
  35061. };
  35062. LensFlareSystem.prototype.render = function () {
  35063. if (!this._effect.isReady())
  35064. return false;
  35065. var engine = this._scene.getEngine();
  35066. var viewport = this._scene.activeCamera.viewport;
  35067. var globalViewport = viewport.toScreenGlobal(engine);
  35068. // Position
  35069. if (!this.computeEffectivePosition(globalViewport)) {
  35070. return false;
  35071. }
  35072. // Visibility
  35073. if (!this._isVisible()) {
  35074. return false;
  35075. }
  35076. // Intensity
  35077. var awayX;
  35078. var awayY;
  35079. if (this._positionX < this.borderLimit + globalViewport.x) {
  35080. awayX = this.borderLimit + globalViewport.x - this._positionX;
  35081. }
  35082. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  35083. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  35084. }
  35085. else {
  35086. awayX = 0;
  35087. }
  35088. if (this._positionY < this.borderLimit + globalViewport.y) {
  35089. awayY = this.borderLimit + globalViewport.y - this._positionY;
  35090. }
  35091. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  35092. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  35093. }
  35094. else {
  35095. awayY = 0;
  35096. }
  35097. var away = (awayX > awayY) ? awayX : awayY;
  35098. if (away > this.borderLimit) {
  35099. away = this.borderLimit;
  35100. }
  35101. var intensity = 1.0 - (away / this.borderLimit);
  35102. if (intensity < 0) {
  35103. return false;
  35104. }
  35105. if (intensity > 1.0) {
  35106. intensity = 1.0;
  35107. }
  35108. // Position
  35109. var centerX = globalViewport.x + globalViewport.width / 2;
  35110. var centerY = globalViewport.y + globalViewport.height / 2;
  35111. var distX = centerX - this._positionX;
  35112. var distY = centerY - this._positionY;
  35113. // Effects
  35114. engine.enableEffect(this._effect);
  35115. engine.setState(false);
  35116. engine.setDepthBuffer(false);
  35117. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35118. // VBOs
  35119. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  35120. // Flares
  35121. for (var index = 0; index < this.lensFlares.length; index++) {
  35122. var flare = this.lensFlares[index];
  35123. var x = centerX - (distX * flare.position);
  35124. var y = centerY - (distY * flare.position);
  35125. var cw = flare.size;
  35126. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  35127. var cx = 2 * (x / globalViewport.width) - 1.0;
  35128. var cy = 1.0 - 2 * (y / globalViewport.height);
  35129. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  35130. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  35131. // Texture
  35132. this._effect.setTexture("textureSampler", flare.texture);
  35133. // Color
  35134. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  35135. // Draw order
  35136. engine.draw(true, 0, 6);
  35137. }
  35138. engine.setDepthBuffer(true);
  35139. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35140. return true;
  35141. };
  35142. LensFlareSystem.prototype.dispose = function () {
  35143. if (this._vertexBuffer) {
  35144. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  35145. this._vertexBuffer = null;
  35146. }
  35147. if (this._indexBuffer) {
  35148. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35149. this._indexBuffer = null;
  35150. }
  35151. while (this.lensFlares.length) {
  35152. this.lensFlares[0].dispose();
  35153. }
  35154. // Remove from scene
  35155. var index = this._scene.lensFlareSystems.indexOf(this);
  35156. this._scene.lensFlareSystems.splice(index, 1);
  35157. };
  35158. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  35159. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  35160. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  35161. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  35162. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  35163. var parsedFlare = parsedLensFlareSystem.flares[index];
  35164. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  35165. }
  35166. return lensFlareSystem;
  35167. };
  35168. LensFlareSystem.prototype.serialize = function () {
  35169. var serializationObject = {};
  35170. serializationObject.emitterId = this.getEmitter().id;
  35171. serializationObject.borderLimit = this.borderLimit;
  35172. serializationObject.flares = [];
  35173. for (var index = 0; index < this.lensFlares.length; index++) {
  35174. var flare = this.lensFlares[index];
  35175. serializationObject.flares.push({
  35176. size: flare.size,
  35177. position: flare.position,
  35178. color: flare.color.asArray(),
  35179. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  35180. });
  35181. }
  35182. return serializationObject;
  35183. };
  35184. return LensFlareSystem;
  35185. })();
  35186. BABYLON.LensFlareSystem = LensFlareSystem;
  35187. })(BABYLON || (BABYLON = {}));
  35188. var BABYLON;
  35189. (function (BABYLON) {
  35190. // We're mainly based on the logic defined into the FreeCamera code
  35191. var DeviceOrientationCamera = (function (_super) {
  35192. __extends(DeviceOrientationCamera, _super);
  35193. function DeviceOrientationCamera(name, position, scene) {
  35194. var _this = this;
  35195. _super.call(this, name, position, scene);
  35196. this._offsetX = null;
  35197. this._offsetY = null;
  35198. this._orientationGamma = 0;
  35199. this._orientationBeta = 0;
  35200. this._initialOrientationGamma = 0;
  35201. this._initialOrientationBeta = 0;
  35202. this.angularSensibility = 10000.0;
  35203. this.moveSensibility = 50.0;
  35204. window.addEventListener("resize", function () {
  35205. _this._initialOrientationGamma = null;
  35206. }, false);
  35207. }
  35208. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35209. var _this = this;
  35210. if (this._attachedCanvas) {
  35211. return;
  35212. }
  35213. this._attachedCanvas = canvas;
  35214. if (!this._orientationChanged) {
  35215. this._orientationChanged = function (evt) {
  35216. if (!_this._initialOrientationGamma) {
  35217. _this._initialOrientationGamma = evt.gamma;
  35218. _this._initialOrientationBeta = evt.beta;
  35219. }
  35220. _this._orientationGamma = evt.gamma;
  35221. _this._orientationBeta = evt.beta;
  35222. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  35223. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  35224. };
  35225. }
  35226. window.addEventListener("deviceorientation", this._orientationChanged);
  35227. };
  35228. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  35229. if (this._attachedCanvas !== canvas) {
  35230. return;
  35231. }
  35232. window.removeEventListener("deviceorientation", this._orientationChanged);
  35233. this._attachedCanvas = null;
  35234. this._orientationGamma = 0;
  35235. this._orientationBeta = 0;
  35236. this._initialOrientationGamma = 0;
  35237. this._initialOrientationBeta = 0;
  35238. };
  35239. DeviceOrientationCamera.prototype._checkInputs = function () {
  35240. if (!this._offsetX) {
  35241. return;
  35242. }
  35243. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35244. var speed = this._computeLocalCameraSpeed();
  35245. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35246. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35247. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35248. _super.prototype._checkInputs.call(this);
  35249. };
  35250. DeviceOrientationCamera.prototype.getTypeName = function () {
  35251. return "DeviceOrientationCamera";
  35252. };
  35253. __decorate([
  35254. BABYLON.serialize()
  35255. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35256. __decorate([
  35257. BABYLON.serialize()
  35258. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35259. return DeviceOrientationCamera;
  35260. })(BABYLON.FreeCamera);
  35261. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35262. })(BABYLON || (BABYLON = {}));
  35263. var BABYLON;
  35264. (function (BABYLON) {
  35265. // We're mainly based on the logic defined into the FreeCamera code
  35266. var UniversalCamera = (function (_super) {
  35267. __extends(UniversalCamera, _super);
  35268. function UniversalCamera(name, position, scene) {
  35269. var _this = this;
  35270. _super.call(this, name, position, scene);
  35271. this.gamepadAngularSensibility = 200;
  35272. this.gamepadMoveSensibility = 40;
  35273. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  35274. }
  35275. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  35276. // Only the first gamepad can control the camera
  35277. if (gamepad.index === 0) {
  35278. this.gamepad = gamepad;
  35279. }
  35280. };
  35281. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35282. _super.prototype.attachControl.call(this, canvas, false);
  35283. };
  35284. UniversalCamera.prototype.detachControl = function (canvas) {
  35285. _super.prototype.detachControl.call(this, canvas);
  35286. };
  35287. UniversalCamera.prototype._checkInputs = function () {
  35288. if (this.gamepad) {
  35289. var LSValues = this.gamepad.leftStick;
  35290. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  35291. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  35292. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  35293. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  35294. var RSValues = this.gamepad.rightStick;
  35295. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  35296. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  35297. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  35298. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  35299. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  35300. var speed = this._computeLocalCameraSpeed() * 50.0;
  35301. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  35302. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  35303. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  35304. }
  35305. _super.prototype._checkInputs.call(this);
  35306. };
  35307. UniversalCamera.prototype.dispose = function () {
  35308. this._gamepads.dispose();
  35309. _super.prototype.dispose.call(this);
  35310. };
  35311. UniversalCamera.prototype.getTypeName = function () {
  35312. return "UniversalCamera";
  35313. };
  35314. __decorate([
  35315. BABYLON.serialize()
  35316. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  35317. __decorate([
  35318. BABYLON.serialize()
  35319. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  35320. return UniversalCamera;
  35321. })(BABYLON.TouchCamera);
  35322. BABYLON.UniversalCamera = UniversalCamera;
  35323. })(BABYLON || (BABYLON = {}));
  35324. var BABYLON;
  35325. (function (BABYLON) {
  35326. var Gamepads = (function () {
  35327. function Gamepads(ongamedpadconnected) {
  35328. var _this = this;
  35329. this.babylonGamepads = [];
  35330. this.oneGamepadConnected = false;
  35331. this.isMonitoring = false;
  35332. this.gamepadEventSupported = 'GamepadEvent' in window;
  35333. this.gamepadSupportAvailable = (navigator.getGamepads ||
  35334. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  35335. this._callbackGamepadConnected = ongamedpadconnected;
  35336. if (this.gamepadSupportAvailable) {
  35337. // Checking if the gamepad connected event is supported (like in Firefox)
  35338. if (this.gamepadEventSupported) {
  35339. window.addEventListener('gamepadconnected', function (evt) {
  35340. _this._onGamepadConnected(evt);
  35341. }, false);
  35342. window.addEventListener('gamepaddisconnected', function (evt) {
  35343. _this._onGamepadDisconnected(evt);
  35344. }, false);
  35345. }
  35346. else {
  35347. this._startMonitoringGamepads();
  35348. }
  35349. }
  35350. }
  35351. Gamepads.prototype.dispose = function () {
  35352. if (Gamepads.gamepadDOMInfo) {
  35353. document.body.removeChild(Gamepads.gamepadDOMInfo);
  35354. }
  35355. };
  35356. Gamepads.prototype._onGamepadConnected = function (evt) {
  35357. var newGamepad = this._addNewGamepad(evt.gamepad);
  35358. if (this._callbackGamepadConnected)
  35359. this._callbackGamepadConnected(newGamepad);
  35360. this._startMonitoringGamepads();
  35361. };
  35362. Gamepads.prototype._addNewGamepad = function (gamepad) {
  35363. if (!this.oneGamepadConnected) {
  35364. this.oneGamepadConnected = true;
  35365. if (Gamepads.gamepadDOMInfo) {
  35366. document.body.removeChild(Gamepads.gamepadDOMInfo);
  35367. Gamepads.gamepadDOMInfo = null;
  35368. }
  35369. }
  35370. var newGamepad;
  35371. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  35372. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  35373. }
  35374. else {
  35375. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  35376. }
  35377. this.babylonGamepads.push(newGamepad);
  35378. return newGamepad;
  35379. };
  35380. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  35381. // Remove the gamepad from the list of gamepads to monitor.
  35382. for (var i in this.babylonGamepads) {
  35383. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  35384. this.babylonGamepads.splice(i, 1);
  35385. break;
  35386. }
  35387. }
  35388. // If no gamepads are left, stop the polling loop.
  35389. if (this.babylonGamepads.length == 0) {
  35390. this._stopMonitoringGamepads();
  35391. }
  35392. };
  35393. Gamepads.prototype._startMonitoringGamepads = function () {
  35394. if (!this.isMonitoring) {
  35395. this.isMonitoring = true;
  35396. this._checkGamepadsStatus();
  35397. }
  35398. };
  35399. Gamepads.prototype._stopMonitoringGamepads = function () {
  35400. this.isMonitoring = false;
  35401. };
  35402. Gamepads.prototype._checkGamepadsStatus = function () {
  35403. var _this = this;
  35404. // updating gamepad objects
  35405. this._updateGamepadObjects();
  35406. for (var i in this.babylonGamepads) {
  35407. this.babylonGamepads[i].update();
  35408. }
  35409. if (this.isMonitoring) {
  35410. if (window.requestAnimationFrame) {
  35411. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35412. }
  35413. else if (window.mozRequestAnimationFrame) {
  35414. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35415. }
  35416. else if (window.webkitRequestAnimationFrame) {
  35417. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35418. }
  35419. }
  35420. };
  35421. // This function is called only on Chrome, which does not yet support
  35422. // connection/disconnection events, but requires you to monitor
  35423. // an array for changes.
  35424. Gamepads.prototype._updateGamepadObjects = function () {
  35425. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  35426. for (var i = 0; i < gamepads.length; i++) {
  35427. if (gamepads[i]) {
  35428. if (!(gamepads[i].index in this.babylonGamepads)) {
  35429. var newGamepad = this._addNewGamepad(gamepads[i]);
  35430. if (this._callbackGamepadConnected) {
  35431. this._callbackGamepadConnected(newGamepad);
  35432. }
  35433. }
  35434. else {
  35435. this.babylonGamepads[i].browserGamepad = gamepads[i];
  35436. }
  35437. }
  35438. }
  35439. };
  35440. return Gamepads;
  35441. })();
  35442. BABYLON.Gamepads = Gamepads;
  35443. var StickValues = (function () {
  35444. function StickValues(x, y) {
  35445. this.x = x;
  35446. this.y = y;
  35447. }
  35448. return StickValues;
  35449. })();
  35450. BABYLON.StickValues = StickValues;
  35451. var Gamepad = (function () {
  35452. function Gamepad(id, index, browserGamepad) {
  35453. this.id = id;
  35454. this.index = index;
  35455. this.browserGamepad = browserGamepad;
  35456. if (this.browserGamepad.axes.length >= 2) {
  35457. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  35458. }
  35459. if (this.browserGamepad.axes.length >= 4) {
  35460. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  35461. }
  35462. }
  35463. Gamepad.prototype.onleftstickchanged = function (callback) {
  35464. this._onleftstickchanged = callback;
  35465. };
  35466. Gamepad.prototype.onrightstickchanged = function (callback) {
  35467. this._onrightstickchanged = callback;
  35468. };
  35469. Object.defineProperty(Gamepad.prototype, "leftStick", {
  35470. get: function () {
  35471. return this._leftStick;
  35472. },
  35473. set: function (newValues) {
  35474. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  35475. this._onleftstickchanged(newValues);
  35476. }
  35477. this._leftStick = newValues;
  35478. },
  35479. enumerable: true,
  35480. configurable: true
  35481. });
  35482. Object.defineProperty(Gamepad.prototype, "rightStick", {
  35483. get: function () {
  35484. return this._rightStick;
  35485. },
  35486. set: function (newValues) {
  35487. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  35488. this._onrightstickchanged(newValues);
  35489. }
  35490. this._rightStick = newValues;
  35491. },
  35492. enumerable: true,
  35493. configurable: true
  35494. });
  35495. Gamepad.prototype.update = function () {
  35496. if (this._leftStick) {
  35497. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  35498. }
  35499. if (this._rightStick) {
  35500. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  35501. }
  35502. };
  35503. return Gamepad;
  35504. })();
  35505. BABYLON.Gamepad = Gamepad;
  35506. var GenericPad = (function (_super) {
  35507. __extends(GenericPad, _super);
  35508. function GenericPad(id, index, gamepad) {
  35509. _super.call(this, id, index, gamepad);
  35510. this.id = id;
  35511. this.index = index;
  35512. this.gamepad = gamepad;
  35513. this._buttons = new Array(gamepad.buttons.length);
  35514. }
  35515. GenericPad.prototype.onbuttondown = function (callback) {
  35516. this._onbuttondown = callback;
  35517. };
  35518. GenericPad.prototype.onbuttonup = function (callback) {
  35519. this._onbuttonup = callback;
  35520. };
  35521. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  35522. if (newValue !== currentValue) {
  35523. if (this._onbuttondown && newValue === 1) {
  35524. this._onbuttondown(buttonIndex);
  35525. }
  35526. if (this._onbuttonup && newValue === 0) {
  35527. this._onbuttonup(buttonIndex);
  35528. }
  35529. }
  35530. return newValue;
  35531. };
  35532. GenericPad.prototype.update = function () {
  35533. _super.prototype.update.call(this);
  35534. for (var index = 0; index < this._buttons.length; index++) {
  35535. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  35536. }
  35537. };
  35538. return GenericPad;
  35539. })(Gamepad);
  35540. BABYLON.GenericPad = GenericPad;
  35541. (function (Xbox360Button) {
  35542. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  35543. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  35544. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  35545. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  35546. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  35547. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  35548. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  35549. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  35550. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  35551. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  35552. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  35553. var Xbox360Button = BABYLON.Xbox360Button;
  35554. (function (Xbox360Dpad) {
  35555. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  35556. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  35557. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  35558. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  35559. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  35560. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  35561. var Xbox360Pad = (function (_super) {
  35562. __extends(Xbox360Pad, _super);
  35563. function Xbox360Pad() {
  35564. _super.apply(this, arguments);
  35565. this._leftTrigger = 0;
  35566. this._rightTrigger = 0;
  35567. this._buttonA = 0;
  35568. this._buttonB = 0;
  35569. this._buttonX = 0;
  35570. this._buttonY = 0;
  35571. this._buttonBack = 0;
  35572. this._buttonStart = 0;
  35573. this._buttonLB = 0;
  35574. this._buttonRB = 0;
  35575. this._buttonLeftStick = 0;
  35576. this._buttonRightStick = 0;
  35577. this._dPadUp = 0;
  35578. this._dPadDown = 0;
  35579. this._dPadLeft = 0;
  35580. this._dPadRight = 0;
  35581. }
  35582. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  35583. this._onlefttriggerchanged = callback;
  35584. };
  35585. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  35586. this._onrighttriggerchanged = callback;
  35587. };
  35588. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  35589. get: function () {
  35590. return this._leftTrigger;
  35591. },
  35592. set: function (newValue) {
  35593. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  35594. this._onlefttriggerchanged(newValue);
  35595. }
  35596. this._leftTrigger = newValue;
  35597. },
  35598. enumerable: true,
  35599. configurable: true
  35600. });
  35601. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  35602. get: function () {
  35603. return this._rightTrigger;
  35604. },
  35605. set: function (newValue) {
  35606. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  35607. this._onrighttriggerchanged(newValue);
  35608. }
  35609. this._rightTrigger = newValue;
  35610. },
  35611. enumerable: true,
  35612. configurable: true
  35613. });
  35614. Xbox360Pad.prototype.onbuttondown = function (callback) {
  35615. this._onbuttondown = callback;
  35616. };
  35617. Xbox360Pad.prototype.onbuttonup = function (callback) {
  35618. this._onbuttonup = callback;
  35619. };
  35620. Xbox360Pad.prototype.ondpaddown = function (callback) {
  35621. this._ondpaddown = callback;
  35622. };
  35623. Xbox360Pad.prototype.ondpadup = function (callback) {
  35624. this._ondpadup = callback;
  35625. };
  35626. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  35627. if (newValue !== currentValue) {
  35628. if (this._onbuttondown && newValue === 1) {
  35629. this._onbuttondown(buttonType);
  35630. }
  35631. if (this._onbuttonup && newValue === 0) {
  35632. this._onbuttonup(buttonType);
  35633. }
  35634. }
  35635. return newValue;
  35636. };
  35637. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  35638. if (newValue !== currentValue) {
  35639. if (this._ondpaddown && newValue === 1) {
  35640. this._ondpaddown(buttonType);
  35641. }
  35642. if (this._ondpadup && newValue === 0) {
  35643. this._ondpadup(buttonType);
  35644. }
  35645. }
  35646. return newValue;
  35647. };
  35648. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  35649. get: function () {
  35650. return this._buttonA;
  35651. },
  35652. set: function (value) {
  35653. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  35654. },
  35655. enumerable: true,
  35656. configurable: true
  35657. });
  35658. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  35659. get: function () {
  35660. return this._buttonB;
  35661. },
  35662. set: function (value) {
  35663. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  35669. get: function () {
  35670. return this._buttonX;
  35671. },
  35672. set: function (value) {
  35673. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  35674. },
  35675. enumerable: true,
  35676. configurable: true
  35677. });
  35678. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  35679. get: function () {
  35680. return this._buttonY;
  35681. },
  35682. set: function (value) {
  35683. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  35684. },
  35685. enumerable: true,
  35686. configurable: true
  35687. });
  35688. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  35689. get: function () {
  35690. return this._buttonStart;
  35691. },
  35692. set: function (value) {
  35693. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  35694. },
  35695. enumerable: true,
  35696. configurable: true
  35697. });
  35698. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  35699. get: function () {
  35700. return this._buttonBack;
  35701. },
  35702. set: function (value) {
  35703. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  35704. },
  35705. enumerable: true,
  35706. configurable: true
  35707. });
  35708. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  35709. get: function () {
  35710. return this._buttonLB;
  35711. },
  35712. set: function (value) {
  35713. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  35714. },
  35715. enumerable: true,
  35716. configurable: true
  35717. });
  35718. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  35719. get: function () {
  35720. return this._buttonRB;
  35721. },
  35722. set: function (value) {
  35723. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  35729. get: function () {
  35730. return this._buttonLeftStick;
  35731. },
  35732. set: function (value) {
  35733. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  35734. },
  35735. enumerable: true,
  35736. configurable: true
  35737. });
  35738. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  35739. get: function () {
  35740. return this._buttonRightStick;
  35741. },
  35742. set: function (value) {
  35743. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  35744. },
  35745. enumerable: true,
  35746. configurable: true
  35747. });
  35748. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  35749. get: function () {
  35750. return this._dPadUp;
  35751. },
  35752. set: function (value) {
  35753. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  35754. },
  35755. enumerable: true,
  35756. configurable: true
  35757. });
  35758. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  35759. get: function () {
  35760. return this._dPadDown;
  35761. },
  35762. set: function (value) {
  35763. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  35764. },
  35765. enumerable: true,
  35766. configurable: true
  35767. });
  35768. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  35769. get: function () {
  35770. return this._dPadLeft;
  35771. },
  35772. set: function (value) {
  35773. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  35774. },
  35775. enumerable: true,
  35776. configurable: true
  35777. });
  35778. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  35779. get: function () {
  35780. return this._dPadRight;
  35781. },
  35782. set: function (value) {
  35783. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  35784. },
  35785. enumerable: true,
  35786. configurable: true
  35787. });
  35788. Xbox360Pad.prototype.update = function () {
  35789. _super.prototype.update.call(this);
  35790. this.buttonA = this.browserGamepad.buttons[0].value;
  35791. this.buttonB = this.browserGamepad.buttons[1].value;
  35792. this.buttonX = this.browserGamepad.buttons[2].value;
  35793. this.buttonY = this.browserGamepad.buttons[3].value;
  35794. this.buttonLB = this.browserGamepad.buttons[4].value;
  35795. this.buttonRB = this.browserGamepad.buttons[5].value;
  35796. this.leftTrigger = this.browserGamepad.buttons[6].value;
  35797. this.rightTrigger = this.browserGamepad.buttons[7].value;
  35798. this.buttonBack = this.browserGamepad.buttons[8].value;
  35799. this.buttonStart = this.browserGamepad.buttons[9].value;
  35800. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  35801. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  35802. this.dPadUp = this.browserGamepad.buttons[12].value;
  35803. this.dPadDown = this.browserGamepad.buttons[13].value;
  35804. this.dPadLeft = this.browserGamepad.buttons[14].value;
  35805. this.dPadRight = this.browserGamepad.buttons[15].value;
  35806. };
  35807. return Xbox360Pad;
  35808. })(Gamepad);
  35809. BABYLON.Xbox360Pad = Xbox360Pad;
  35810. })(BABYLON || (BABYLON = {}));
  35811. var BABYLON;
  35812. (function (BABYLON) {
  35813. // We're mainly based on the logic defined into the FreeCamera code
  35814. var GamepadCamera = (function (_super) {
  35815. __extends(GamepadCamera, _super);
  35816. function GamepadCamera(name, position, scene) {
  35817. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  35818. _super.call(this, name, position, scene);
  35819. }
  35820. GamepadCamera.prototype.getTypeName = function () {
  35821. return "GamepadCamera";
  35822. };
  35823. return GamepadCamera;
  35824. })(BABYLON.UniversalCamera);
  35825. BABYLON.GamepadCamera = GamepadCamera;
  35826. })(BABYLON || (BABYLON = {}));
  35827. var BABYLON;
  35828. (function (BABYLON) {
  35829. var Analyser = (function () {
  35830. function Analyser(scene) {
  35831. this.SMOOTHING = 0.75;
  35832. this.FFT_SIZE = 512;
  35833. this.BARGRAPHAMPLITUDE = 256;
  35834. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35835. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35836. this._scene = scene;
  35837. this._audioEngine = BABYLON.Engine.audioEngine;
  35838. if (this._audioEngine.canUseWebAudio) {
  35839. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35840. this._webAudioAnalyser.minDecibels = -140;
  35841. this._webAudioAnalyser.maxDecibels = 0;
  35842. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35843. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35844. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35845. }
  35846. }
  35847. Analyser.prototype.getFrequencyBinCount = function () {
  35848. if (this._audioEngine.canUseWebAudio) {
  35849. return this._webAudioAnalyser.frequencyBinCount;
  35850. }
  35851. else {
  35852. return 0;
  35853. }
  35854. };
  35855. Analyser.prototype.getByteFrequencyData = function () {
  35856. if (this._audioEngine.canUseWebAudio) {
  35857. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35858. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35859. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35860. }
  35861. return this._byteFreqs;
  35862. };
  35863. Analyser.prototype.getByteTimeDomainData = function () {
  35864. if (this._audioEngine.canUseWebAudio) {
  35865. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35866. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35867. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35868. }
  35869. return this._byteTime;
  35870. };
  35871. Analyser.prototype.getFloatFrequencyData = function () {
  35872. if (this._audioEngine.canUseWebAudio) {
  35873. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35874. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35875. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35876. }
  35877. return this._floatFreqs;
  35878. };
  35879. Analyser.prototype.drawDebugCanvas = function () {
  35880. var _this = this;
  35881. if (this._audioEngine.canUseWebAudio) {
  35882. if (!this._debugCanvas) {
  35883. this._debugCanvas = document.createElement("canvas");
  35884. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35885. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35886. this._debugCanvas.style.position = "absolute";
  35887. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35888. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35889. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35890. document.body.appendChild(this._debugCanvas);
  35891. this._registerFunc = function () {
  35892. _this.drawDebugCanvas();
  35893. };
  35894. this._scene.registerBeforeRender(this._registerFunc);
  35895. }
  35896. if (this._registerFunc) {
  35897. var workingArray = this.getByteFrequencyData();
  35898. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35899. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35900. // Draw the frequency domain chart.
  35901. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35902. var value = workingArray[i];
  35903. var percent = value / this.BARGRAPHAMPLITUDE;
  35904. var height = this.DEBUGCANVASSIZE.height * percent;
  35905. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35906. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35907. var hue = i / this.getFrequencyBinCount() * 360;
  35908. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35909. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35910. }
  35911. }
  35912. }
  35913. };
  35914. Analyser.prototype.stopDebugCanvas = function () {
  35915. if (this._debugCanvas) {
  35916. this._scene.unregisterBeforeRender(this._registerFunc);
  35917. this._registerFunc = null;
  35918. document.body.removeChild(this._debugCanvas);
  35919. this._debugCanvas = null;
  35920. this._debugCanvasContext = null;
  35921. }
  35922. };
  35923. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35924. if (this._audioEngine.canUseWebAudio) {
  35925. inputAudioNode.connect(this._webAudioAnalyser);
  35926. this._webAudioAnalyser.connect(outputAudioNode);
  35927. }
  35928. };
  35929. Analyser.prototype.dispose = function () {
  35930. if (this._audioEngine.canUseWebAudio) {
  35931. this._webAudioAnalyser.disconnect();
  35932. }
  35933. };
  35934. return Analyser;
  35935. })();
  35936. BABYLON.Analyser = Analyser;
  35937. })(BABYLON || (BABYLON = {}));
  35938. var BABYLON;
  35939. (function (BABYLON) {
  35940. var DepthRenderer = (function () {
  35941. function DepthRenderer(scene, type) {
  35942. var _this = this;
  35943. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35944. this._viewMatrix = BABYLON.Matrix.Zero();
  35945. this._projectionMatrix = BABYLON.Matrix.Zero();
  35946. this._transformMatrix = BABYLON.Matrix.Zero();
  35947. this._worldViewProjection = BABYLON.Matrix.Zero();
  35948. this._scene = scene;
  35949. var engine = scene.getEngine();
  35950. // Render target
  35951. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35952. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35953. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35954. this._depthMap.refreshRate = 1;
  35955. this._depthMap.renderParticles = false;
  35956. this._depthMap.renderList = null;
  35957. // set default depth value to 1.0 (far away)
  35958. this._depthMap.onClear = function (engine) {
  35959. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35960. };
  35961. // Custom render function
  35962. var renderSubMesh = function (subMesh) {
  35963. var mesh = subMesh.getRenderingMesh();
  35964. var scene = _this._scene;
  35965. var engine = scene.getEngine();
  35966. // Culling
  35967. engine.setState(subMesh.getMaterial().backFaceCulling);
  35968. // Managing instances
  35969. var batch = mesh._getInstancesRenderList(subMesh._id);
  35970. if (batch.mustReturn) {
  35971. return;
  35972. }
  35973. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35974. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35975. engine.enableEffect(_this._effect);
  35976. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35977. var material = subMesh.getMaterial();
  35978. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35979. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35980. // Alpha test
  35981. if (material && material.needAlphaTesting()) {
  35982. var alphaTexture = material.getAlphaTestTexture();
  35983. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35984. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35985. }
  35986. // Bones
  35987. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35989. }
  35990. // Draw
  35991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35992. }
  35993. };
  35994. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35995. var index;
  35996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35997. renderSubMesh(opaqueSubMeshes.data[index]);
  35998. }
  35999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36000. renderSubMesh(alphaTestSubMeshes.data[index]);
  36001. }
  36002. };
  36003. }
  36004. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  36005. var defines = [];
  36006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36007. var mesh = subMesh.getMesh();
  36008. var scene = mesh.getScene();
  36009. var material = subMesh.getMaterial();
  36010. // Alpha test
  36011. if (material && material.needAlphaTesting()) {
  36012. defines.push("#define ALPHATEST");
  36013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36014. attribs.push(BABYLON.VertexBuffer.UVKind);
  36015. defines.push("#define UV1");
  36016. }
  36017. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36018. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36019. defines.push("#define UV2");
  36020. }
  36021. }
  36022. // Bones
  36023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36026. if (mesh.numBoneInfluencers > 4) {
  36027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36029. }
  36030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36031. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36032. }
  36033. else {
  36034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36035. }
  36036. // Instances
  36037. if (useInstances) {
  36038. defines.push("#define INSTANCES");
  36039. attribs.push("world0");
  36040. attribs.push("world1");
  36041. attribs.push("world2");
  36042. attribs.push("world3");
  36043. }
  36044. // Get correct effect
  36045. var join = defines.join("\n");
  36046. if (this._cachedDefines !== join) {
  36047. this._cachedDefines = join;
  36048. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36049. }
  36050. return this._effect.isReady();
  36051. };
  36052. DepthRenderer.prototype.getDepthMap = function () {
  36053. return this._depthMap;
  36054. };
  36055. // Methods
  36056. DepthRenderer.prototype.dispose = function () {
  36057. this._depthMap.dispose();
  36058. };
  36059. return DepthRenderer;
  36060. })();
  36061. BABYLON.DepthRenderer = DepthRenderer;
  36062. })(BABYLON || (BABYLON = {}));
  36063. var BABYLON;
  36064. (function (BABYLON) {
  36065. var SSAORenderingPipeline = (function (_super) {
  36066. __extends(SSAORenderingPipeline, _super);
  36067. /**
  36068. * @constructor
  36069. * @param {string} name - The rendering pipeline name
  36070. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36071. * @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 }
  36072. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36073. */
  36074. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36075. var _this = this;
  36076. _super.call(this, scene.getEngine(), name);
  36077. // Members
  36078. /**
  36079. * The PassPostProcess id in the pipeline that contains the original scene color
  36080. * @type {string}
  36081. */
  36082. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36083. /**
  36084. * The SSAO PostProcess id in the pipeline
  36085. * @type {string}
  36086. */
  36087. this.SSAORenderEffect = "SSAORenderEffect";
  36088. /**
  36089. * The horizontal blur PostProcess id in the pipeline
  36090. * @type {string}
  36091. */
  36092. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36093. /**
  36094. * The vertical blur PostProcess id in the pipeline
  36095. * @type {string}
  36096. */
  36097. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36098. /**
  36099. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36100. * @type {string}
  36101. */
  36102. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36103. /**
  36104. * The output strength of the SSAO post-process. Default value is 1.0.
  36105. * @type {number}
  36106. */
  36107. this.totalStrength = 1.0;
  36108. /**
  36109. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36110. * @type {number}
  36111. */
  36112. this.radius = 0.0001;
  36113. /**
  36114. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36115. * Must not be equal to fallOff and superior to fallOff.
  36116. * Default value is 0.975
  36117. * @type {number}
  36118. */
  36119. this.area = 0.0075;
  36120. /**
  36121. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36122. * Must not be equal to area and inferior to area.
  36123. * Default value is 0.0
  36124. * @type {number}
  36125. */
  36126. this.fallOff = 0.000001;
  36127. /**
  36128. * The base color of the SSAO post-process
  36129. * The final result is "base + ssao" between [0, 1]
  36130. * @type {number}
  36131. */
  36132. this.base = 0.5;
  36133. this._firstUpdate = true;
  36134. this._scene = scene;
  36135. // Set up assets
  36136. this._createRandomTexture();
  36137. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36138. var ssaoRatio = ratio.ssaoRatio || ratio;
  36139. var combineRatio = ratio.combineRatio || ratio;
  36140. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36141. this._createSSAOPostProcess(ssaoRatio);
  36142. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36143. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36144. this._createSSAOCombinePostProcess(combineRatio);
  36145. // Set up pipeline
  36146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36151. // Finish
  36152. scene.postProcessRenderPipelineManager.addPipeline(this);
  36153. if (cameras)
  36154. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36155. }
  36156. // Public Methods
  36157. /**
  36158. * Returns the horizontal blur PostProcess
  36159. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36160. */
  36161. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36162. return this._blurHPostProcess;
  36163. };
  36164. /**
  36165. * Returns the vertical blur PostProcess
  36166. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36167. */
  36168. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36169. return this._blurVPostProcess;
  36170. };
  36171. /**
  36172. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36173. */
  36174. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36175. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36176. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36177. this._originalColorPostProcess = undefined;
  36178. this._ssaoPostProcess = undefined;
  36179. this._blurHPostProcess = undefined;
  36180. this._blurVPostProcess = undefined;
  36181. this._ssaoCombinePostProcess = undefined;
  36182. this._randomTexture.dispose();
  36183. if (disableDepthRender)
  36184. this._scene.disableDepthRenderer();
  36185. };
  36186. // Private Methods
  36187. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36188. var _this = this;
  36189. var numSamples = 16;
  36190. var sampleSphere = [
  36191. 0.5381, 0.1856, -0.4319,
  36192. 0.1379, 0.2486, 0.4430,
  36193. 0.3371, 0.5679, -0.0057,
  36194. -0.6999, -0.0451, -0.0019,
  36195. 0.0689, -0.1598, -0.8547,
  36196. 0.0560, 0.0069, -0.1843,
  36197. -0.0146, 0.1402, 0.0762,
  36198. 0.0100, -0.1924, -0.0344,
  36199. -0.3577, -0.5301, -0.4358,
  36200. -0.3169, 0.1063, 0.0158,
  36201. 0.0103, -0.5869, 0.0046,
  36202. -0.0897, -0.4940, 0.3287,
  36203. 0.7119, -0.0154, -0.0918,
  36204. -0.0533, 0.0596, -0.5411,
  36205. 0.0352, -0.0631, 0.5460,
  36206. -0.4776, 0.2847, -0.0271
  36207. ];
  36208. var samplesFactor = 1.0 / numSamples;
  36209. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36210. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36211. "area", "fallOff", "base"
  36212. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36213. this._ssaoPostProcess.onApply = function (effect) {
  36214. if (_this._firstUpdate) {
  36215. effect.setArray3("sampleSphere", sampleSphere);
  36216. effect.setFloat("samplesFactor", samplesFactor);
  36217. effect.setFloat("randTextureTiles", 4.0);
  36218. _this._firstUpdate = false;
  36219. }
  36220. effect.setFloat("totalStrength", _this.totalStrength);
  36221. effect.setFloat("radius", _this.radius);
  36222. effect.setFloat("area", _this.area);
  36223. effect.setFloat("fallOff", _this.fallOff);
  36224. effect.setFloat("base", _this.base);
  36225. effect.setTexture("textureSampler", _this._depthTexture);
  36226. effect.setTexture("randomSampler", _this._randomTexture);
  36227. };
  36228. };
  36229. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36230. var _this = this;
  36231. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36232. this._ssaoCombinePostProcess.onApply = function (effect) {
  36233. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36234. };
  36235. };
  36236. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36237. var size = 512;
  36238. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36239. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36240. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36241. var context = this._randomTexture.getContext();
  36242. var rand = function (min, max) {
  36243. return Math.random() * (max - min) + min;
  36244. };
  36245. var randVector = BABYLON.Vector3.Zero();
  36246. for (var x = 0; x < size; x++) {
  36247. for (var y = 0; y < size; y++) {
  36248. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36249. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36250. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36251. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36252. context.fillRect(x, y, 1, 1);
  36253. }
  36254. }
  36255. this._randomTexture.update(false);
  36256. };
  36257. return SSAORenderingPipeline;
  36258. })(BABYLON.PostProcessRenderPipeline);
  36259. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36260. })(BABYLON || (BABYLON = {}));
  36261. var BABYLON;
  36262. (function (BABYLON) {
  36263. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36264. var VolumetricLightScatteringPostProcess = (function (_super) {
  36265. __extends(VolumetricLightScatteringPostProcess, _super);
  36266. /**
  36267. * @constructor
  36268. * @param {string} name - The post-process name
  36269. * @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)
  36270. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36271. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36272. * @param {number} samples - The post-process quality, default 100
  36273. * @param {number} samplingMode - The post-process filtering mode
  36274. * @param {BABYLON.Engine} engine - The babylon engine
  36275. * @param {boolean} reusable - If the post-process is reusable
  36276. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36277. */
  36278. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36279. var _this = this;
  36280. if (samples === void 0) { samples = 100; }
  36281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36282. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36283. this._screenCoordinates = BABYLON.Vector2.Zero();
  36284. /**
  36285. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36286. * @type {boolean}
  36287. */
  36288. this.useCustomMeshPosition = false;
  36289. /**
  36290. * If the post-process should inverse the light scattering direction
  36291. * @type {boolean}
  36292. */
  36293. this.invert = true;
  36294. /**
  36295. * Set to true to use the diffuseColor instead of the diffuseTexture
  36296. * @type {boolean}
  36297. */
  36298. this.useDiffuseColor = false;
  36299. /**
  36300. * Array containing the excluded meshes not rendered in the internal pass
  36301. */
  36302. this.excludedMeshes = new Array();
  36303. /**
  36304. * Controls the overall intensity of the post-process
  36305. * @type {number}
  36306. */
  36307. this.exposure = 0.3;
  36308. /**
  36309. * Dissipates each sample's contribution in range [0, 1]
  36310. * @type {number}
  36311. */
  36312. this.decay = 0.96815;
  36313. /**
  36314. * Controls the overall intensity of each sample
  36315. * @type {number}
  36316. */
  36317. this.weight = 0.58767;
  36318. /**
  36319. * Controls the density of each sample
  36320. * @type {number}
  36321. */
  36322. this.density = 0.926;
  36323. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36324. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  36325. // Configure mesh
  36326. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36327. // Configure
  36328. this._createPass(scene, ratio.passRatio || ratio);
  36329. this.onActivate = function (camera) {
  36330. if (!_this.isSupported) {
  36331. _this.dispose(camera);
  36332. }
  36333. _this.onActivate = null;
  36334. };
  36335. this.onApply = function (effect) {
  36336. _this._updateMeshScreenCoordinates(scene);
  36337. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36338. effect.setFloat("exposure", _this.exposure);
  36339. effect.setFloat("decay", _this.decay);
  36340. effect.setFloat("weight", _this.weight);
  36341. effect.setFloat("density", _this.density);
  36342. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36343. };
  36344. }
  36345. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36346. var mesh = subMesh.getMesh();
  36347. var defines = [];
  36348. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36349. var material = subMesh.getMaterial();
  36350. var needUV = false;
  36351. // Render this.mesh as default
  36352. if (mesh === this.mesh) {
  36353. if (this.useDiffuseColor) {
  36354. defines.push("#define DIFFUSE_COLOR_RENDER");
  36355. }
  36356. else if (material) {
  36357. if (material.diffuseTexture !== undefined) {
  36358. defines.push("#define BASIC_RENDER");
  36359. }
  36360. else {
  36361. defines.push("#define DIFFUSE_COLOR_RENDER");
  36362. }
  36363. }
  36364. defines.push("#define NEED_UV");
  36365. needUV = true;
  36366. }
  36367. // Alpha test
  36368. if (material) {
  36369. if (material.needAlphaTesting()) {
  36370. defines.push("#define ALPHATEST");
  36371. }
  36372. if (material.opacityTexture !== undefined) {
  36373. defines.push("#define OPACITY");
  36374. if (material.opacityTexture.getAlphaFromRGB) {
  36375. defines.push("#define OPACITYRGB");
  36376. }
  36377. if (!needUV) {
  36378. defines.push("#define NEED_UV");
  36379. }
  36380. }
  36381. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36382. attribs.push(BABYLON.VertexBuffer.UVKind);
  36383. defines.push("#define UV1");
  36384. }
  36385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36386. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36387. defines.push("#define UV2");
  36388. }
  36389. }
  36390. // Bones
  36391. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36394. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36395. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36396. }
  36397. else {
  36398. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36399. }
  36400. // Instances
  36401. if (useInstances) {
  36402. defines.push("#define INSTANCES");
  36403. attribs.push("world0");
  36404. attribs.push("world1");
  36405. attribs.push("world2");
  36406. attribs.push("world3");
  36407. }
  36408. // Get correct effect
  36409. var join = defines.join("\n");
  36410. if (this._cachedDefines !== join) {
  36411. this._cachedDefines = join;
  36412. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36413. }
  36414. return this._volumetricLightScatteringPass.isReady();
  36415. };
  36416. /**
  36417. * Sets the new light position for light scattering effect
  36418. * @param {BABYLON.Vector3} The new custom light position
  36419. */
  36420. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36421. this._customMeshPosition = position;
  36422. };
  36423. /**
  36424. * Returns the light position for light scattering effect
  36425. * @return {BABYLON.Vector3} The custom light position
  36426. */
  36427. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36428. return this._customMeshPosition;
  36429. };
  36430. /**
  36431. * Disposes the internal assets and detaches the post-process from the camera
  36432. */
  36433. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36434. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36435. if (rttIndex !== -1) {
  36436. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36437. }
  36438. this._volumetricLightScatteringRTT.dispose();
  36439. _super.prototype.dispose.call(this, camera);
  36440. };
  36441. /**
  36442. * Returns the render target texture used by the post-process
  36443. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36444. */
  36445. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36446. return this._volumetricLightScatteringRTT;
  36447. };
  36448. // Private methods
  36449. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36450. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36451. return true;
  36452. }
  36453. return false;
  36454. };
  36455. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36456. var _this = this;
  36457. var engine = scene.getEngine();
  36458. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36459. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36460. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36461. this._volumetricLightScatteringRTT.renderList = null;
  36462. this._volumetricLightScatteringRTT.renderParticles = false;
  36463. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36464. // Custom render function for submeshes
  36465. var renderSubMesh = function (subMesh) {
  36466. var mesh = subMesh.getRenderingMesh();
  36467. if (_this._meshExcluded(mesh)) {
  36468. return;
  36469. }
  36470. var scene = mesh.getScene();
  36471. var engine = scene.getEngine();
  36472. // Culling
  36473. engine.setState(subMesh.getMaterial().backFaceCulling);
  36474. // Managing instances
  36475. var batch = mesh._getInstancesRenderList(subMesh._id);
  36476. if (batch.mustReturn) {
  36477. return;
  36478. }
  36479. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36480. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36481. engine.enableEffect(_this._volumetricLightScatteringPass);
  36482. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36483. var material = subMesh.getMaterial();
  36484. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36485. // Alpha test
  36486. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36487. var alphaTexture = material.getAlphaTestTexture();
  36488. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36489. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36490. }
  36491. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36492. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36493. if (alphaTexture) {
  36494. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36495. }
  36496. }
  36497. if (material.opacityTexture !== undefined) {
  36498. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36499. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36500. }
  36501. }
  36502. // Bones
  36503. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36504. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36505. }
  36506. // Draw
  36507. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36508. }
  36509. };
  36510. // Render target texture callbacks
  36511. var savedSceneClearColor;
  36512. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36513. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36514. savedSceneClearColor = scene.clearColor;
  36515. scene.clearColor = sceneClearColor;
  36516. };
  36517. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36518. scene.clearColor = savedSceneClearColor;
  36519. };
  36520. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36521. var engine = scene.getEngine();
  36522. var index;
  36523. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36524. renderSubMesh(opaqueSubMeshes.data[index]);
  36525. }
  36526. engine.setAlphaTesting(true);
  36527. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36528. renderSubMesh(alphaTestSubMeshes.data[index]);
  36529. }
  36530. engine.setAlphaTesting(false);
  36531. if (transparentSubMeshes.length) {
  36532. // Sort sub meshes
  36533. for (index = 0; index < transparentSubMeshes.length; index++) {
  36534. var submesh = transparentSubMeshes.data[index];
  36535. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36536. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36537. }
  36538. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36539. sortedArray.sort(function (a, b) {
  36540. // Alpha index first
  36541. if (a._alphaIndex > b._alphaIndex) {
  36542. return 1;
  36543. }
  36544. if (a._alphaIndex < b._alphaIndex) {
  36545. return -1;
  36546. }
  36547. // Then distance to camera
  36548. if (a._distanceToCamera < b._distanceToCamera) {
  36549. return 1;
  36550. }
  36551. if (a._distanceToCamera > b._distanceToCamera) {
  36552. return -1;
  36553. }
  36554. return 0;
  36555. });
  36556. // Render sub meshes
  36557. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36558. for (index = 0; index < sortedArray.length; index++) {
  36559. renderSubMesh(sortedArray[index]);
  36560. }
  36561. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36562. }
  36563. };
  36564. };
  36565. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36566. var transform = scene.getTransformMatrix();
  36567. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36568. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36569. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36570. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36571. if (this.invert)
  36572. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36573. };
  36574. // Static methods
  36575. /**
  36576. * Creates a default mesh for the Volumeric Light Scattering post-process
  36577. * @param {string} The mesh name
  36578. * @param {BABYLON.Scene} The scene where to create the mesh
  36579. * @return {BABYLON.Mesh} the default mesh
  36580. */
  36581. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36582. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36583. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36584. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36585. return mesh;
  36586. };
  36587. return VolumetricLightScatteringPostProcess;
  36588. })(BABYLON.PostProcess);
  36589. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36590. })(BABYLON || (BABYLON = {}));
  36591. // BABYLON.JS Chromatic Aberration GLSL Shader
  36592. // Author: Olivier Guyot
  36593. // Separates very slightly R, G and B colors on the edges of the screen
  36594. // Inspired by Francois Tarlier & Martins Upitis
  36595. var BABYLON;
  36596. (function (BABYLON) {
  36597. var LensRenderingPipeline = (function (_super) {
  36598. __extends(LensRenderingPipeline, _super);
  36599. /**
  36600. * @constructor
  36601. *
  36602. * Effect parameters are as follow:
  36603. * {
  36604. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36605. * edge_blur: number; // from 0 to x (1 for realism)
  36606. * distortion: number; // from 0 to x (1 for realism)
  36607. * grain_amount: number; // from 0 to 1
  36608. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36609. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36610. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36611. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36612. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36613. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36614. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36615. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36616. * }
  36617. * Note: if an effect parameter is unset, effect is disabled
  36618. *
  36619. * @param {string} name - The rendering pipeline name
  36620. * @param {object} parameters - An object containing all parameters (see above)
  36621. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36622. * @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)
  36623. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36624. */
  36625. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36626. var _this = this;
  36627. if (ratio === void 0) { ratio = 1.0; }
  36628. _super.call(this, scene.getEngine(), name);
  36629. // Lens effects can be of the following:
  36630. // - chromatic aberration (slight shift of RGB colors)
  36631. // - blur on the edge of the lens
  36632. // - lens distortion
  36633. // - depth-of-field blur & highlights enhancing
  36634. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36635. // - grain effect (noise or custom texture)
  36636. // Two additional texture samplers are needed:
  36637. // - depth map (for depth-of-field)
  36638. // - grain texture
  36639. /**
  36640. * The chromatic aberration PostProcess id in the pipeline
  36641. * @type {string}
  36642. */
  36643. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36644. /**
  36645. * The highlights enhancing PostProcess id in the pipeline
  36646. * @type {string}
  36647. */
  36648. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36649. /**
  36650. * The depth-of-field PostProcess id in the pipeline
  36651. * @type {string}
  36652. */
  36653. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36654. this._scene = scene;
  36655. // Fetch texture samplers
  36656. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36657. if (parameters.grain_texture) {
  36658. this._grainTexture = parameters.grain_texture;
  36659. }
  36660. else {
  36661. this._createGrainTexture();
  36662. }
  36663. // save parameters
  36664. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36665. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36666. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36667. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36668. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36669. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36670. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36671. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36672. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36673. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36674. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36675. // Create effects
  36676. this._createChromaticAberrationPostProcess(ratio);
  36677. this._createHighlightsPostProcess(ratio);
  36678. this._createDepthOfFieldPostProcess(ratio / 4);
  36679. // Set up pipeline
  36680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36681. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36683. if (this._highlightsGain === -1) {
  36684. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36685. }
  36686. // Finish
  36687. scene.postProcessRenderPipelineManager.addPipeline(this);
  36688. if (cameras) {
  36689. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36690. }
  36691. }
  36692. // public methods (self explanatory)
  36693. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36694. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36695. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36696. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36697. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36698. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36699. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36700. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36701. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36702. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36703. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36704. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36705. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36706. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36707. };
  36708. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36709. this._highlightsPostProcess.updateEffect();
  36710. };
  36711. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36712. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36713. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36714. this._highlightsGain = amount;
  36715. };
  36716. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36717. if (this._highlightsGain === -1) {
  36718. this._highlightsGain = 1.0;
  36719. }
  36720. this._highlightsThreshold = amount;
  36721. };
  36722. LensRenderingPipeline.prototype.disableHighlights = function () {
  36723. this._highlightsGain = -1;
  36724. };
  36725. /**
  36726. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36727. */
  36728. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36729. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36730. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36731. this._chromaticAberrationPostProcess = undefined;
  36732. this._highlightsPostProcess = undefined;
  36733. this._depthOfFieldPostProcess = undefined;
  36734. this._grainTexture.dispose();
  36735. if (disableDepthRender)
  36736. this._scene.disableDepthRenderer();
  36737. };
  36738. // colors shifting and distortion
  36739. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36740. var _this = this;
  36741. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36742. [], // samplers
  36743. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36744. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36745. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36746. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36747. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36748. };
  36749. };
  36750. // highlights enhancing
  36751. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36752. var _this = this;
  36753. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36754. [], // samplers
  36755. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36756. this._highlightsPostProcess.onApply = function (effect) {
  36757. effect.setFloat('gain', _this._highlightsGain);
  36758. effect.setFloat('threshold', _this._highlightsThreshold);
  36759. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36760. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36761. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36762. };
  36763. };
  36764. // colors shifting and distortion
  36765. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36766. var _this = this;
  36767. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36768. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36769. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36770. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36771. this._depthOfFieldPostProcess.onApply = function (effect) {
  36772. effect.setTexture("depthSampler", _this._depthTexture);
  36773. effect.setTexture("grainSampler", _this._grainTexture);
  36774. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36775. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36776. effect.setFloat('grain_amount', _this._grainAmount);
  36777. effect.setBool('blur_noise', _this._blurNoise);
  36778. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36779. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36780. effect.setFloat('distortion', _this._distortion);
  36781. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36782. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36783. effect.setFloat('aperture', _this._dofAperture);
  36784. effect.setFloat('darken', _this._dofDarken);
  36785. effect.setFloat('edge_blur', _this._edgeBlur);
  36786. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36787. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36788. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36789. };
  36790. };
  36791. // creates a black and white random noise texture, 512x512
  36792. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36793. var size = 512;
  36794. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36795. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36796. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36797. var context = this._grainTexture.getContext();
  36798. var rand = function (min, max) {
  36799. return Math.random() * (max - min) + min;
  36800. };
  36801. var value;
  36802. for (var x = 0; x < size; x++) {
  36803. for (var y = 0; y < size; y++) {
  36804. value = Math.floor(rand(0.42, 0.58) * 255);
  36805. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36806. context.fillRect(x, y, 1, 1);
  36807. }
  36808. }
  36809. this._grainTexture.update(false);
  36810. };
  36811. return LensRenderingPipeline;
  36812. })(BABYLON.PostProcessRenderPipeline);
  36813. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36814. })(BABYLON || (BABYLON = {}));
  36815. //
  36816. // This post-process allows the modification of rendered colors by using
  36817. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36818. //
  36819. // The object needs to be provided an url to a texture containing the color
  36820. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36821. // Use an image editing software to tweak the LUT to match your needs.
  36822. //
  36823. // For an example of a color LUT, see here:
  36824. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36825. // For explanations on color grading, see here:
  36826. // http://udn.epicgames.com/Three/ColorGrading.html
  36827. //
  36828. var BABYLON;
  36829. (function (BABYLON) {
  36830. var ColorCorrectionPostProcess = (function (_super) {
  36831. __extends(ColorCorrectionPostProcess, _super);
  36832. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36833. var _this = this;
  36834. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36835. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36836. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36837. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36838. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36839. this.onApply = function (effect) {
  36840. effect.setTexture("colorTable", _this._colorTableTexture);
  36841. };
  36842. }
  36843. return ColorCorrectionPostProcess;
  36844. })(BABYLON.PostProcess);
  36845. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36846. })(BABYLON || (BABYLON = {}));
  36847. var BABYLON;
  36848. (function (BABYLON) {
  36849. var AnaglyphFreeCamera = (function (_super) {
  36850. __extends(AnaglyphFreeCamera, _super);
  36851. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  36852. _super.call(this, name, position, scene);
  36853. this.interaxialDistance = interaxialDistance;
  36854. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36855. }
  36856. AnaglyphFreeCamera.prototype.getTypeName = function () {
  36857. return "AnaglyphFreeCamera";
  36858. };
  36859. return AnaglyphFreeCamera;
  36860. })(BABYLON.FreeCamera);
  36861. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  36862. var AnaglyphArcRotateCamera = (function (_super) {
  36863. __extends(AnaglyphArcRotateCamera, _super);
  36864. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  36865. _super.call(this, name, alpha, beta, radius, target, scene);
  36866. this.interaxialDistance = interaxialDistance;
  36867. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36868. }
  36869. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  36870. return "AnaglyphArcRotateCamera";
  36871. };
  36872. return AnaglyphArcRotateCamera;
  36873. })(BABYLON.ArcRotateCamera);
  36874. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  36875. var AnaglyphGamepadCamera = (function (_super) {
  36876. __extends(AnaglyphGamepadCamera, _super);
  36877. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  36878. _super.call(this, name, position, scene);
  36879. this.interaxialDistance = interaxialDistance;
  36880. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36881. }
  36882. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  36883. return "AnaglyphGamepadCamera";
  36884. };
  36885. return AnaglyphGamepadCamera;
  36886. })(BABYLON.GamepadCamera);
  36887. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  36888. var AnaglyphUniversalCamera = (function (_super) {
  36889. __extends(AnaglyphUniversalCamera, _super);
  36890. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  36891. _super.call(this, name, position, scene);
  36892. this.interaxialDistance = interaxialDistance;
  36893. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  36894. }
  36895. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  36896. return "AnaglyphUniversalCamera";
  36897. };
  36898. return AnaglyphUniversalCamera;
  36899. })(BABYLON.UniversalCamera);
  36900. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  36901. var StereoscopicFreeCamera = (function (_super) {
  36902. __extends(StereoscopicFreeCamera, _super);
  36903. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  36904. _super.call(this, name, position, scene);
  36905. this.interaxialDistance = interaxialDistance;
  36906. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  36907. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36908. }
  36909. StereoscopicFreeCamera.prototype.getTypeName = function () {
  36910. return "StereoscopicFreeCamera";
  36911. };
  36912. return StereoscopicFreeCamera;
  36913. })(BABYLON.FreeCamera);
  36914. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  36915. var StereoscopicArcRotateCamera = (function (_super) {
  36916. __extends(StereoscopicArcRotateCamera, _super);
  36917. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  36918. _super.call(this, name, alpha, beta, radius, target, scene);
  36919. this.interaxialDistance = interaxialDistance;
  36920. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  36921. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36922. }
  36923. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  36924. return "StereoscopicArcRotateCamera";
  36925. };
  36926. return StereoscopicArcRotateCamera;
  36927. })(BABYLON.ArcRotateCamera);
  36928. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  36929. var StereoscopicGamepadCamera = (function (_super) {
  36930. __extends(StereoscopicGamepadCamera, _super);
  36931. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  36932. _super.call(this, name, position, scene);
  36933. this.interaxialDistance = interaxialDistance;
  36934. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  36935. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36936. }
  36937. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  36938. return "StereoscopicGamepadCamera";
  36939. };
  36940. return StereoscopicGamepadCamera;
  36941. })(BABYLON.GamepadCamera);
  36942. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  36943. var StereoscopicUniversalCamera = (function (_super) {
  36944. __extends(StereoscopicUniversalCamera, _super);
  36945. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  36946. _super.call(this, name, position, scene);
  36947. this.interaxialDistance = interaxialDistance;
  36948. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  36949. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  36950. }
  36951. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  36952. return "StereoscopicUniversalCamera";
  36953. };
  36954. return StereoscopicUniversalCamera;
  36955. })(BABYLON.UniversalCamera);
  36956. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  36957. })(BABYLON || (BABYLON = {}));
  36958. var BABYLON;
  36959. (function (BABYLON) {
  36960. var HDRRenderingPipeline = (function (_super) {
  36961. __extends(HDRRenderingPipeline, _super);
  36962. /**
  36963. * @constructor
  36964. * @param {string} name - The rendering pipeline name
  36965. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36966. * @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)
  36967. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36968. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36969. */
  36970. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36971. var _this = this;
  36972. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36973. _super.call(this, scene.getEngine(), name);
  36974. /**
  36975. * Public members
  36976. */
  36977. // Gaussian Blur
  36978. /**
  36979. * Gaussian blur coefficient
  36980. * @type {number}
  36981. */
  36982. this.gaussCoeff = 0.3;
  36983. /**
  36984. * Gaussian blur mean
  36985. * @type {number}
  36986. */
  36987. this.gaussMean = 1.0;
  36988. /**
  36989. * Gaussian blur standard deviation
  36990. * @type {number}
  36991. */
  36992. this.gaussStandDev = 0.8;
  36993. /**
  36994. * Gaussian blur multiplier. Multiplies the blur effect
  36995. * @type {number}
  36996. */
  36997. this.gaussMultiplier = 4.0;
  36998. // HDR
  36999. /**
  37000. * Exposure, controls the overall intensity of the pipeline
  37001. * @type {number}
  37002. */
  37003. this.exposure = 1.0;
  37004. /**
  37005. * Minimum luminance that the post-process can output. Luminance is >= 0
  37006. * @type {number}
  37007. */
  37008. this.minimumLuminance = 1.0;
  37009. /**
  37010. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  37011. * @type {number}
  37012. */
  37013. this.maximumLuminance = 1e20;
  37014. /**
  37015. * Increase rate for luminance: eye adaptation speed to dark
  37016. * @type {number}
  37017. */
  37018. this.luminanceIncreaserate = 0.5;
  37019. /**
  37020. * Decrease rate for luminance: eye adaptation speed to bright
  37021. * @type {number}
  37022. */
  37023. this.luminanceDecreaseRate = 0.5;
  37024. // Bright pass
  37025. /**
  37026. * Minimum luminance needed to compute HDR
  37027. * @type {number}
  37028. */
  37029. this.brightThreshold = 0.8;
  37030. this._needUpdate = true;
  37031. this._scene = scene;
  37032. // Bright pass
  37033. this._createBrightPassPostProcess(scene, ratio);
  37034. // Down sample X4
  37035. this._createDownSampleX4PostProcess(scene, ratio);
  37036. // Create gaussian blur post-processes
  37037. this._createGaussianBlurPostProcess(scene, ratio);
  37038. // Texture adder
  37039. this._createTextureAdderPostProcess(scene, ratio);
  37040. // Luminance generator
  37041. this._createLuminanceGeneratorPostProcess(scene);
  37042. // HDR
  37043. this._createHDRPostProcess(scene, ratio);
  37044. // Pass postprocess
  37045. if (originalPostProcess === null) {
  37046. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  37047. }
  37048. else {
  37049. this._originalPostProcess = originalPostProcess;
  37050. }
  37051. // Configure pipeline
  37052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  37053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  37054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  37055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  37056. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  37057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  37058. var addDownSamplerPostProcess = function (id) {
  37059. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  37060. };
  37061. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37062. addDownSamplerPostProcess(i);
  37063. }
  37064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  37065. // Finish
  37066. scene.postProcessRenderPipelineManager.addPipeline(this);
  37067. if (cameras !== null) {
  37068. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37069. }
  37070. this.update();
  37071. }
  37072. /**
  37073. * Tells the pipeline to update its post-processes
  37074. */
  37075. HDRRenderingPipeline.prototype.update = function () {
  37076. this._needUpdate = true;
  37077. };
  37078. /**
  37079. * Returns the current calculated luminance
  37080. */
  37081. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  37082. return this._hdrCurrentLuminance;
  37083. };
  37084. /**
  37085. * Returns the currently drawn luminance
  37086. */
  37087. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  37088. return this._hdrOutputLuminance;
  37089. };
  37090. /**
  37091. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  37092. */
  37093. HDRRenderingPipeline.prototype.dispose = function () {
  37094. this._originalPostProcess = undefined;
  37095. this._brightPassPostProcess = undefined;
  37096. this._downSampleX4PostProcess = undefined;
  37097. this._guassianBlurHPostProcess = undefined;
  37098. this._guassianBlurVPostProcess = undefined;
  37099. this._textureAdderPostProcess = undefined;
  37100. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37101. this._downSamplePostProcesses[i] = undefined;
  37102. }
  37103. this._hdrPostProcess = undefined;
  37104. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37105. };
  37106. /**
  37107. * Creates the HDR post-process and computes the luminance adaptation
  37108. */
  37109. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  37110. var _this = this;
  37111. var hdrLastLuminance = 0.0;
  37112. this._hdrOutputLuminance = -1.0;
  37113. this._hdrCurrentLuminance = 1.0;
  37114. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  37115. this._hdrPostProcess.onApply = function (effect) {
  37116. if (_this._hdrOutputLuminance < 0.0) {
  37117. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37118. }
  37119. else {
  37120. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  37121. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  37122. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  37123. }
  37124. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  37125. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  37126. }
  37127. else {
  37128. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37129. }
  37130. }
  37131. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  37132. hdrLastLuminance += scene.getEngine().getDeltaTime();
  37133. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37134. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37135. effect.setFloat("exposure", _this.exposure);
  37136. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  37137. _this._needUpdate = false;
  37138. };
  37139. };
  37140. /**
  37141. * Texture Adder post-process
  37142. */
  37143. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  37144. var _this = this;
  37145. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  37146. this._textureAdderPostProcess.onApply = function (effect) {
  37147. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37148. };
  37149. };
  37150. /**
  37151. * Down sample X4 post-process
  37152. */
  37153. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37154. var _this = this;
  37155. var downSampleX4Offsets = new Array(32);
  37156. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37157. this._downSampleX4PostProcess.onApply = function (effect) {
  37158. if (_this._needUpdate) {
  37159. var id = 0;
  37160. for (var i = -2; i < 2; i++) {
  37161. for (var j = -2; j < 2; j++) {
  37162. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37163. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37164. id += 2;
  37165. }
  37166. }
  37167. }
  37168. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37169. };
  37170. };
  37171. /**
  37172. * Bright pass post-process
  37173. */
  37174. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37175. var _this = this;
  37176. var brightOffsets = new Array(8);
  37177. var brightPassCallback = function (effect) {
  37178. if (_this._needUpdate) {
  37179. var sU = (1.0 / _this._brightPassPostProcess.width);
  37180. var sV = (1.0 / _this._brightPassPostProcess.height);
  37181. brightOffsets[0] = -0.5 * sU;
  37182. brightOffsets[1] = 0.5 * sV;
  37183. brightOffsets[2] = 0.5 * sU;
  37184. brightOffsets[3] = 0.5 * sV;
  37185. brightOffsets[4] = -0.5 * sU;
  37186. brightOffsets[5] = -0.5 * sV;
  37187. brightOffsets[6] = 0.5 * sU;
  37188. brightOffsets[7] = -0.5 * sV;
  37189. }
  37190. effect.setArray2("dsOffsets", brightOffsets);
  37191. effect.setFloat("brightThreshold", _this.brightThreshold);
  37192. };
  37193. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37194. this._brightPassPostProcess.onApply = brightPassCallback;
  37195. };
  37196. /**
  37197. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37198. */
  37199. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37200. var _this = this;
  37201. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37202. var luminanceOffsets = new Array(8);
  37203. var downSampleOffsets = new Array(18);
  37204. var halfDestPixelSize;
  37205. this._downSamplePostProcesses = new Array(lumSteps);
  37206. // Utils for luminance
  37207. var luminanceUpdateSourceOffsets = function (width, height) {
  37208. var sU = (1.0 / width);
  37209. var sV = (1.0 / height);
  37210. luminanceOffsets[0] = -0.5 * sU;
  37211. luminanceOffsets[1] = 0.5 * sV;
  37212. luminanceOffsets[2] = 0.5 * sU;
  37213. luminanceOffsets[3] = 0.5 * sV;
  37214. luminanceOffsets[4] = -0.5 * sU;
  37215. luminanceOffsets[5] = -0.5 * sV;
  37216. luminanceOffsets[6] = 0.5 * sU;
  37217. luminanceOffsets[7] = -0.5 * sV;
  37218. };
  37219. var luminanceUpdateDestOffsets = function (width, height) {
  37220. var id = 0;
  37221. for (var x = -1; x < 2; x++) {
  37222. for (var y = -1; y < 2; y++) {
  37223. downSampleOffsets[id] = (x) / width;
  37224. downSampleOffsets[id + 1] = (y) / height;
  37225. id += 2;
  37226. }
  37227. }
  37228. };
  37229. // Luminance callback
  37230. var luminanceCallback = function (effect) {
  37231. if (_this._needUpdate) {
  37232. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37233. }
  37234. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37235. effect.setArray2("lumOffsets", luminanceOffsets);
  37236. };
  37237. // Down sample callbacks
  37238. var downSampleCallback = function (indice) {
  37239. var i = indice;
  37240. return function (effect) {
  37241. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37242. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37243. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37244. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37245. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37246. effect.setArray2("dsOffsets", downSampleOffsets);
  37247. };
  37248. };
  37249. var downSampleAfterRenderCallback = function (effect) {
  37250. // Unpack result
  37251. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37252. 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);
  37253. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37254. };
  37255. // Create luminance post-process
  37256. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37257. 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);
  37258. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37259. // Create down sample post-processes
  37260. for (var i = lumSteps - 2; i >= 0; i--) {
  37261. var length = Math.pow(3, i);
  37262. ratio = { width: length, height: length };
  37263. var defines = "#define DOWN_SAMPLE\n";
  37264. if (i === 0) {
  37265. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37266. }
  37267. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37268. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37269. if (i === 0) {
  37270. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37271. }
  37272. }
  37273. };
  37274. /**
  37275. * Gaussian blur post-processes. Horizontal and Vertical
  37276. */
  37277. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37278. var _this = this;
  37279. var blurOffsetsW = new Array(9);
  37280. var blurOffsetsH = new Array(9);
  37281. var blurWeights = new Array(9);
  37282. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37283. // Utils for gaussian blur
  37284. var calculateBlurOffsets = function (height) {
  37285. var lastOutputDimensions = {
  37286. width: scene.getEngine().getRenderWidth(),
  37287. height: scene.getEngine().getRenderHeight()
  37288. };
  37289. for (var i = 0; i < 9; i++) {
  37290. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37291. if (height) {
  37292. blurOffsetsH[i] = value;
  37293. }
  37294. else {
  37295. blurOffsetsW[i] = value;
  37296. }
  37297. }
  37298. };
  37299. var calculateWeights = function () {
  37300. var x = 0.0;
  37301. for (var i = 0; i < 9; i++) {
  37302. x = (i - 4.0) / 4.0;
  37303. 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));
  37304. }
  37305. };
  37306. // Callback
  37307. var gaussianBlurCallback = function (height) {
  37308. return function (effect) {
  37309. if (_this._needUpdate) {
  37310. calculateWeights();
  37311. calculateBlurOffsets(height);
  37312. }
  37313. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37314. effect.setArray("blurWeights", blurWeights);
  37315. effect.setFloat("multiplier", _this.gaussMultiplier);
  37316. };
  37317. };
  37318. // Create horizontal gaussian blur post-processes
  37319. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37320. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37321. // Create vertical gaussian blur post-process
  37322. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37323. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37324. };
  37325. // Luminance generator
  37326. HDRRenderingPipeline.LUM_STEPS = 6;
  37327. return HDRRenderingPipeline;
  37328. })(BABYLON.PostProcessRenderPipeline);
  37329. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37330. })(BABYLON || (BABYLON = {}));
  37331. var BABYLON;
  37332. (function (BABYLON) {
  37333. var FaceAdjacencies = (function () {
  37334. function FaceAdjacencies() {
  37335. this.edges = new Array();
  37336. this.edgesConnectedCount = 0;
  37337. }
  37338. return FaceAdjacencies;
  37339. })();
  37340. var EdgesRenderer = (function () {
  37341. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37342. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37343. if (epsilon === void 0) { epsilon = 0.95; }
  37344. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37345. this.edgesWidthScalerForOrthographic = 1000.0;
  37346. this.edgesWidthScalerForPerspective = 50.0;
  37347. this._linesPositions = new Array();
  37348. this._linesNormals = new Array();
  37349. this._linesIndices = new Array();
  37350. this._buffers = new Array();
  37351. this._checkVerticesInsteadOfIndices = false;
  37352. this._source = source;
  37353. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37354. this._epsilon = epsilon;
  37355. this._prepareRessources();
  37356. this._generateEdgesLines();
  37357. }
  37358. EdgesRenderer.prototype._prepareRessources = function () {
  37359. if (this._lineShader) {
  37360. return;
  37361. }
  37362. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37363. attributes: ["position", "normal"],
  37364. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37365. });
  37366. this._lineShader.disableDepthWrite = true;
  37367. this._lineShader.backFaceCulling = false;
  37368. };
  37369. EdgesRenderer.prototype.dispose = function () {
  37370. this._vb0.dispose();
  37371. this._vb1.dispose();
  37372. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37373. this._lineShader.dispose();
  37374. };
  37375. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37376. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37377. return 0;
  37378. }
  37379. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37380. return 1;
  37381. }
  37382. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37383. return 2;
  37384. }
  37385. return -1;
  37386. };
  37387. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37388. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37389. return 0;
  37390. }
  37391. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37392. return 1;
  37393. }
  37394. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37395. return 2;
  37396. }
  37397. return -1;
  37398. };
  37399. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37400. var needToCreateLine;
  37401. if (edge === undefined) {
  37402. needToCreateLine = true;
  37403. }
  37404. else {
  37405. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37406. needToCreateLine = dotProduct < this._epsilon;
  37407. }
  37408. if (needToCreateLine) {
  37409. var offset = this._linesPositions.length / 3;
  37410. var normal = p0.subtract(p1);
  37411. normal.normalize();
  37412. // Positions
  37413. this._linesPositions.push(p0.x);
  37414. this._linesPositions.push(p0.y);
  37415. this._linesPositions.push(p0.z);
  37416. this._linesPositions.push(p0.x);
  37417. this._linesPositions.push(p0.y);
  37418. this._linesPositions.push(p0.z);
  37419. this._linesPositions.push(p1.x);
  37420. this._linesPositions.push(p1.y);
  37421. this._linesPositions.push(p1.z);
  37422. this._linesPositions.push(p1.x);
  37423. this._linesPositions.push(p1.y);
  37424. this._linesPositions.push(p1.z);
  37425. // Normals
  37426. this._linesNormals.push(p1.x);
  37427. this._linesNormals.push(p1.y);
  37428. this._linesNormals.push(p1.z);
  37429. this._linesNormals.push(-1);
  37430. this._linesNormals.push(p1.x);
  37431. this._linesNormals.push(p1.y);
  37432. this._linesNormals.push(p1.z);
  37433. this._linesNormals.push(1);
  37434. this._linesNormals.push(p0.x);
  37435. this._linesNormals.push(p0.y);
  37436. this._linesNormals.push(p0.z);
  37437. this._linesNormals.push(-1);
  37438. this._linesNormals.push(p0.x);
  37439. this._linesNormals.push(p0.y);
  37440. this._linesNormals.push(p0.z);
  37441. this._linesNormals.push(1);
  37442. // Indices
  37443. this._linesIndices.push(offset);
  37444. this._linesIndices.push(offset + 1);
  37445. this._linesIndices.push(offset + 2);
  37446. this._linesIndices.push(offset);
  37447. this._linesIndices.push(offset + 2);
  37448. this._linesIndices.push(offset + 3);
  37449. }
  37450. };
  37451. EdgesRenderer.prototype._generateEdgesLines = function () {
  37452. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37453. var indices = this._source.getIndices();
  37454. // First let's find adjacencies
  37455. var adjacencies = new Array();
  37456. var faceNormals = new Array();
  37457. var index;
  37458. var faceAdjacencies;
  37459. // Prepare faces
  37460. for (index = 0; index < indices.length; index += 3) {
  37461. faceAdjacencies = new FaceAdjacencies();
  37462. var p0Index = indices[index];
  37463. var p1Index = indices[index + 1];
  37464. var p2Index = indices[index + 2];
  37465. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37466. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37467. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37468. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37469. faceNormal.normalize();
  37470. faceNormals.push(faceNormal);
  37471. adjacencies.push(faceAdjacencies);
  37472. }
  37473. // Scan
  37474. for (index = 0; index < adjacencies.length; index++) {
  37475. faceAdjacencies = adjacencies[index];
  37476. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37477. var otherFaceAdjacencies = adjacencies[otherIndex];
  37478. if (faceAdjacencies.edgesConnectedCount === 3) {
  37479. break;
  37480. }
  37481. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37482. continue;
  37483. }
  37484. var otherP0 = indices[otherIndex * 3];
  37485. var otherP1 = indices[otherIndex * 3 + 1];
  37486. var otherP2 = indices[otherIndex * 3 + 2];
  37487. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37488. var otherEdgeIndex;
  37489. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37490. continue;
  37491. }
  37492. switch (edgeIndex) {
  37493. case 0:
  37494. if (this._checkVerticesInsteadOfIndices) {
  37495. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37496. }
  37497. else {
  37498. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37499. }
  37500. break;
  37501. case 1:
  37502. if (this._checkVerticesInsteadOfIndices) {
  37503. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37504. }
  37505. else {
  37506. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37507. }
  37508. break;
  37509. case 2:
  37510. if (this._checkVerticesInsteadOfIndices) {
  37511. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37512. }
  37513. else {
  37514. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37515. }
  37516. break;
  37517. }
  37518. if (otherEdgeIndex === -1) {
  37519. continue;
  37520. }
  37521. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37522. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37523. faceAdjacencies.edgesConnectedCount++;
  37524. otherFaceAdjacencies.edgesConnectedCount++;
  37525. if (faceAdjacencies.edgesConnectedCount === 3) {
  37526. break;
  37527. }
  37528. }
  37529. }
  37530. }
  37531. // Create lines
  37532. for (index = 0; index < adjacencies.length; index++) {
  37533. // 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
  37534. var current = adjacencies[index];
  37535. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37536. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37537. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37538. }
  37539. // Merge into a single mesh
  37540. var engine = this._source.getScene().getEngine();
  37541. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37542. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37543. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37544. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37545. this._ib = engine.createIndexBuffer(this._linesIndices);
  37546. this._indicesCount = this._linesIndices.length;
  37547. };
  37548. EdgesRenderer.prototype.render = function () {
  37549. if (!this._lineShader.isReady()) {
  37550. return;
  37551. }
  37552. var scene = this._source.getScene();
  37553. var engine = scene.getEngine();
  37554. this._lineShader._preBind();
  37555. // VBOs
  37556. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37557. scene.resetCachedMaterial();
  37558. this._lineShader.setColor4("color", this._source.edgesColor);
  37559. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37560. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37561. }
  37562. else {
  37563. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37564. }
  37565. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37566. this._lineShader.bind(this._source.getWorldMatrix());
  37567. // Draw order
  37568. engine.draw(true, 0, this._indicesCount);
  37569. this._lineShader.unbind();
  37570. engine.setDepthWrite(true);
  37571. };
  37572. return EdgesRenderer;
  37573. })();
  37574. BABYLON.EdgesRenderer = EdgesRenderer;
  37575. })(BABYLON || (BABYLON = {}));
  37576. var BABYLON;
  37577. (function (BABYLON) {
  37578. (function (TonemappingOperator) {
  37579. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37580. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37581. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37582. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37583. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37584. var TonemappingOperator = BABYLON.TonemappingOperator;
  37585. ;
  37586. var TonemapPostProcess = (function (_super) {
  37587. __extends(TonemapPostProcess, _super);
  37588. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37589. var _this = this;
  37590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37591. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37592. this._operator = operator;
  37593. this.exposureAdjustment = exposureAdjustment;
  37594. var params = ["_ExposureAdjustment"];
  37595. var defines = "#define ";
  37596. if (operator === TonemappingOperator.Hable)
  37597. defines += "HABLE_TONEMAPPING";
  37598. else if (operator === TonemappingOperator.Reinhard)
  37599. defines += "REINHARD_TONEMAPPING";
  37600. else if (operator === TonemappingOperator.HejiDawson)
  37601. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37602. else if (operator === TonemappingOperator.Photographic)
  37603. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37604. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37605. this.onApply = function (effect) {
  37606. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37607. };
  37608. }
  37609. return TonemapPostProcess;
  37610. })(BABYLON.PostProcess);
  37611. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37612. })(BABYLON || (BABYLON = {}));
  37613. var BABYLON;
  37614. (function (BABYLON) {
  37615. var ReflectionProbe = (function () {
  37616. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37617. var _this = this;
  37618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37619. this.name = name;
  37620. this._viewMatrix = BABYLON.Matrix.Identity();
  37621. this._target = BABYLON.Vector3.Zero();
  37622. this._add = BABYLON.Vector3.Zero();
  37623. this.position = BABYLON.Vector3.Zero();
  37624. this._scene = scene;
  37625. this._scene.reflectionProbes.push(this);
  37626. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37627. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37628. switch (faceIndex) {
  37629. case 0:
  37630. _this._add.copyFromFloats(1, 0, 0);
  37631. break;
  37632. case 1:
  37633. _this._add.copyFromFloats(-1, 0, 0);
  37634. break;
  37635. case 2:
  37636. _this._add.copyFromFloats(0, -1, 0);
  37637. break;
  37638. case 3:
  37639. _this._add.copyFromFloats(0, 1, 0);
  37640. break;
  37641. case 4:
  37642. _this._add.copyFromFloats(0, 0, 1);
  37643. break;
  37644. case 5:
  37645. _this._add.copyFromFloats(0, 0, -1);
  37646. break;
  37647. }
  37648. if (_this._attachedMesh) {
  37649. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37650. }
  37651. _this.position.addToRef(_this._add, _this._target);
  37652. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37653. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37654. };
  37655. this._renderTargetTexture.onAfterUnbind = function () {
  37656. scene.updateTransformMatrix(true);
  37657. };
  37658. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37659. }
  37660. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37661. get: function () {
  37662. return this._renderTargetTexture.refreshRate;
  37663. },
  37664. set: function (value) {
  37665. this._renderTargetTexture.refreshRate = value;
  37666. },
  37667. enumerable: true,
  37668. configurable: true
  37669. });
  37670. ReflectionProbe.prototype.getScene = function () {
  37671. return this._scene;
  37672. };
  37673. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37674. get: function () {
  37675. return this._renderTargetTexture;
  37676. },
  37677. enumerable: true,
  37678. configurable: true
  37679. });
  37680. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37681. get: function () {
  37682. return this._renderTargetTexture.renderList;
  37683. },
  37684. enumerable: true,
  37685. configurable: true
  37686. });
  37687. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37688. this._attachedMesh = mesh;
  37689. };
  37690. ReflectionProbe.prototype.dispose = function () {
  37691. var index = this._scene.reflectionProbes.indexOf(this);
  37692. if (index !== -1) {
  37693. // Remove from the scene if found
  37694. this._scene.reflectionProbes.splice(index, 1);
  37695. }
  37696. if (this._renderTargetTexture) {
  37697. this._renderTargetTexture.dispose();
  37698. this._renderTargetTexture = null;
  37699. }
  37700. };
  37701. return ReflectionProbe;
  37702. })();
  37703. BABYLON.ReflectionProbe = ReflectionProbe;
  37704. })(BABYLON || (BABYLON = {}));
  37705. var BABYLON;
  37706. (function (BABYLON) {
  37707. var SolidParticle = (function () {
  37708. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37709. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37710. this.position = BABYLON.Vector3.Zero(); // position
  37711. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37712. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37713. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37714. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37715. this.alive = true; // alive
  37716. this.idx = particleIndex;
  37717. this._pos = positionIndex;
  37718. this._model = model;
  37719. this.shapeId = shapeId;
  37720. this.idxInShape = idxInShape;
  37721. }
  37722. return SolidParticle;
  37723. })();
  37724. BABYLON.SolidParticle = SolidParticle;
  37725. var ModelShape = (function () {
  37726. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37727. this.shapeID = id;
  37728. this._shape = shape;
  37729. this._shapeUV = shapeUV;
  37730. this._positionFunction = posFunction;
  37731. this._vertexFunction = vtxFunction;
  37732. }
  37733. return ModelShape;
  37734. })();
  37735. BABYLON.ModelShape = ModelShape;
  37736. })(BABYLON || (BABYLON = {}));
  37737. var BABYLON;
  37738. (function (BABYLON) {
  37739. /**
  37740. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37741. */
  37742. var SolidParticleSystem = (function () {
  37743. /**
  37744. * Creates a SPS (Solid Particle System) object.
  37745. * @param name the SPS name, this will be the underlying mesh name
  37746. * @param scene the scene in which the SPS is added
  37747. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37748. */
  37749. function SolidParticleSystem(name, scene, options) {
  37750. // public members
  37751. /**
  37752. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37753. * Example : var p = SPS.particles[i];
  37754. */
  37755. this.particles = new Array();
  37756. /**
  37757. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37758. */
  37759. this.nbParticles = 0;
  37760. /**
  37761. * If the particles must ever face the camera (default false). Useful for planar particles.
  37762. */
  37763. this.billboard = false;
  37764. /**
  37765. * This a counter ofr your own usage. It's not set by any SPS functions.
  37766. */
  37767. this.counter = 0;
  37768. /**
  37769. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37770. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37771. */
  37772. this.vars = {};
  37773. this._positions = new Array();
  37774. this._indices = new Array();
  37775. this._normals = new Array();
  37776. this._colors = new Array();
  37777. this._uvs = new Array();
  37778. this._index = 0; // indices index
  37779. this._updatable = true;
  37780. this._pickable = false;
  37781. this._isVisibilityBoxLocked = false;
  37782. this._alwaysVisible = false;
  37783. this._shapeCounter = 0;
  37784. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37785. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37786. this._computeParticleColor = true;
  37787. this._computeParticleTexture = true;
  37788. this._computeParticleRotation = true;
  37789. this._computeParticleVertex = false;
  37790. this._computeBoundingBox = false;
  37791. this._cam_axisZ = BABYLON.Vector3.Zero();
  37792. this._cam_axisY = BABYLON.Vector3.Zero();
  37793. this._cam_axisX = BABYLON.Vector3.Zero();
  37794. this._axisX = BABYLON.Axis.X;
  37795. this._axisY = BABYLON.Axis.Y;
  37796. this._axisZ = BABYLON.Axis.Z;
  37797. this._fakeCamPos = BABYLON.Vector3.Zero();
  37798. this._rotMatrix = new BABYLON.Matrix();
  37799. this._invertMatrix = new BABYLON.Matrix();
  37800. this._rotated = BABYLON.Vector3.Zero();
  37801. this._quaternion = new BABYLON.Quaternion();
  37802. this._vertex = BABYLON.Vector3.Zero();
  37803. this._normal = BABYLON.Vector3.Zero();
  37804. this._yaw = 0.0;
  37805. this._pitch = 0.0;
  37806. this._roll = 0.0;
  37807. this._halfroll = 0.0;
  37808. this._halfpitch = 0.0;
  37809. this._halfyaw = 0.0;
  37810. this._sinRoll = 0.0;
  37811. this._cosRoll = 0.0;
  37812. this._sinPitch = 0.0;
  37813. this._cosPitch = 0.0;
  37814. this._sinYaw = 0.0;
  37815. this._cosYaw = 0.0;
  37816. this._w = 0.0;
  37817. this._minimum = BABYLON.Tmp.Vector3[0];
  37818. this._maximum = BABYLON.Tmp.Vector3[1];
  37819. this.name = name;
  37820. this._scene = scene;
  37821. this._camera = scene.activeCamera;
  37822. this._pickable = options ? options.isPickable : false;
  37823. if (options && options.updatable) {
  37824. this._updatable = options.updatable;
  37825. }
  37826. else {
  37827. this._updatable = true;
  37828. }
  37829. if (this._pickable) {
  37830. this.pickedParticles = [];
  37831. }
  37832. }
  37833. /**
  37834. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37835. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37836. */
  37837. SolidParticleSystem.prototype.buildMesh = function () {
  37838. if (this.nbParticles === 0) {
  37839. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37840. this.addShape(triangle, 1);
  37841. triangle.dispose();
  37842. }
  37843. this._positions32 = new Float32Array(this._positions);
  37844. this._uvs32 = new Float32Array(this._uvs);
  37845. this._colors32 = new Float32Array(this._colors);
  37846. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37847. this._normals32 = new Float32Array(this._normals);
  37848. this._fixedNormal32 = new Float32Array(this._normals);
  37849. var vertexData = new BABYLON.VertexData();
  37850. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37851. vertexData.indices = this._indices;
  37852. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37853. if (this._uvs32) {
  37854. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37855. ;
  37856. }
  37857. if (this._colors32) {
  37858. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37859. }
  37860. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37861. vertexData.applyToMesh(mesh, this._updatable);
  37862. this.mesh = mesh;
  37863. this.mesh.isPickable = this._pickable;
  37864. // free memory
  37865. this._positions = null;
  37866. this._normals = null;
  37867. this._uvs = null;
  37868. this._colors = null;
  37869. if (!this._updatable) {
  37870. this.particles.length = 0;
  37871. }
  37872. return mesh;
  37873. };
  37874. /**
  37875. * Digests the mesh and generates as many solid particles in the system as wanted.
  37876. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37877. * Thus the particles generated from digest() have their property "positiion" yet set.
  37878. * @param mesh the mesh to be digested
  37879. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37880. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37881. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37882. */
  37883. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37884. var size = (options && options.facetNb) || 1;
  37885. var number = (options && options.number);
  37886. var delta = (options && options.delta) || 0;
  37887. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37888. var meshInd = mesh.getIndices();
  37889. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37890. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37891. var f = 0; // facet counter
  37892. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37893. // compute size from number
  37894. if (number) {
  37895. number = (number > totalFacets) ? totalFacets : number;
  37896. size = Math.round(totalFacets / number);
  37897. delta = 0;
  37898. }
  37899. else {
  37900. size = (size > totalFacets) ? totalFacets : size;
  37901. }
  37902. var facetPos = []; // submesh positions
  37903. var facetInd = []; // submesh indices
  37904. var facetUV = []; // submesh UV
  37905. var facetCol = []; // submesh colors
  37906. var barycenter = BABYLON.Tmp.Vector3[0];
  37907. var rand;
  37908. var sizeO = size;
  37909. while (f < totalFacets) {
  37910. size = sizeO + Math.floor((1 + delta) * Math.random());
  37911. if (f > totalFacets - size) {
  37912. size = totalFacets - f;
  37913. }
  37914. // reset temp arrays
  37915. facetPos.length = 0;
  37916. facetInd.length = 0;
  37917. facetUV.length = 0;
  37918. facetCol.length = 0;
  37919. // iterate over "size" facets
  37920. var fi = 0;
  37921. for (var j = f * 3; j < (f + size) * 3; j++) {
  37922. facetInd.push(fi);
  37923. var i = meshInd[j];
  37924. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37925. if (meshUV) {
  37926. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37927. }
  37928. if (meshCol) {
  37929. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37930. }
  37931. fi++;
  37932. }
  37933. // create a model shape for each single particle
  37934. var idx = this.nbParticles;
  37935. var shape = this._posToShape(facetPos);
  37936. var shapeUV = this._uvsToShapeUV(facetUV);
  37937. // compute the barycenter of the shape
  37938. var v;
  37939. for (v = 0; v < shape.length; v++) {
  37940. barycenter.addInPlace(shape[v]);
  37941. }
  37942. barycenter.scaleInPlace(1 / shape.length);
  37943. // shift the shape from its barycenter to the origin
  37944. for (v = 0; v < shape.length; v++) {
  37945. shape[v].subtractInPlace(barycenter);
  37946. }
  37947. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37948. // add the particle in the SPS
  37949. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37950. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37951. // initialize the particle position
  37952. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37953. this._index += shape.length;
  37954. idx++;
  37955. this.nbParticles++;
  37956. this._shapeCounter++;
  37957. f += size;
  37958. }
  37959. };
  37960. //reset copy
  37961. SolidParticleSystem.prototype._resetCopy = function () {
  37962. this._copy.position.x = 0;
  37963. this._copy.position.y = 0;
  37964. this._copy.position.z = 0;
  37965. this._copy.rotation.x = 0;
  37966. this._copy.rotation.y = 0;
  37967. this._copy.rotation.z = 0;
  37968. this._copy.quaternion = null;
  37969. this._copy.scale.x = 1;
  37970. this._copy.scale.y = 1;
  37971. this._copy.scale.z = 1;
  37972. this._copy.uvs.x = 0;
  37973. this._copy.uvs.y = 0;
  37974. this._copy.uvs.z = 1;
  37975. this._copy.uvs.w = 1;
  37976. this._copy.color = null;
  37977. };
  37978. // _meshBuilder : inserts the shape model in the global SPS mesh
  37979. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37980. var i;
  37981. var u = 0;
  37982. var c = 0;
  37983. this._resetCopy();
  37984. if (options && options.positionFunction) {
  37985. options.positionFunction(this._copy, idx, idxInShape);
  37986. }
  37987. if (this._copy.quaternion) {
  37988. this._quaternion.x = this._copy.quaternion.x;
  37989. this._quaternion.y = this._copy.quaternion.y;
  37990. this._quaternion.z = this._copy.quaternion.z;
  37991. this._quaternion.w = this._copy.quaternion.w;
  37992. }
  37993. else {
  37994. this._yaw = this._copy.rotation.y;
  37995. this._pitch = this._copy.rotation.x;
  37996. this._roll = this._copy.rotation.z;
  37997. this._quaternionRotationYPR();
  37998. }
  37999. this._quaternionToRotationMatrix();
  38000. for (i = 0; i < shape.length; i++) {
  38001. this._vertex.x = shape[i].x;
  38002. this._vertex.y = shape[i].y;
  38003. this._vertex.z = shape[i].z;
  38004. if (options && options.vertexFunction) {
  38005. options.vertexFunction(this._copy, this._vertex, i);
  38006. }
  38007. this._vertex.x *= this._copy.scale.x;
  38008. this._vertex.y *= this._copy.scale.y;
  38009. this._vertex.z *= this._copy.scale.z;
  38010. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38011. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38012. if (meshUV) {
  38013. 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);
  38014. u += 2;
  38015. }
  38016. if (this._copy.color) {
  38017. this._color = this._copy.color;
  38018. }
  38019. else if (meshCol && meshCol[c]) {
  38020. this._color.r = meshCol[c];
  38021. this._color.g = meshCol[c + 1];
  38022. this._color.b = meshCol[c + 2];
  38023. this._color.a = meshCol[c + 3];
  38024. }
  38025. else {
  38026. this._color.r = 1;
  38027. this._color.g = 1;
  38028. this._color.b = 1;
  38029. this._color.a = 1;
  38030. }
  38031. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38032. c += 4;
  38033. }
  38034. for (i = 0; i < meshInd.length; i++) {
  38035. indices.push(p + meshInd[i]);
  38036. }
  38037. if (this._pickable) {
  38038. var nbfaces = meshInd.length / 3;
  38039. for (i = 0; i < nbfaces; i++) {
  38040. this.pickedParticles.push({ idx: idx, faceId: i });
  38041. }
  38042. }
  38043. };
  38044. // returns a shape array from positions array
  38045. SolidParticleSystem.prototype._posToShape = function (positions) {
  38046. var shape = [];
  38047. for (var i = 0; i < positions.length; i += 3) {
  38048. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38049. }
  38050. return shape;
  38051. };
  38052. // returns a shapeUV array from a Vector4 uvs
  38053. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38054. var shapeUV = [];
  38055. if (uvs) {
  38056. for (var i = 0; i < uvs.length; i++)
  38057. shapeUV.push(uvs[i]);
  38058. }
  38059. return shapeUV;
  38060. };
  38061. // adds a new particle object in the particles array
  38062. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  38063. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  38064. };
  38065. /**
  38066. * Adds some particles to the SPS from the model shape.
  38067. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  38068. * @param mesh any Mesh object that will be used as a model for the solid particles.
  38069. * @param nb the number of particles to be created from this model
  38070. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  38071. */
  38072. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38073. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38074. var meshInd = mesh.getIndices();
  38075. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38076. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38077. var shape = this._posToShape(meshPos);
  38078. var shapeUV = this._uvsToShapeUV(meshUV);
  38079. var posfunc = options ? options.positionFunction : null;
  38080. var vtxfunc = options ? options.vertexFunction : null;
  38081. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38082. // particles
  38083. var idx = this.nbParticles;
  38084. for (var i = 0; i < nb; i++) {
  38085. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  38086. if (this._updatable) {
  38087. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  38088. }
  38089. this._index += shape.length;
  38090. idx++;
  38091. }
  38092. this.nbParticles += nb;
  38093. this._shapeCounter++;
  38094. return this._shapeCounter - 1;
  38095. };
  38096. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38097. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38098. this._resetCopy();
  38099. if (particle._model._positionFunction) {
  38100. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38101. }
  38102. if (this._copy.quaternion) {
  38103. this._quaternion.x = this._copy.quaternion.x;
  38104. this._quaternion.y = this._copy.quaternion.y;
  38105. this._quaternion.z = this._copy.quaternion.z;
  38106. this._quaternion.w = this._copy.quaternion.w;
  38107. }
  38108. else {
  38109. this._yaw = this._copy.rotation.y;
  38110. this._pitch = this._copy.rotation.x;
  38111. this._roll = this._copy.rotation.z;
  38112. this._quaternionRotationYPR();
  38113. }
  38114. this._quaternionToRotationMatrix();
  38115. this._shape = particle._model._shape;
  38116. for (var pt = 0; pt < this._shape.length; pt++) {
  38117. this._vertex.x = this._shape[pt].x;
  38118. this._vertex.y = this._shape[pt].y;
  38119. this._vertex.z = this._shape[pt].z;
  38120. if (particle._model._vertexFunction) {
  38121. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38122. }
  38123. this._vertex.x *= this._copy.scale.x;
  38124. this._vertex.y *= this._copy.scale.y;
  38125. this._vertex.z *= this._copy.scale.z;
  38126. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38127. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38128. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38129. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38130. }
  38131. particle.position.x = 0;
  38132. particle.position.y = 0;
  38133. particle.position.z = 0;
  38134. particle.rotation.x = 0;
  38135. particle.rotation.y = 0;
  38136. particle.rotation.z = 0;
  38137. particle.quaternion = null;
  38138. particle.scale.x = 1;
  38139. particle.scale.y = 1;
  38140. particle.scale.z = 1;
  38141. };
  38142. /**
  38143. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38144. */
  38145. SolidParticleSystem.prototype.rebuildMesh = function () {
  38146. for (var p = 0; p < this.particles.length; p++) {
  38147. this._rebuildParticle(this.particles[p]);
  38148. }
  38149. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38150. };
  38151. /**
  38152. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38153. * This method calls updateParticle() for each particles of the SPS.
  38154. * For an animated SPS, it is usually called within the render loop.
  38155. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38156. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38157. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38158. */
  38159. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38160. if (start === void 0) { start = 0; }
  38161. if (end === void 0) { end = this.nbParticles - 1; }
  38162. if (update === void 0) { update = true; }
  38163. if (!this._updatable) {
  38164. return;
  38165. }
  38166. // custom beforeUpdate
  38167. this.beforeUpdateParticles(start, end, update);
  38168. this._cam_axisX.x = 1;
  38169. this._cam_axisX.y = 0;
  38170. this._cam_axisX.z = 0;
  38171. this._cam_axisY.x = 0;
  38172. this._cam_axisY.y = 1;
  38173. this._cam_axisY.z = 0;
  38174. this._cam_axisZ.x = 0;
  38175. this._cam_axisZ.y = 0;
  38176. this._cam_axisZ.z = 1;
  38177. // if the particles will always face the camera
  38178. if (this.billboard) {
  38179. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38180. this._yaw = this.mesh.rotation.y;
  38181. this._pitch = this.mesh.rotation.x;
  38182. this._roll = this.mesh.rotation.z;
  38183. this._quaternionRotationYPR();
  38184. this._quaternionToRotationMatrix();
  38185. this._rotMatrix.invertToRef(this._invertMatrix);
  38186. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38187. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38188. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38189. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38190. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38191. this._cam_axisY.normalize();
  38192. this._cam_axisX.normalize();
  38193. this._cam_axisZ.normalize();
  38194. }
  38195. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38196. var idx = 0;
  38197. var index = 0;
  38198. var colidx = 0;
  38199. var colorIndex = 0;
  38200. var uvidx = 0;
  38201. var uvIndex = 0;
  38202. if (this._computeBoundingBox) {
  38203. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38204. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38205. }
  38206. // particle loop
  38207. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38208. for (var p = start; p <= end; p++) {
  38209. this._particle = this.particles[p];
  38210. this._shape = this._particle._model._shape;
  38211. this._shapeUV = this._particle._model._shapeUV;
  38212. // call to custom user function to update the particle properties
  38213. this.updateParticle(this._particle);
  38214. // particle rotation matrix
  38215. if (this.billboard) {
  38216. this._particle.rotation.x = 0.0;
  38217. this._particle.rotation.y = 0.0;
  38218. }
  38219. if (this._computeParticleRotation) {
  38220. if (this._particle.quaternion) {
  38221. this._quaternion.x = this._particle.quaternion.x;
  38222. this._quaternion.y = this._particle.quaternion.y;
  38223. this._quaternion.z = this._particle.quaternion.z;
  38224. this._quaternion.w = this._particle.quaternion.w;
  38225. }
  38226. else {
  38227. this._yaw = this._particle.rotation.y;
  38228. this._pitch = this._particle.rotation.x;
  38229. this._roll = this._particle.rotation.z;
  38230. this._quaternionRotationYPR();
  38231. }
  38232. this._quaternionToRotationMatrix();
  38233. }
  38234. for (var pt = 0; pt < this._shape.length; pt++) {
  38235. idx = index + pt * 3;
  38236. colidx = colorIndex + pt * 4;
  38237. uvidx = uvIndex + pt * 2;
  38238. this._vertex.x = this._shape[pt].x;
  38239. this._vertex.y = this._shape[pt].y;
  38240. this._vertex.z = this._shape[pt].z;
  38241. if (this._computeParticleVertex) {
  38242. this.updateParticleVertex(this._particle, this._vertex, pt);
  38243. }
  38244. // positions
  38245. this._vertex.x *= this._particle.scale.x;
  38246. this._vertex.y *= this._particle.scale.y;
  38247. this._vertex.z *= this._particle.scale.z;
  38248. 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];
  38249. 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;
  38250. 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;
  38251. 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;
  38252. 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;
  38253. 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;
  38254. 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;
  38255. if (this._computeBoundingBox) {
  38256. if (this._positions32[idx] < this._minimum.x) {
  38257. this._minimum.x = this._positions32[idx];
  38258. }
  38259. if (this._positions32[idx] > this._maximum.x) {
  38260. this._maximum.x = this._positions32[idx];
  38261. }
  38262. if (this._positions32[idx + 1] < this._minimum.y) {
  38263. this._minimum.y = this._positions32[idx + 1];
  38264. }
  38265. if (this._positions32[idx + 1] > this._maximum.y) {
  38266. this._maximum.y = this._positions32[idx + 1];
  38267. }
  38268. if (this._positions32[idx + 2] < this._minimum.z) {
  38269. this._minimum.z = this._positions32[idx + 2];
  38270. }
  38271. if (this._positions32[idx + 2] > this._maximum.z) {
  38272. this._maximum.z = this._positions32[idx + 2];
  38273. }
  38274. }
  38275. // normals : if the particles can't be morphed then just rotate the normals
  38276. if (!this._computeParticleVertex && !this.billboard) {
  38277. this._normal.x = this._fixedNormal32[idx];
  38278. this._normal.y = this._fixedNormal32[idx + 1];
  38279. this._normal.z = this._fixedNormal32[idx + 2];
  38280. 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];
  38281. 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;
  38282. 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;
  38283. 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;
  38284. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38285. 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;
  38286. 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;
  38287. }
  38288. if (this._computeParticleColor) {
  38289. this._colors32[colidx] = this._particle.color.r;
  38290. this._colors32[colidx + 1] = this._particle.color.g;
  38291. this._colors32[colidx + 2] = this._particle.color.b;
  38292. this._colors32[colidx + 3] = this._particle.color.a;
  38293. }
  38294. if (this._computeParticleTexture) {
  38295. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38296. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38297. }
  38298. }
  38299. index = idx + 3;
  38300. colorIndex = colidx + 4;
  38301. uvIndex = uvidx + 2;
  38302. }
  38303. if (update) {
  38304. if (this._computeParticleColor) {
  38305. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38306. }
  38307. if (this._computeParticleTexture) {
  38308. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38309. }
  38310. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38311. if (!this.mesh.areNormalsFrozen) {
  38312. if (this._computeParticleVertex || this.billboard) {
  38313. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38314. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38315. for (var i = 0; i < this._normals32.length; i++) {
  38316. this._fixedNormal32[i] = this._normals32[i];
  38317. }
  38318. }
  38319. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38320. }
  38321. }
  38322. if (this._computeBoundingBox) {
  38323. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38324. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38325. }
  38326. this.afterUpdateParticles(start, end, update);
  38327. };
  38328. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38329. this._halfroll = this._roll * 0.5;
  38330. this._halfpitch = this._pitch * 0.5;
  38331. this._halfyaw = this._yaw * 0.5;
  38332. this._sinRoll = Math.sin(this._halfroll);
  38333. this._cosRoll = Math.cos(this._halfroll);
  38334. this._sinPitch = Math.sin(this._halfpitch);
  38335. this._cosPitch = Math.cos(this._halfpitch);
  38336. this._sinYaw = Math.sin(this._halfyaw);
  38337. this._cosYaw = Math.cos(this._halfyaw);
  38338. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38339. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38340. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38341. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38342. };
  38343. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38344. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38345. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38346. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38347. this._rotMatrix.m[3] = 0;
  38348. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38349. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38350. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38351. this._rotMatrix.m[7] = 0;
  38352. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38353. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38354. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38355. this._rotMatrix.m[11] = 0;
  38356. this._rotMatrix.m[12] = 0;
  38357. this._rotMatrix.m[13] = 0;
  38358. this._rotMatrix.m[14] = 0;
  38359. this._rotMatrix.m[15] = 1.0;
  38360. };
  38361. /**
  38362. * Disposes the SPS
  38363. */
  38364. SolidParticleSystem.prototype.dispose = function () {
  38365. this.mesh.dispose();
  38366. this.vars = null;
  38367. // drop references to internal big arrays for the GC
  38368. this._positions = null;
  38369. this._indices = null;
  38370. this._normals = null;
  38371. this._uvs = null;
  38372. this._colors = null;
  38373. this._positions32 = null;
  38374. this._normals32 = null;
  38375. this._fixedNormal32 = null;
  38376. this._uvs32 = null;
  38377. this._colors32 = null;
  38378. this.pickedParticles = null;
  38379. };
  38380. /**
  38381. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38382. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38383. */
  38384. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38385. if (!this._isVisibilityBoxLocked) {
  38386. this.mesh.refreshBoundingInfo();
  38387. }
  38388. };
  38389. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38390. * @param size the size (float) of the visibility box
  38391. * note : this doesn't lock the SPS mesh bounding box.
  38392. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38393. */
  38394. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38395. var vis = size / 2;
  38396. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38397. };
  38398. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38399. // getter and setter
  38400. /**
  38401. * True if the SPS is set as always visible
  38402. */
  38403. get: function () {
  38404. return this._alwaysVisible;
  38405. },
  38406. /**
  38407. * Sets the SPS as always visible or not
  38408. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38409. */
  38410. set: function (val) {
  38411. this._alwaysVisible = val;
  38412. this.mesh.alwaysSelectAsActiveMesh = val;
  38413. },
  38414. enumerable: true,
  38415. configurable: true
  38416. });
  38417. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38418. /**
  38419. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38420. */
  38421. get: function () {
  38422. return this._isVisibilityBoxLocked;
  38423. },
  38424. /**
  38425. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38426. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38427. */
  38428. set: function (val) {
  38429. this._isVisibilityBoxLocked = val;
  38430. this.mesh.getBoundingInfo().isLocked = val;
  38431. },
  38432. enumerable: true,
  38433. configurable: true
  38434. });
  38435. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38436. // getters
  38437. get: function () {
  38438. return this._computeParticleRotation;
  38439. },
  38440. // Optimizer setters
  38441. /**
  38442. * Tells to setParticles() to compute the particle rotations or not.
  38443. * Default value : true. The SPS is faster when it's set to false.
  38444. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38445. */
  38446. set: function (val) {
  38447. this._computeParticleRotation = val;
  38448. },
  38449. enumerable: true,
  38450. configurable: true
  38451. });
  38452. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38453. get: function () {
  38454. return this._computeParticleColor;
  38455. },
  38456. /**
  38457. * Tells to setParticles() to compute the particle colors or not.
  38458. * Default value : true. The SPS is faster when it's set to false.
  38459. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38460. */
  38461. set: function (val) {
  38462. this._computeParticleColor = val;
  38463. },
  38464. enumerable: true,
  38465. configurable: true
  38466. });
  38467. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38468. get: function () {
  38469. return this._computeParticleTexture;
  38470. },
  38471. /**
  38472. * Tells to setParticles() to compute the particle textures or not.
  38473. * Default value : true. The SPS is faster when it's set to false.
  38474. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38475. */
  38476. set: function (val) {
  38477. this._computeParticleTexture = val;
  38478. },
  38479. enumerable: true,
  38480. configurable: true
  38481. });
  38482. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38483. get: function () {
  38484. return this._computeParticleVertex;
  38485. },
  38486. /**
  38487. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38488. * Default value : false. The SPS is faster when it's set to false.
  38489. * Note : the particle custom vertex positions aren't stored values.
  38490. */
  38491. set: function (val) {
  38492. this._computeParticleVertex = val;
  38493. },
  38494. enumerable: true,
  38495. configurable: true
  38496. });
  38497. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38498. get: function () {
  38499. return this._computeBoundingBox;
  38500. },
  38501. /**
  38502. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38503. */
  38504. set: function (val) {
  38505. this._computeBoundingBox = val;
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. // =======================================================================
  38511. // Particle behavior logic
  38512. // these following methods may be overwritten by the user to fit his needs
  38513. /**
  38514. * This function does nothing. It may be overwritten to set all the particles first values.
  38515. * The SPS doesn't call this function, you may have to call it by your own.
  38516. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38517. */
  38518. SolidParticleSystem.prototype.initParticles = function () {
  38519. };
  38520. /**
  38521. * This function does nothing. It may be overwritten to recycle a particle.
  38522. * The SPS doesn't call this function, you may have to call it by your own.
  38523. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38524. */
  38525. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38526. return particle;
  38527. };
  38528. /**
  38529. * Updates a particle : this function should be overwritten by the user.
  38530. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38531. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38532. * ex : just set a particle position or velocity and recycle conditions
  38533. */
  38534. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38535. return particle;
  38536. };
  38537. /**
  38538. * Updates a vertex of a particle : it can be overwritten by the user.
  38539. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38540. * @param particle the current particle
  38541. * @param vertex the current index of the current particle
  38542. * @param pt the index of the current vertex in the particle shape
  38543. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38544. * ex : just set a vertex particle position
  38545. */
  38546. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38547. return vertex;
  38548. };
  38549. /**
  38550. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38551. * This does nothing and may be overwritten by the user.
  38552. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38553. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38554. * @param update the boolean update value actually passed to setParticles()
  38555. */
  38556. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38557. };
  38558. /**
  38559. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38560. * This will be passed three parameters.
  38561. * This does nothing and may be overwritten by the user.
  38562. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38563. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38564. * @param update the boolean update value actually passed to setParticles()
  38565. */
  38566. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38567. };
  38568. return SolidParticleSystem;
  38569. })();
  38570. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38571. })(BABYLON || (BABYLON = {}));
  38572. var BABYLON;
  38573. (function (BABYLON) {
  38574. var Internals;
  38575. (function (Internals) {
  38576. var FileFaceOrientation = (function () {
  38577. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38578. this.name = name;
  38579. this.worldAxisForNormal = worldAxisForNormal;
  38580. this.worldAxisForFileX = worldAxisForFileX;
  38581. this.worldAxisForFileY = worldAxisForFileY;
  38582. }
  38583. return FileFaceOrientation;
  38584. })();
  38585. ;
  38586. var CubeMapToSphericalPolynomialTools = (function () {
  38587. function CubeMapToSphericalPolynomialTools() {
  38588. }
  38589. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38590. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38591. var totalSolidAngle = 0.0;
  38592. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38593. var du = 2.0 / cubeInfo.size;
  38594. var dv = du;
  38595. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38596. var minUV = du * 0.5 - 1.0;
  38597. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38598. var fileFace = this.FileFaces[faceIndex];
  38599. var dataArray = cubeInfo[fileFace.name];
  38600. var v = minUV;
  38601. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38602. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38603. // Because SP is still linear, so summation is fine in that basis.
  38604. for (var y = 0; y < cubeInfo.size; y++) {
  38605. var u = minUV;
  38606. for (var x = 0; x < cubeInfo.size; x++) {
  38607. // World direction (not normalised)
  38608. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38609. worldDirection.normalize();
  38610. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38611. if (1) {
  38612. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38613. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38614. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38615. var color = new BABYLON.Color3(r, g, b);
  38616. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38617. }
  38618. else {
  38619. if (faceIndex == 0) {
  38620. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38621. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38622. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38623. }
  38624. else if (faceIndex == 1) {
  38625. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38626. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38627. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38628. }
  38629. else if (faceIndex == 2) {
  38630. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38631. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38632. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38633. }
  38634. else if (faceIndex == 3) {
  38635. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38636. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38637. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38638. }
  38639. else if (faceIndex == 4) {
  38640. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38641. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38642. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38643. }
  38644. else if (faceIndex == 5) {
  38645. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38646. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38647. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38648. }
  38649. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  38650. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38651. }
  38652. totalSolidAngle += deltaSolidAngle;
  38653. u += du;
  38654. }
  38655. v += dv;
  38656. }
  38657. }
  38658. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  38659. var correction = correctSolidAngle / totalSolidAngle;
  38660. sphericalHarmonics.scale(correction);
  38661. // Additionally scale by pi -- audit needed
  38662. sphericalHarmonics.scale(1.0 / Math.PI);
  38663. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  38664. };
  38665. CubeMapToSphericalPolynomialTools.FileFaces = [
  38666. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  38667. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  38668. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  38669. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  38670. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  38671. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  38672. ];
  38673. return CubeMapToSphericalPolynomialTools;
  38674. })();
  38675. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  38676. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38677. })(BABYLON || (BABYLON = {}));
  38678. var BABYLON;
  38679. (function (BABYLON) {
  38680. var Internals;
  38681. (function (Internals) {
  38682. var PanoramaToCubeMapTools = (function () {
  38683. function PanoramaToCubeMapTools() {
  38684. }
  38685. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  38686. if (!float32Array) {
  38687. throw "ConvertPanoramaToCubemap: input cannot be null";
  38688. }
  38689. if (float32Array.length != inputWidth * inputHeight * 3) {
  38690. throw "ConvertPanoramaToCubemap: input size is wrong";
  38691. }
  38692. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  38693. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  38694. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  38695. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  38696. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  38697. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  38698. return {
  38699. front: textureFront,
  38700. back: textureBack,
  38701. left: textureLeft,
  38702. right: textureRight,
  38703. up: textureUp,
  38704. down: textureDown,
  38705. size: size
  38706. };
  38707. };
  38708. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  38709. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  38710. var textureArray = new Float32Array(buffer);
  38711. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  38712. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  38713. var dy = 1 / texSize;
  38714. var fy = 0;
  38715. for (var y = 0; y < texSize; y++) {
  38716. var xv1 = faceData[0];
  38717. var xv2 = faceData[2];
  38718. for (var x = 0; x < texSize; x++) {
  38719. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  38720. v.normalize();
  38721. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  38722. // 3 channels per pixels
  38723. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  38724. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  38725. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  38726. xv1 = xv1.add(rotDX1);
  38727. xv2 = xv2.add(rotDX2);
  38728. }
  38729. fy += dy;
  38730. }
  38731. return textureArray;
  38732. };
  38733. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  38734. var theta = Math.atan2(vDir.z, vDir.x);
  38735. var phi = Math.acos(vDir.y);
  38736. while (theta < -Math.PI)
  38737. theta += 2 * Math.PI;
  38738. while (theta > Math.PI)
  38739. theta -= 2 * Math.PI;
  38740. var dx = theta / Math.PI;
  38741. var dy = phi / Math.PI;
  38742. // recenter.
  38743. dx = dx * 0.5 + 0.5;
  38744. var px = Math.round(dx * inputWidth);
  38745. if (px < 0)
  38746. px = 0;
  38747. else if (px >= inputWidth)
  38748. px = inputWidth - 1;
  38749. var py = Math.round(dy * inputHeight);
  38750. if (py < 0)
  38751. py = 0;
  38752. else if (py >= inputHeight)
  38753. py = inputHeight - 1;
  38754. var inputY = (inputHeight - py - 1);
  38755. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  38756. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  38757. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  38758. return {
  38759. r: r,
  38760. g: g,
  38761. b: b
  38762. };
  38763. };
  38764. PanoramaToCubeMapTools.FACE_FRONT = [
  38765. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38766. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38767. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38768. new BABYLON.Vector3(1.0, 1.0, -1.0)
  38769. ];
  38770. PanoramaToCubeMapTools.FACE_BACK = [
  38771. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38772. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38773. new BABYLON.Vector3(1.0, 1.0, 1.0),
  38774. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  38775. ];
  38776. PanoramaToCubeMapTools.FACE_LEFT = [
  38777. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38778. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38779. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38780. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38781. ];
  38782. PanoramaToCubeMapTools.FACE_RIGHT = [
  38783. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38784. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38785. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38786. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  38787. ];
  38788. PanoramaToCubeMapTools.FACE_UP = [
  38789. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38790. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38791. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38792. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38793. ];
  38794. PanoramaToCubeMapTools.FACE_DOWN = [
  38795. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38796. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38797. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38798. new BABYLON.Vector3(1.0, -1.0, -1.0)
  38799. ];
  38800. return PanoramaToCubeMapTools;
  38801. })();
  38802. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  38803. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38804. })(BABYLON || (BABYLON = {}));
  38805. var BABYLON;
  38806. (function (BABYLON) {
  38807. var Internals;
  38808. (function (Internals) {
  38809. ;
  38810. var HDRTools = (function () {
  38811. function HDRTools() {
  38812. }
  38813. HDRTools.Ldexp = function (mantissa, exponent) {
  38814. if (exponent > 1023) {
  38815. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  38816. }
  38817. if (exponent < -1074) {
  38818. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  38819. }
  38820. return mantissa * Math.pow(2, exponent);
  38821. };
  38822. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  38823. if (exponent > 0) {
  38824. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  38825. float32array[index + 0] = red * exponent;
  38826. float32array[index + 1] = green * exponent;
  38827. float32array[index + 2] = blue * exponent;
  38828. }
  38829. else {
  38830. float32array[index + 0] = 0;
  38831. float32array[index + 1] = 0;
  38832. float32array[index + 2] = 0;
  38833. }
  38834. };
  38835. HDRTools.readStringLine = function (uint8array, startIndex) {
  38836. var line = "";
  38837. var character = "";
  38838. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  38839. character = String.fromCharCode(uint8array[i]);
  38840. if (character == "\n") {
  38841. break;
  38842. }
  38843. line += character;
  38844. }
  38845. return line;
  38846. };
  38847. /* minimal header reading. modify if you want to parse more information */
  38848. HDRTools.RGBE_ReadHeader = function (uint8array) {
  38849. var height = 0;
  38850. var width = 0;
  38851. var line = this.readStringLine(uint8array, 0);
  38852. if (line[0] != '#' || line[1] != '?') {
  38853. throw "Bad HDR Format.";
  38854. }
  38855. var endOfHeader = false;
  38856. var findFormat = false;
  38857. var lineIndex = 0;
  38858. do {
  38859. lineIndex += (line.length + 1);
  38860. line = this.readStringLine(uint8array, lineIndex);
  38861. if (line == "FORMAT=32-bit_rle_rgbe") {
  38862. findFormat = true;
  38863. }
  38864. else if (line.length == 0) {
  38865. endOfHeader = true;
  38866. }
  38867. } while (!endOfHeader);
  38868. if (!findFormat) {
  38869. throw "HDR Bad header format, unsupported FORMAT";
  38870. }
  38871. lineIndex += (line.length + 1);
  38872. line = this.readStringLine(uint8array, lineIndex);
  38873. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  38874. var match = sizeRegexp.exec(line);
  38875. // TODO. Support +Y and -X if needed.
  38876. if (match.length < 3) {
  38877. throw "HDR Bad header format, no size";
  38878. }
  38879. width = parseInt(match[2]);
  38880. height = parseInt(match[1]);
  38881. if (width < 8 || width > 0x7fff) {
  38882. throw "HDR Bad header format, unsupported size";
  38883. }
  38884. lineIndex += (line.length + 1);
  38885. return {
  38886. height: height,
  38887. width: width,
  38888. dataPosition: lineIndex
  38889. };
  38890. };
  38891. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  38892. var uint8array = new Uint8Array(buffer);
  38893. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  38894. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38895. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  38896. return cubeMapData;
  38897. };
  38898. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  38899. // Keep for multi format supports.
  38900. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38901. };
  38902. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  38903. var num_scanlines = hdrInfo.height;
  38904. var scanline_width = hdrInfo.width;
  38905. var a, b, c, d, count;
  38906. var dataIndex = hdrInfo.dataPosition;
  38907. var index = 0, endIndex = 0, i = 0;
  38908. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  38909. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  38910. // 3 channels of 4 bytes per pixel in float.
  38911. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  38912. var resultArray = new Float32Array(resultBuffer);
  38913. // read in each successive scanline
  38914. while (num_scanlines > 0) {
  38915. a = uint8array[dataIndex++];
  38916. b = uint8array[dataIndex++];
  38917. c = uint8array[dataIndex++];
  38918. d = uint8array[dataIndex++];
  38919. if (a != 2 || b != 2 || (c & 0x80)) {
  38920. // this file is not run length encoded
  38921. throw "HDR Bad header format, not RLE";
  38922. }
  38923. if (((c << 8) | d) != scanline_width) {
  38924. throw "HDR Bad header format, wrong scan line width";
  38925. }
  38926. index = 0;
  38927. // read each of the four channels for the scanline into the buffer
  38928. for (i = 0; i < 4; i++) {
  38929. endIndex = (i + 1) * scanline_width;
  38930. while (index < endIndex) {
  38931. a = uint8array[dataIndex++];
  38932. b = uint8array[dataIndex++];
  38933. if (a > 128) {
  38934. // a run of the same value
  38935. count = a - 128;
  38936. if ((count == 0) || (count > endIndex - index)) {
  38937. throw "HDR Bad Format, bad scanline data (run)";
  38938. }
  38939. while (count-- > 0) {
  38940. scanLineArray[index++] = b;
  38941. }
  38942. }
  38943. else {
  38944. // a non-run
  38945. count = a;
  38946. if ((count == 0) || (count > endIndex - index)) {
  38947. throw "HDR Bad Format, bad scanline data (non-run)";
  38948. }
  38949. scanLineArray[index++] = b;
  38950. if (--count > 0) {
  38951. for (var j = 0; j < count; j++) {
  38952. scanLineArray[index++] = uint8array[dataIndex++];
  38953. }
  38954. }
  38955. }
  38956. }
  38957. }
  38958. // now convert data from buffer into floats
  38959. for (i = 0; i < scanline_width; i++) {
  38960. a = scanLineArray[i];
  38961. b = scanLineArray[i + scanline_width];
  38962. c = scanLineArray[i + 2 * scanline_width];
  38963. d = scanLineArray[i + 3 * scanline_width];
  38964. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  38965. }
  38966. num_scanlines--;
  38967. }
  38968. return resultArray;
  38969. };
  38970. return HDRTools;
  38971. })();
  38972. Internals.HDRTools = HDRTools;
  38973. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38974. })(BABYLON || (BABYLON = {}));
  38975. var BABYLON;
  38976. (function (BABYLON) {
  38977. var Internals;
  38978. (function (Internals) {
  38979. var PMREMGenerator = (function () {
  38980. function PMREMGenerator() {
  38981. }
  38982. return PMREMGenerator;
  38983. })();
  38984. Internals.PMREMGenerator = PMREMGenerator;
  38985. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38986. })(BABYLON || (BABYLON = {}));
  38987. var BABYLON;
  38988. (function (BABYLON) {
  38989. var HDRCubeTexture = (function (_super) {
  38990. __extends(HDRCubeTexture, _super);
  38991. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace) {
  38992. if (noMipmap === void 0) { noMipmap = false; }
  38993. if (generateHarmonics === void 0) { generateHarmonics = true; }
  38994. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  38995. _super.call(this, scene);
  38996. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  38997. this._useInGammaSpace = false;
  38998. this._generateHarmonics = true;
  38999. this.sphericalPolynomial = null;
  39000. this.name = url;
  39001. this.url = url;
  39002. this._noMipmap = noMipmap;
  39003. this.hasAlpha = false;
  39004. this._size = size;
  39005. this._useInGammaSpace = useInGammaSpace;
  39006. if (!url) {
  39007. return;
  39008. }
  39009. this._texture = this._getFromCache(url, noMipmap);
  39010. if (!this._texture) {
  39011. if (!scene.useDelayedTextureLoading) {
  39012. this.loadTexture();
  39013. }
  39014. else {
  39015. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39016. }
  39017. }
  39018. this.isCube = true;
  39019. this._textureMatrix = BABYLON.Matrix.Identity();
  39020. }
  39021. HDRCubeTexture.prototype.loadTexture = function () {
  39022. var _this = this;
  39023. var callback = function (buffer) {
  39024. // Extract the raw linear data.
  39025. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  39026. // Generate harmonics if needed.
  39027. if (_this._generateHarmonics) {
  39028. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  39029. }
  39030. var results = [];
  39031. var byteArray = null;
  39032. // Create uintarray fallback.
  39033. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  39034. // 3 channels of 1 bytes per pixel in bytes.
  39035. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  39036. byteArray = new Uint8Array(byteBuffer);
  39037. }
  39038. // Push each faces.
  39039. for (var j = 0; j < 6; j++) {
  39040. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  39041. // If special cases.
  39042. if (_this._useInGammaSpace || byteArray) {
  39043. for (var i = 0; i < _this._size * _this._size; i++) {
  39044. // Put in gamma space if requested.
  39045. if (_this._useInGammaSpace) {
  39046. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  39047. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  39048. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  39049. }
  39050. // Convert to int texture for fallback.
  39051. if (byteArray) {
  39052. // R
  39053. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  39054. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  39055. // G
  39056. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  39057. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  39058. // B
  39059. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  39060. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  39061. }
  39062. }
  39063. }
  39064. results.push(dataFace);
  39065. }
  39066. return results;
  39067. };
  39068. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  39069. };
  39070. HDRCubeTexture.prototype.clone = function () {
  39071. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace);
  39072. // Base texture
  39073. newTexture.level = this.level;
  39074. newTexture.wrapU = this.wrapU;
  39075. newTexture.wrapV = this.wrapV;
  39076. newTexture.coordinatesIndex = this.coordinatesIndex;
  39077. newTexture.coordinatesMode = this.coordinatesMode;
  39078. return newTexture;
  39079. };
  39080. // Methods
  39081. HDRCubeTexture.prototype.delayLoad = function () {
  39082. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39083. return;
  39084. }
  39085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39086. this._texture = this._getFromCache(this.url, this._noMipmap);
  39087. if (!this._texture) {
  39088. this.loadTexture();
  39089. }
  39090. };
  39091. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  39092. return this._textureMatrix;
  39093. };
  39094. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39095. var texture = null;
  39096. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39097. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace);
  39098. texture.name = parsedTexture.name;
  39099. texture.hasAlpha = parsedTexture.hasAlpha;
  39100. texture.level = parsedTexture.level;
  39101. texture.coordinatesMode = parsedTexture.coordinatesMode;
  39102. }
  39103. return texture;
  39104. };
  39105. HDRCubeTexture.prototype.serialize = function () {
  39106. if (!this.name) {
  39107. return null;
  39108. }
  39109. var serializationObject = {};
  39110. serializationObject.name = this.name;
  39111. serializationObject.hasAlpha = this.hasAlpha;
  39112. serializationObject.isCube = true;
  39113. serializationObject.level = this.level;
  39114. serializationObject.size = this._size;
  39115. serializationObject.coordinatesMode = this.coordinatesMode;
  39116. serializationObject.useInGammaSpace = this._useInGammaSpace;
  39117. serializationObject.generateHarmonics = this._generateHarmonics;
  39118. return serializationObject;
  39119. };
  39120. HDRCubeTexture._facesMapping = [
  39121. "left",
  39122. "down",
  39123. "front",
  39124. "right",
  39125. "up",
  39126. "back"
  39127. ];
  39128. return HDRCubeTexture;
  39129. })(BABYLON.BaseTexture);
  39130. BABYLON.HDRCubeTexture = HDRCubeTexture;
  39131. })(BABYLON || (BABYLON = {}));
  39132. 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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#include<fresnelFunction>\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\n#include<reflectionFunction>\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#include<bumpFragmentFunctions>\r\n#include<clipPlaneFragmentDeclaration>\r\n#include<logDepthDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\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#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n#ifdef REFLECTIONOVERALPHA\r\n\talpha = clamp(alpha + dot(reflectionColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#include<logDepthFragment>\r\n#include<fogFragment>\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#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<pointCloudVertexDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<logDepthDeclaration>\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\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#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n#include<pointCloudVertex>\r\n#include<logDepthVertex>\r\n\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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#include<fresnelFunction>\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#include<clipPlaneFragmentDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\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#include<fogFragment>\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#include<bonesDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<bonesVertex>\r\n\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#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\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\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\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#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\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#include<fogVertexDeclaration>\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}"};
  39133. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2;var i=function(){function i(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 i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},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,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.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},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.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},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},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,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.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)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(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);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=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=n;var r=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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,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=r;var o=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 e(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),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,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,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},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),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=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=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=o.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/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),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*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=e;var h=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],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=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],d=t.m[1],g=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],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],S=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*S,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*S,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,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=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=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*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 e.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,c,y,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]=c,x.m[12]=y,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,c,y,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]=c,z.m[11]=y,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,\ni.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),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){e.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 s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,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,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.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,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=a?h/n:h,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=a?h:h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=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(c)},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 e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(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=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=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],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},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,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*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=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.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 o.Dot(n,i)+r},t}();t.Plane=a;var u=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=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(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=m;var c=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=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.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=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;var p=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,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-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=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=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=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-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 r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.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?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=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 o(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=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,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 r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}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.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=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]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.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 s;if(void 0===r||null===r){var e;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)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=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;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e: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;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,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=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.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=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  39134. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#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","bonesVertex":"#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\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","bumpFragmentFunctions":"#ifdef BUMP\r\n\tvarying vec2 vBumpUV;\r\n\tuniform vec2 vBumpInfos;\r\n\tuniform sampler2D bumpSampler;\r\n\r\n\t// Thanks to http://www.thetenthplanet.de/archives/1180\r\n\tmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n\t{\r\n\t\t// get edge vectors of the pixel triangle\r\n\t\tvec3 dp1 = dFdx(p);\r\n\t\tvec3 dp2 = dFdy(p);\r\n\t\tvec2 duv1 = dFdx(uv);\r\n\t\tvec2 duv2 = dFdy(uv);\r\n\r\n\t\t// solve the linear system\r\n\t\tvec3 dp2perp = cross(dp2, normal);\r\n\t\tvec3 dp1perp = cross(normal, dp1);\r\n\t\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\t\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t\t// construct a scale-invariant frame \r\n\t\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\t\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n\t}\r\n\r\n\tvec3 perturbNormal(vec3 viewDir)\r\n\t{\r\n\t\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\t\tmap = map * 255. / 127. - 128. / 127.;\r\n\t\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\t\treturn normalize(TBN * map);\r\n\t}\r\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t{\r\n\t\tdiscard;\r\n\t}\r\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\r\n\tvarying float fClipDistance;\r\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\r\n\tuniform vec4 vClipPlane;\r\n\tvarying float fClipDistance;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#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","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","fresnelFunction":"#ifdef FRESNEL\r\n\tfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n\t{\r\n\t\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\t\treturn clamp(fresnelTerm, 0., 1.);\r\n\t}\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// 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\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","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\r\n\tuniform float logarithmicDepthConstant;\r\n\tvarying float vFragmentDepth;\r\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif","pointCloudVertex":"#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\r\n\tuniform float pointSize;\r\n#endif","reflectionFunction":"vec3 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}","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\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\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  39135. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  39136. module.exports = BABYLON;
  39137. };